feat(slack): add gated managed setup alongside customer-owned apps

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-09 10:03:53 -05:00
1 parent 835a022936
commit 785ae16699
46 files changed
+4629 -783

No files matched your search

@@ -1,5 +1,6 @@
import { chatSlackRegistrations, toolOauthStates } from "@paperclipai/db";
import { buildSlackAppManifest } from "@paperclipai/shared";
import { chatSlackManagerGrants, chatSlackRegistrations, toolOauthStates } from "@paperclipai/db";
import type { PaperclipCloudConnector, SealedConnectorCredentials } from "../services/paperclip-cloud-connector.js";
import { buildSlackAppManifest, SLACK_MANAGER_SCOPES } from "@paperclipai/shared";
import { toolAccessService } from "../services/tool-access.js";
import { toolActionRequests, toolInvocations } from "@paperclipai/db";
import { GitHubPublicationLeaseLost, withGitHubPublicationLease } from "../services/chat-github-publication-lease.js";
@@ -4063,7 +4064,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
const token = `xoxb-bot-token-canary-${id}`;
const scopes = buildSlackAppManifest({ app: appDetails, agentName: "Maya", webhookUrl: "https://paperclip.example/hook" }).oauth_config.scopes.bot;
const state = {
failCreate: false, failValidate: false, failInventory: false, failAuth: false, failExchange: false,
managedBotAppId: appId, grantedScopes: scopes, managedError: null as string | null, failCreate: false, failValidate: false, failInventory: false, failAuth: false, failExchange: false,
failManifestUpdate: false, timeoutManifestUpdate: false,
beforeManifestUpdate: null as null | (() => Promise<void>),
failIcon: false, timeoutIcon: false, failUser: false, failWelcome: false, timeoutWelcome: false,
@@ -4076,15 +4077,17 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
const fallback = fakeSlackFetch(botId);
const provider = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input);
if (url.endsWith("bots.info")) return Response.json({ ok: true, bot: { id: "BMANAGED", app_id: state.managedBotAppId, user_id: botId, deleted: false } });
if (url.endsWith("apps.managedInstall")) return Response.json(state.managedError ? { ok: false, error: state.managedError } : { ok: true, app_id: appId, team_id: "TAUTO", api_access_tokens: { bot_access_token: token } });
if (url.endsWith("apps.manifest.validate")) return Response.json(state.failValidate ? { ok: false, error: "invalid_auth", detail: configToken } : { ok: true });
if (url.endsWith("apps.manifest.create")) {
if (state.failCreate) throw new Error(`Timeout ${configToken} ${clientSecret}`);
return Response.json({ ok: true, app_id: appId, credentials: { client_id: "123.456", client_secret: clientSecret, signing_secret: signingSecret } });
return Response.json({ ok: true, app_id: appId, team_id: "TAUTO", credentials: { client_id: "123.456", client_secret: clientSecret, signing_secret: signingSecret } });
}
if (url.endsWith("apps.manifest.update")) {
await state.beforeManifestUpdate?.();
if (state.timeoutManifestUpdate) throw new Error(`Manifest timeout ${configToken} ${clientSecret}`);
return Response.json(state.failManifestUpdate ? { ok: false, error: "invalid_auth", detail: configToken } : { ok: true, app_id: appId });
return Response.json(state.failManifestUpdate ? { ok: false, error: "invalid_auth", detail: configToken } : { ok: true, app_id: appId, permissions_updated: true });
}
if (url.endsWith("apps.icon.set")) {
await state.beforeIcon?.();
@@ -4098,7 +4101,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
if (url.endsWith("auth.test")) {
await state.beforeAuth?.();
if (state.failAuth) throw new Error(`Temporary failure ${token}`);
return Response.json({ ok: true, team_id: "TAUTO", user_id: botId, user: `maya-${id}`, team: "Test workspace" }, { headers: { "x-oauth-scopes": scopes.join(",") } });
return Response.json({ ok: true, team_id: "TAUTO", user_id: botId, bot_id: "BMANAGED", user: `maya-${id}`, team: "Test workspace" }, { headers: { "x-oauth-scopes": state.grantedScopes.join(",") } });
}
if (url.endsWith("users.info")) {
await state.beforeUser?.();
@@ -4124,6 +4127,190 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
const install = async () => new URL((await service.slackRegistration.install(endpoint.id, actor)).authorizationUrl).searchParams.get("state")!;
return { ...company, endpoint, service, sdk, app, state, provider, create, install, createInput, token, appId, botId, installerId, avatarBytes, renderAvatar };
}
async function managedFixture() {
const broker = {
getCapabilities: vi.fn(async () => ["slack.manager"]),
getSlackManagerAppId: vi.fn(async () => "AMANAGER"),
startAuthorization: vi.fn(async (_input: { returnState: string }) => ({ authorizationUrl: "https://slack.com/oauth/v2/authorize?state=broker", expiresAt: new Date(Date.now() + 600_000).toISOString() })),
claim: vi.fn(), refresh: vi.fn(), revoke: vi.fn(async () => undefined),
};
const f = await fixture({ slackManaged: { enabled: true, broker: broker as unknown as PaperclipCloudConnector } });
const credentials: SealedConnectorCredentials = { v: 1, provider: "slack", profile: "slack.manager", instanceId: "test", environment: "staging", subject: actor.userId, companyId: f.companyId,
accessToken: "xoxe.xoxp-manager-access-canary", refreshToken: "xoxe-manager-refresh-canary", tokenType: "user", accessTokenExpiresAt: new Date(Date.now() + 43_200_000).toISOString(), refreshTokenExpiresAt: null,
scopes: [...SLACK_MANAGER_SCOPES], slackManager: { appId: "AMANAGER", workspaceId: "TAUTO", workspaceName: "Test workspace", userId: f.installerId } };
broker.claim.mockResolvedValue(credentials);
broker.refresh.mockResolvedValue({ ...credentials, accessToken: "xoxe.rotated-canary", refreshToken: "xoxe.rotated-refresh-canary" });
await f.service.update(f.endpoint.id, { slackSetupMethod: "managed" }, actor.userId);
const grants = f.service.slackRegistration.managerGrants;
const authorize = async () => { await grants.authorize(f.endpoint.id, actor); return broker.startAuthorization.mock.calls.at(-1)![0].returnState; };
const authorizeState = await authorize();
await grants.complete(authorizeState, "claim-canary", null, actor);
const choices = await grants.choices(f.companyId, actor);
expect(choices.workspaces).toHaveLength(1);
const grantId = choices.workspaces[0]!.grantId;
const input = { requestId: randomUUID(), grantId };
const provision = () => f.service.slackRegistration.managed.provision(f.endpoint.id, actor, input);
return { ...f, broker, credentials, grants, authorize, authorizeState, grantId, input, provision };
}
describe("managed Slack", () => {
it("keeps open-source setup independent of the broker", async () => {
const f = await fixture();
expect(await f.service.slackRegistration.managerGrants.choices(f.companyId, actor)).toEqual({ managedAvailable: false, defaultMethod: "automatic", workspaces: [] });
await f.create();
expect((await f.service.get(f.endpoint.id)).setup.slackSetupMethod).toBe("automatic");
await expect(f.service.update(f.endpoint.id, { slackSetupMethod: "managed" }, actor.userId)).rejects.toThrow();
});
it("creates and installs once, uploads the avatar and links only the manager grant owner", async () => {
const f = await managedFixture();
await Promise.all([f.provision(), f.provision()]);
const saved = await f.service.get(f.endpoint.id);
expect(saved.setup).toMatchObject({ slackSetupMethod: "managed", slackRegistration: { status: "configured", appId: f.appId }, slackAvatar: { status: "uploaded" }, slackAccount: { status: "linked", paperclipUserId: actor.userId, externalUserId: f.installerId } });
expect(f.provider.mock.calls.filter(([url]) => String(url).endsWith("apps.manifest.create"))).toHaveLength(1);
expect(f.provider.mock.calls.filter(([url]) => String(url).endsWith("apps.managedInstall"))).toHaveLength(1);
const activities = await db.select().from(activityLog).where(eq(activityLog.companyId, f.companyId));
for (const secret of [f.credentials.accessToken, f.credentials.refreshToken!, f.token, clientSecret, signingSecret, "claim-canary"]) expect(JSON.stringify({ saved, activities, choices: await f.grants.choices(f.companyId, actor) })).not.toContain(secret);
await expect(f.service.update(f.endpoint.id, { slackSetupMethod: "automatic" }, actor.userId)).rejects.toThrow();
});
it("reuses the same personal workspace grant for another draft without another authorization", async () => {
const f = await managedFixture();
const draft = await f.service.create(f.companyId, { provider: "slack", assignedAgentId: f.assignedAgentId, slackSetupMethod: "managed" }, actor.userId);
expect((await f.grants.choices(f.companyId, actor)).workspaces[0]!.grantId).toBe(f.grantId);
const otherActor = { ...actor, userId: "another-user", bypassPermissionCheck: true };
expect((await f.grants.choices(f.companyId, otherActor)).workspaces).toEqual([]);
await expect(f.service.slackRegistration.managed.provision(draft.id, otherActor, { ...f.input, requestId: randomUUID() })).rejects.toThrow();
expect(f.broker.startAuthorization).toHaveBeenCalledTimes(1);
});
it("installs a second bot using the same grant without new manager consent", async () => {
const f = await managedFixture(); await f.provision();
const secondBot = "USECONDMANAGED";
const secondApp = "ASECONDMANAGED";
const scopes = buildSlackAppManifest({ app: appDetails, agentName: "Maya", webhookUrl: "https://paperclip.example/hook" }).oauth_config.scopes.bot;
const provider: typeof fetch = async (input, init) => {
const url = String(input);
if (url.endsWith("apps.manifest.create")) return Response.json({ ok: true, app_id: secondApp, team_id: "TAUTO", credentials: { client_id: "222.333", client_secret: clientSecret, signing_secret: signingSecret } });
if (url.endsWith("apps.managedInstall")) return Response.json({ ok: true, app_id: secondApp, team_id: "TAUTO", api_access_tokens: { bot_access_token: "xoxb-second-managed" } });
if (url.endsWith("auth.test")) return Response.json({ ok: true, team_id: "TAUTO", user_id: secondBot, bot_id: "BSECOND", team: "Test workspace" }, { headers: { "x-oauth-scopes": scopes.join(",") } });
if (url.endsWith("bots.info")) return Response.json({ ok: true, bot: { id: "BSECOND", app_id: secondApp, user_id: secondBot, deleted: false } });
return f.provider(input, init);
};
const { service } = createService(new FakeChatSdkRuntime(), provider, { renderSlackAvatar: f.renderAvatar, slackManaged: { enabled: true, broker: f.broker as unknown as PaperclipCloudConnector } });
const second = await service.create(f.companyId, { provider: "slack", assignedAgentId: f.assignedAgentId, slackSetupMethod: "managed", slackApp: appDetails }, actor.userId);
await service.slackRegistration.managed.provision(second.id, actor, { grantId: f.grantId, requestId: randomUUID() });
expect((await service.get(second.id)).setup.slackRegistration).toMatchObject({ status: "configured", appId: secondApp });
expect(f.broker.startAuthorization).toHaveBeenCalledTimes(1);
expect(f.broker.claim).toHaveBeenCalledTimes(1);
});
it("rejects missing tool scopes before activating a managed bot", async () => {
const f = await managedFixture(); f.state.grantedScopes = [];
await f.provision();
const saved = await f.service.get(f.endpoint.id);
expect(saved.providerAccountId).toBeNull();
expect(saved.setup.slackRegistration).toMatchObject({ status: "credentials_saved", errorCode: "slack_install_scopes_missing" });
});
it("claims concurrent manager callbacks once", async () => {
const f = await managedFixture(); const state = await f.authorize();
const results = await Promise.allSettled([1, 2].map(() => f.grants.complete(state, "claim", null, actor)));
expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1);
expect(f.broker.claim).toHaveBeenCalledTimes(2);
});
it("atomically consumes manager state and rejects wrong actors and expired attempts", async () => {
const f = await managedFixture();
await expect(f.grants.complete(f.authorizeState, "replay", null, actor)).rejects.toThrow();
const state = await f.authorize();
await expect(f.grants.complete(state, "claim", null, { ...actor, userId: "another-user", bypassPermissionCheck: true })).rejects.toThrow();
await db.update(toolOauthStates).set({ expiresAt: new Date(0) }).where(eq(toolOauthStates.state, state));
await expect(f.grants.complete(state, "claim", null, actor)).rejects.toThrow();
expect(f.broker.claim).toHaveBeenCalledTimes(1);
});
it("preserves declined manager authorization as a safe recoverable outcome", async () => {
const f = await managedFixture();
await f.grants.complete(await f.authorize(), null, "access_denied", actor);
expect((await f.service.get(f.endpoint.id)).setup.slackManagerError).toBe("slack_install_declined");
});
it("resumes saved installation credentials after inventory failure without creating or reinstalling", async () => {
const f = await managedFixture(); f.state.failInventory = true;
await f.provision();
expect((await f.service.slackRegistration.registration(f.endpoint.id))?.status).toBe("credentials_saved");
f.state.failInventory = false; await f.provision();
expect((await f.service.get(f.endpoint.id)).setup.slackRegistration?.status).toBe("configured");
expect(f.provider.mock.calls.filter(([url]) => String(url).endsWith("apps.managedInstall"))).toHaveLength(1);
expect(f.provider.mock.calls.filter(([url]) => String(url).endsWith("apps.manifest.create"))).toHaveLength(1);
});
it("never recreates an uncertain app", async () => {
const f = await managedFixture(); f.state.failCreate = true;
await f.provision(); await f.provision();
expect((await f.service.get(f.endpoint.id)).setup.slackRegistration?.status).toBe("uncertain");
expect(f.provider.mock.calls.filter(([url]) => String(url).endsWith("apps.manifest.create"))).toHaveLength(1);
});
it("uses bound OAuth for approval fallback and rejects a different installer", async () => {
const f = await managedFixture(); f.state.managedError = "app_approval_request_eligible";
const result = await f.provision();
const state = new URL(result.authorization!.authorizationUrl).searchParams.get("state")!;
f.state.oauth.authed_user.id = "UOTHER";
await f.service.slackRegistration.complete(state, "code-canary", null, actor);
expect((await f.service.get(f.endpoint.id)).setup.slackRegistration?.errorCode).toBe("slack_install_identity_mismatch");
expect((await f.service.get(f.endpoint.id)).providerAccountId).toBeNull();
});
it("serializes refreshes across endpoints and never replays an ambiguous refresh", async () => {
const f = await managedFixture();
await db.update(chatSlackManagerGrants).set({ expiresAt: new Date(0) }).where(eq(chatSlackManagerGrants.id, f.grantId));
const tokens = await Promise.all([1, 2].map(() => f.grants.token(f.grantId, f.companyId, actor)));
expect(tokens.every(result => result.token === "xoxe.rotated-canary")).toBe(true);
expect(f.broker.refresh).toHaveBeenCalledTimes(1);
await db.update(chatSlackManagerGrants).set({ expiresAt: new Date(0) }).where(eq(chatSlackManagerGrants.id, f.grantId));
f.broker.refresh.mockRejectedValue(new Error("provider echoed manager-canary"));
await expect(f.grants.token(f.grantId, f.companyId, actor)).rejects.toThrow();
await expect(f.grants.token(f.grantId, f.companyId, actor)).rejects.toThrow();
expect(f.broker.refresh).toHaveBeenCalledTimes(2);
});
it("rejects a bot token belonging to a different Slack app before activation", async () => {
const f = await managedFixture(); f.state.managedBotAppId = "ADIFFERENT";
await f.provision();
const saved = await f.service.get(f.endpoint.id);
expect(saved.providerAccountId).toBeNull();
expect(saved.setup.slackRegistration).toMatchObject({ status: "credentials_saved", errorCode: "slack_install_identity_mismatch" });
});
it("rejects manager identity changes and both callback-origin and ingress-origin drift", async () => {
const f = await managedFixture(); const state = await f.authorize();
for (const change of [{ publicBaseUrl: "https://changed.example" }, { webhookPublicBaseUrl: "https://changed.example" }]) {
const changed = createService(new FakeChatSdkRuntime(), f.provider, { ...change, slackManaged: { enabled: true, broker: f.broker as unknown as PaperclipCloudConnector } }).service;
await expect(changed.slackRegistration.managerGrants.complete(state, "claim", null, actor)).rejects.toThrow();
}
f.broker.getSlackManagerAppId.mockResolvedValue("ANEWMANAGER");
await expect(f.provision()).rejects.toThrow();
expect((await f.grants.choices(f.companyId, actor)).workspaces).toEqual([]);
});
it("preserves provider rate-limit backoff across subsequent attempts", async () => {
const f = await managedFixture(); f.state.managedError = "ratelimited";
await f.provision();
f.state.managedError = null; await f.provision();
expect(f.provider.mock.calls.filter(([url]) => String(url).endsWith("apps.managedInstall"))).toHaveLength(1);
expect((await f.service.get(f.endpoint.id)).setup.slackRegistration?.errorCode).toBe("slack_setup_rate_limited");
});
it("routes the broker claim_id callback back to the saved wizard without exposing the handoff", async () => {
const f = await managedFixture(); const state = await f.authorize();
const response = await request(f.app).get(`/api/chat-slack/managed/oauth/callback?state=${state}&claim_id=sealed-claim-canary`).set("accept", "application/json").expect(303);
expect(f.broker.claim.mock.calls.at(-1)![0].claimId).toBe("sealed-claim-canary");
expect(response.headers.location).toContain(f.endpoint.id);
expect(response.text).not.toContain("sealed-claim-canary");
expect(response.headers["cache-control"]).toBe("no-store");
});
it("does not accept another company's grant or keep authorizations after removal", async () => {
const f = await managedFixture(); const other = await seedCompany();
await expect(f.grants.token(f.grantId, other.companyId, { ...actor, bypassPermissionCheck: true })).rejects.toThrow();
const state = await f.authorize();
await f.service.configure(f.endpoint.id, { action: "remove" }, actor.userId);
await expect(f.grants.complete(state, "claim", null, actor)).rejects.toThrow();
expect((await f.grants.get(f.grantId, f.companyId, actor)).status).toBe("active");
});
it("revocation invalidates pending authorization and prevents future provisioning", async () => {
const f = await managedFixture(); const state = await f.authorize();
await f.grants.revoke(f.grantId, f.companyId, actor);
await expect(f.grants.complete(state, "claim", null, actor)).rejects.toThrow();
await expect(f.provision()).rejects.toThrow();
expect((await f.grants.choices(f.companyId, actor)).workspaces).toEqual([]);
});
});
function setupEvent(f: Awaited<ReturnType<typeof fixture>>, patch: Record<string, unknown> = {}, url = f.endpoint.setup.webhookUrl!, secret = signingSecret, timestamp?: string) {
return signedSlackWebhookRequest({ url, contentType: "application/json", signingSecret: secret, ...(timestamp ? { timestamp } : {}),
body: JSON.stringify({ type: "event_callback", api_app_id: f.appId, team_id: "TAUTO", event_id: "EvSETUP", event: {
+1 -1
View File
@@ -62,7 +62,7 @@ describe("isPrivateWebhookHttpRequest", () => {
describe("isSecretSensitiveHttpRequest", () => {
it("protects Slack registration, installation, recovery, and all callback methods", () => {
for (const suffix of ["registration", "install", "resume"]) expect(isSecretSensitiveHttpRequest("POST", `/api/chat-endpoints/id/slack/${suffix}`)).toBe(true);
for (const method of ["GET", "POST", "DELETE"]) for (const path of ["/api/chat-slack/oauth/callback?code=canary", "https://paperclip.test/API/CHAT-SLACK/OAUTH/callback?code=canary"])
for (const method of ["GET", "POST", "DELETE"]) for (const path of ["/api/chat-slack/oauth/callback?code=canary", "/api/chat-slack/managed/oauth/callback?claim=canary", "/api/chat-endpoints/endpoint/slack/managed/authorize", "/api/chat-endpoints/endpoint/slack/managed/provision", "https://paperclip.test/API/CHAT-SLACK/OAUTH/callback?code=canary"])
expect(isSecretSensitiveHttpRequest(method, path)).toBe(true);
});
it("identifies credential-bearing chat setup mutations", () => {
@@ -6,6 +6,11 @@ import {
stripSecretBearingUrlParts,
} from "../middleware/redact-sensitive.js";
it("redacts Slack manager grants and sealed OAuth handoffs", () => {
const result = redactSensitive({ managerToken: "manager-canary", refreshToken: "refresh-canary", sealed: { ct: "sealed-canary" }, handoff: { token: "handoff-canary" }, claim_id: "claim-canary" });
expect(JSON.stringify(result)).not.toContain("canary");
});
describe("redactSensitive", () => {
it("redacts a plaintext password field on a sign-in body", () => {
const body = {
+1 -1
View File
@@ -92,7 +92,7 @@ export function isSecretSensitiveHttpRequest(
// Avatar uploads and dedicated Dot MCP calls may contain private image bytes.
if (url && /^(?:\/mcp\/runner(?:\/|$)|\/api\/companies\/[^/]+\/agents\/[^/]+\/avatar(?:\/|$))/i.test(normalizePath(url).replace(/^https?:\/\/[^/]*/i, ""))) return true;
if (!method || !url) return false;
if (/^\/api\/chat-slack\/oauth(?:\/|$)/i.test(normalizePath(url).replace(/^https?:\/\/[^/]*/i, ""))) return true;
if (/^\/api\/chat-slack\/(?:managed\/)?oauth(?:\/|$)/i.test(normalizePath(url).replace(/^https?:\/\/[^/]*/i, ""))) return true;
if (/^\/api\/chat-endpoints\/[^/]+\/slack(?:\/|$)/i.test(normalizePath(url).replace(/^https?:\/\/[^/]*/i, ""))) return true;
if (!SECRET_SENSITIVE_HTTP_METHODS.has(method.toUpperCase())) return false;
const pathname = normalizePath(url);
@@ -16,6 +16,13 @@ const SENSITIVE_KEYS = new Set<string>([
// material under `credentials`. Redact the whole subtree instead of trying
// to keep an ever-changing allowlist of provider-specific field names in
// sync with every connector.
"sealed",
"handoff",
"claim",
"claimid",
"claim_id",
"managertoken",
"manager_token",
"configurationtoken",
"configuration_token",
"credential",
+43 -1
View File
@@ -1,4 +1,4 @@
import { slackRegistrationSchema, slackSetupActionSchema } from "@paperclipai/shared";
import { slackRegistrationSchema, slackSetupActionSchema, slackManagedProvisionSchema } from "@paperclipai/shared";
import { isCrossSiteOAuthCallbackNavigation, oauthCallbackInterstitialHtml } from "../lib/oauth-browser-return.js";
import {
Router,
@@ -151,6 +151,10 @@ export function chatChannelRoutes(db: Db, options: ChatChannelRouteOptions) {
async (req, res) => {
const companyId = req.params.companyId as string;
await assertConnectionManager(req, companyId);
if (req.body.provider === "slack" && !req.body.slackSetupMethod) {
req.body.slackSetupMethod = await service.slackRegistration.managerGrants.available() ? "managed" : "automatic";
}
if (req.body.slackSetupMethod === "managed" && !(await service.slackRegistration.managerGrants.available())) throw forbidden("Managed Slack setup is unavailable");
res
.status(201)
.json(await service.create(companyId, req.body, actorUserId(req)));
@@ -169,6 +173,44 @@ export function chatChannelRoutes(db: Db, options: ChatChannelRouteOptions) {
return { userId: actor.actorId, sessionId: actor.sessionId,
bypassPermissionCheck: req.actor.source === "local_implicit" || req.actor.isInstanceAdmin === true };
};
router.get("/companies/:companyId/chat-slack/setup-options", async (req, res) => {
const companyId = req.params.companyId as string;
await assertConnectionManager(req, companyId);
res.set("Cache-Control", "no-store");
res.json(await service.slackRegistration.managerGrants.choices(companyId, slackActor(req)));
});
router.post("/chat-endpoints/:endpointId/slack/managed/authorize", validate(slackSetupActionSchema), async (req, res) => {
if (!(await assertEndpointManagementAccess(req, res))) return;
res.set("Cache-Control", "no-store");
res.json(await service.slackRegistration.managerGrants.authorize(endpointId(req), slackActor(req)));
});
router.post("/chat-endpoints/:endpointId/slack/managed/provision", validate(slackManagedProvisionSchema), async (req, res) => {
if (!(await assertEndpointManagementAccess(req, res))) return;
res.set("Cache-Control", "no-store");
res.json(await service.slackRegistration.managed.provision(endpointId(req), slackActor(req), req.body));
});
router.delete("/companies/:companyId/chat-slack/manager-grants/:grantId", async (req, res) => {
const companyId = req.params.companyId as string;
await assertConnectionManager(req, companyId);
await service.slackRegistration.managerGrants.revoke(req.params.grantId as string, companyId, slackActor(req));
res.sendStatus(204);
});
router.get("/chat-slack/managed/oauth/callback", async (req, res) => {
res.set("Cache-Control", "no-store"); res.set("Referrer-Policy", "no-referrer");
const actor = slackActor(req);
const state = typeof req.query.state === "string" ? req.query.state : "";
const expiredId = await service.slackRegistration.managerGrants.expiredReturn(state, actor);
if (expiredId) { res.redirect(303, await service.slackRegistration.returnPath(expiredId)); return; }
const pending = await service.slackRegistration.managerGrants.pending(state, actor);
await assertConnectionManager(req, pending.current.endpoint.companyId);
if (req.get("accept")?.includes("text/html") && isCrossSiteOAuthCallbackNavigation(req)) {
res.type("html").send(oauthCallbackInterstitialHtml()); return;
}
const id = await service.slackRegistration.managerGrants.complete(state,
typeof req.query.claim_id === "string" ? req.query.claim_id : null,
typeof req.query.error === "string" ? req.query.error : null, actor);
res.redirect(303, await service.slackRegistration.returnPath(id));
});
router.post("/chat-endpoints/:endpointId/slack/registration", validate(slackRegistrationSchema), async (req, res) => {
if (!(await assertEndpointManagementAccess(req, res))) return;
res.set("Cache-Control", "no-store");
+30 -2
View File
@@ -1,4 +1,4 @@
import { slackRegistrationSchema, slackSetupActionSchema, slackInstallAuthorizationSchema, slackRegistrationStateSchema, slackAppConfigurationSchema, slackAvatarStateSchema, slackAccountStateSchema } from "@paperclipai/shared";
import { slackManagerAuthorizationSchema, slackSetupOptionsSchema, slackManagedProvisionSchema, slackManagedResultSchema, slackRegistrationSchema, slackSetupActionSchema, slackInstallAuthorizationSchema, slackRegistrationStateSchema, slackAppConfigurationSchema, slackAvatarStateSchema, slackAccountStateSchema } from "@paperclipai/shared";
import { experimentalApiMetadata } from "./experimental-api-metadata.js";
import {
experimentalApiPaths,
@@ -798,8 +798,9 @@ const chatAdapterCapabilitiesResponseSchema = z
const chatEndpointSetupResponseSchema = z
.object({
step: z.enum(["choose_agent", "provider_setup", "test", "complete"]),
slackSetupMethod: z.enum(["automatic", "manual", "existing"]).optional(),
slackSetupMethod: z.enum(["managed", "automatic", "manual", "existing"]).optional(),
slackRegistration: slackRegistrationStateSchema.optional(),
slackManagerError: z.string().optional(),
slackAvatar: slackAvatarStateSchema.optional(),
slackAccount: slackAccountStateSchema.optional(),
slackOAuthCallbackUri: z.string().nullable().optional(),
@@ -2475,6 +2476,33 @@ registry.registerPath({
},
});
registry.registerPath({
method: "get", path: "/api/companies/{companyId}/chat-slack/setup-options", tags: ["chat-channels"],
summary: "Discover Slack setup methods and the current user's authorized workspaces",
description: "Managed setup is advertised only for approved Cloud deployments with the broker profile enabled. Self-hosted discovery makes no hosted-service requests. Grants are personal and company scoped.",
request: { params: z.object({ companyId: z.string().uuid() }) }, responses: { 200: r.ok(slackSetupOptionsSchema), 401: r.unauthorized, 403: r.forbidden },
});
for (const action of ["authorize", "provision"] as const) registry.registerPath({
method: "post", path: `/api/chat-endpoints/{endpointId}/slack/managed/${action}`, tags: ["chat-channels"],
summary: action === "authorize" ? "Authorize a personal Slack manager workspace grant" : "Provision the saved managed Slack app",
description: "Requires the selected managed method, company membership, connection-management permission and Cloud availability. Authorization state is actor/session bound and single use. Provisioning accepts a personal grant ID and idempotent creation request ID; no provider credentials or arbitrary manifests are accepted.",
request: { params: z.object({ endpointId: z.string().uuid() }), body: jsonBody(action === "authorize" ? slackSetupActionSchema : slackManagedProvisionSchema) },
responses: { 200: r.ok(action === "authorize" ? slackManagerAuthorizationSchema : slackManagedResultSchema), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict, 422: r.unprocessable },
});
registry.registerPath({
method: "delete", path: "/api/companies/{companyId}/chat-slack/manager-grants/{grantId}", tags: ["chat-channels"],
summary: "Revoke the current user's workspace grant for future managed provisioning",
description: "Removes local manager credentials and invalidates pending manager authorization. Installed bots remain connected; this does not uninstall Slack apps.",
request: { params: z.object({ companyId: z.string().uuid(), grantId: z.string().uuid() }) }, responses: { 204: { description: "Personal manager grant revoked" }, 401: r.unauthorized, 403: r.forbidden },
});
registry.registerPath({
method: "get", path: "/api/chat-slack/managed/oauth/callback", tags: ["chat-channels"],
summary: "Redeem a sealed manager authorization and return to Slack setup",
description: "Authenticated, same-origin continuation with company, actor, session, endpoint revision and configured-origin checks. The broker handoff is single use; credentials are never returned to the browser.",
request: { query: z.object({ state: z.string(), claim_id: z.string().optional(), error: z.string().optional() }) },
responses: { 200: { description: "Same-origin continuation page" }, 303: { description: "Return to saved setup" }, 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 409: r.conflict },
});
for (const action of ["registration", "install", "resume"] as const) {
registry.registerPath({
method: "post", path: `/api/chat-endpoints/{endpointId}/slack/${action}`, tags: ["chat-channels"],
+13 -8
View File
@@ -1,3 +1,4 @@
import { isProvisionedSlackSetup } from "@paperclipai/shared";
import { chatCredentialMutationLease, CREDENTIAL_MUTATION_LEASE_TTL_MS, type CredentialMutationLeaseGuard } from "./chat-credential-mutation-lease.js";
import type { AgentAvatarRequest } from "./agent-avatars.js";
import { slackChatRegistrationService, slackRegistrationProjection } from "./chat-slack-registration.js";
@@ -1527,6 +1528,7 @@ export interface ChatChannelServiceOptions {
claimId: string;
}) => Promise<void>;
renderSlackAvatar?: (request: AgentAvatarRequest) => Promise<Buffer>;
slackManaged?: import("./connectors/slack/setup/registration.js").SlackSetupOptions["managed"];
storage?: StorageService;
}
@@ -2678,6 +2680,7 @@ function providerSetupState(
slackApp: endpoint.setup.slackApp,
slackSetupMethod: endpoint.setup.slackSetupMethod,
slackAvatar: endpoint.setup.slackAvatar,
slackManagerError: endpoint.setup.slackManagerError,
slackAccount: endpoint.setup.slackAccount,
// Slack registers the slash command in the provider configuration.
// Keep that identity immutable when the assigned agent is renamed;
@@ -5923,7 +5926,8 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
actorUserId?: string | null,
) {
if ((input.provider as string) === "agentmail") throw badRequest("Use the email inbox setup API for AgentMail");
if (input.slackApp && input.provider !== "slack") throw unprocessable("Slack app details only apply to Slack connections");
if ((input.slackApp || input.slackSetupMethod) && input.provider !== "slack") throw unprocessable("Slack app details only apply to Slack connections");
if (input.slackSetupMethod === "managed" && !await slackRegistration.managerGrants.available()) throw conflict("Managed Slack setup is unavailable");
const agent = await db
.select({ id: agents.id, name: agents.name, status: agents.status })
.from(agents)
@@ -6034,7 +6038,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
step: "provider_setup",
...(input.provider === "slack"
? { slackApp: input.slackApp ?? defaultSlackAppConfiguration(agent.name),
command: (input.slackApp ?? defaultSlackAppConfiguration(agent.name)).command, slackSetupMethod: "automatic" }
command: (input.slackApp ?? defaultSlackAppConfiguration(agent.name)).command, slackSetupMethod: input.slackSetupMethod ?? "automatic" }
: {}),
},
});
@@ -6080,13 +6084,14 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
}
values.communicationInstructions = input.communicationInstructions;
}
if (input.slackSetupMethod === "managed" && !await slackRegistration.managerGrants.available()) throw conflict("Managed Slack setup is unavailable");
if (input.slackSetupMethod && (existing.endpoint.provider !== "slack" || existing.endpoint.botExternalId || existing.endpoint.status !== "draft")) {
throw conflict("Setup method can only change before connecting the app");
}
if (input.slackApp || input.slackSetupMethod) {
const [registration] = await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId));
if (registration && registration.status !== "failed") {
if (input.slackApp || input.slackSetupMethod === "automatic") throw conflict("Slack app details are locked after creation starts");
if (registration && (registration.managerGrantId || registration.status !== "failed")) {
if (registration.managerGrantId || input.slackSetupMethod === "managed" || input.slackApp || input.slackSetupMethod === "automatic") throw conflict("Slack app details are locked after creation starts");
// Manual recovery fences pending authorization under the same credential lease.
await slackRegistration.cleanup(endpointId, credentialLease);
}
@@ -9589,7 +9594,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
.then((rows) => rows[0] ?? null);
if (!current) throw notFound("Chat endpoint not found");
const observedSlackUrl = (current.setup as InternalSetupState).slackCallbackSurfaces?.events?.url;
const preserveSlackVerification = current.setup.slackSetupMethod === "automatic"
const preserveSlackVerification = isProvisionedSlackSetup(current.setup.slackSetupMethod)
&& (current.setup as InternalSetupState).slackVerificationSigningFingerprint === createHash("sha256").update(credentials.signingSecret ?? "").digest("hex")
&& Boolean(observedSlackUrl && slackCallbackMatchesPublicUrl(observedSlackUrl, `${getWebhookPublicBaseUrl()}/api/chat-webhooks/${endpoint.publicId}/slack`));
await tx
@@ -26600,7 +26605,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
.where(and(eq(toolConnections.id, current.connectionId), eq(toolConnections.companyId, current.companyId)));
if (!connection || connection.status === "archived") return new Response("ignored", { status: 200 });
let secret = (await resolveCredentialRefs(current, connection.refs.filter(ref => ref.configPath.replace(/^credentials\./, "") === "signingSecret"), tx)).signingSecret;
if (!secret && current.setup.slackSetupMethod === "automatic") {
if (!secret && isProvisionedSlackSetup(current.setup.slackSetupMethod)) {
const [registration] = await tx.select().from(chatSlackRegistrations)
.where(and(eq(chatSlackRegistrations.endpointId, current.id), eq(chatSlackRegistrations.companyId, current.companyId)));
if (registration?.status !== "removed" && registration?.secretIds.signingSecret) {
@@ -27149,7 +27154,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
// Recheck the signature under the current credential/runtime fence;
// an SDK acknowledgement alone is not authentication evidence.
let signingFingerprint: string | null = null;
if (!currentSetup.webhookVerifiedAt && currentSetup.slackSetupMethod === "automatic"
if (!currentSetup.webhookVerifiedAt && isProvisionedSlackSetup(currentSetup.slackSetupMethod)
&& callback.surface === "events" && !callback.isUrlVerification
&& slackCallbackMatchesPublicUrl(callback.url, `${getWebhookPublicBaseUrl()}/api/chat-webhooks/${current.publicId}/slack`)) {
const payload = JSON.parse(eventBody) as { type?: string; team_id?: string; api_app_id?: string; event_id?: string; event?: { type?: string } };
@@ -38132,7 +38137,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
}
const slackRegistration = slackChatRegistrationService(db, {
publicOrigin: getPublicBaseUrl, webhookOrigin: getWebhookPublicBaseUrl, fetch: fetchImpl, renderAvatar: options.renderSlackAvatar,
publicOrigin: getPublicBaseUrl, webhookOrigin: getWebhookPublicBaseUrl, fetch: fetchImpl, renderAvatar: options.renderSlackAvatar, managed: options.slackManaged,
withLock: async (endpointId, work) => {
const record = await endpointRecord(endpointId);
if (!record) throw notFound("Chat endpoint not found");
@@ -6,8 +6,11 @@ import type { CredentialMutationLeaseGuard } from "./chat-credential-mutation-le
// Keep generic connection removal independent of the registration service's
// authorization graph; access routes already load tool-access through the barrel.
export async function removeSlackRegistration(db: Db, endpointId: string, lease: CredentialMutationLeaseGuard) {
await lease.assertOwned();
const vault = secretService(db);
const [row] = await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId));
const [endpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpointId));
if (endpoint) await db.delete(toolOauthStates).where(and(eq(toolOauthStates.connectionId, endpoint.connectionId), like(toolOauthStates.state, "slack-manager.%")));
if (!row) return;
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ status: "removed", updatedAt: new Date() }).where(eq(chatSlackRegistrations.endpointId, endpointId));
@@ -16,4 +19,4 @@ export async function removeSlackRegistration(db: Db, endpointId: string, lease:
for (const id of Object.values(row.secretIds)) { await lease.assertOwned(); await vault.remove(id); }
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ secretIds: {} }).where(eq(chatSlackRegistrations.endpointId, endpointId));
}
}
+3 -511
View File
@@ -1,511 +1,3 @@
import { createAgentAvatarPool } from "./agent-avatar-pool.js";
import type { AgentAvatarRequest } from "./agent-avatars.js";
import { removeSlackRegistration } from "./chat-slack-registration-cleanup.js";
import { createHash, randomBytes } from "node:crypto";
import { and, eq, gt, inArray, like, sql } from "drizzle-orm";
import { agents, chatEndpoints, chatSlackRegistrations, companies, toolConnections, toolOauthStates, type Db } from "@paperclipai/db";
import { resolveAgentAppearance, buildSlackAppManifest, slackAppConfigurationSchema, slackRegistrationErrorMessage, type SlackRegistrationInput, type SlackRegistrationState, type SlackAvatarState, type SlackAccountState } from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { accessService } from "./access.js";
import { logActivity } from "./activity-log.js";
import { logger } from "../middleware/logger.js";
import { instanceSettingsService } from "./instance-settings.js";
import { secretService } from "./secrets.js";
import { writeConnectionCredential } from "./connection-credentials.js";
import type { CredentialMutationLeaseGuard } from "./chat-credential-mutation-lease.js";
export interface SlackSetupActor { userId: string; sessionId: string | null; bypassPermissionCheck: boolean }
type Registration = typeof chatSlackRegistrations.$inferSelect;
const prefix = "slack-install.";
const timeoutMs = 20_000;
const object = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
const providerFailure = (code: string) => unprocessable(slackRegistrationErrorMessage(code), { code });
const knownProviderErrors: Record<string, string> = {
invalid_auth: "slack_configuration_token_invalid", token_expired: "slack_configuration_token_invalid",
token_revoked: "slack_configuration_token_invalid", not_authed: "slack_configuration_token_invalid",
invalid_manifest: "slack_manifest_invalid", invalid_app: "slack_manifest_invalid",
ratelimited: "slack_setup_rate_limited", no_permission: "slack_setup_permission_denied",
missing_scope: "slack_setup_permission_denied", not_allowed_token_type: "slack_configuration_token_invalid",
};
export function slackRegistrationProjection(row: Registration): SlackRegistrationState {
return {
status: row.status === "creating" && Date.now() - row.updatedAt.getTime() > 60_000 ? "uncertain" : row.status,
appId: row.appId,
managementUrl: row.appId ? `https://api.slack.com/apps/${encodeURIComponent(row.appId)}` : "https://api.slack.com/apps",
errorCode: row.status === "creating" && Date.now() - row.updatedAt.getTime() > 60_000 ? "slack_creation_uncertain" : row.errorCode,
};
}
export function slackChatRegistrationService(db: Db, options: {
publicOrigin: () => string | null;
webhookOrigin: () => string | null;
fetch?: typeof fetch;
renderAvatar?: (request: AgentAvatarRequest) => Promise<Buffer>;
withLock: <T>(endpointId: string, work: (lease: CredentialMutationLeaseGuard) => Promise<T>) => Promise<T>;
runtimeSigningSecret: (endpointId: string) => Promise<string>;
runtimeBotToken: (endpointId: string) => Promise<string>;
canWelcome: (endpointId: string, account: SlackAccountState) => Promise<boolean>;
linkInstaller: (endpointId: string, user: Record<string, unknown>, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) => Promise<void>;
configure: (endpointId: string, credentials: Record<string, string>, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) => Promise<unknown>;
}) {
const fetchImpl = options.fetch ?? fetch;
const vault = secretService(db);
let avatarPool: ReturnType<typeof createAgentAvatarPool> | undefined;
function origin(value: string | null) {
if (!value) throw badRequest("Configure a public HTTPS URL before creating a Slack app");
const url = new URL(value);
if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash)
throw badRequest("Slack setup requires a configured public HTTPS origin");
return url.origin;
}
const callbackUri = () => `${origin(options.publicOrigin())}/api/chat-slack/oauth/callback`;
async function registration(endpointId: string) {
return (await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId)))[0];
}
async function endpoint(endpointId: string, actor: SlackSetupActor) {
if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) throw forbidden("Chat connectors are disabled");
const [row] = await db.select({ endpoint: chatEndpoints, connection: toolConnections, agentName: agents.name, agentAppearance: agents.appearance })
.from(chatEndpoints).innerJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId), eq(toolConnections.companyId, chatEndpoints.companyId)))
.innerJoin(agents, and(eq(agents.id, chatEndpoints.assignedAgentId), eq(agents.companyId, chatEndpoints.companyId)))
.where(and(eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "slack")));
if (!row || row.endpoint.status === "archived" || row.connection.status === "archived") throw notFound("Slack connection not found");
if (!actor.bypassPermissionCheck && !await accessService(db).hasPermission(row.endpoint.companyId, "user", actor.userId, "tools:manage_connections"))
throw forbidden("Missing permission: tools:manage_connections");
return row;
}
function assertOrigins(row: Registration, publicId: string) {
if (row.callbackUri !== callbackUri()) throw conflict("The Paperclip URL changed. Restore its configured address or update the Slack app and use manual setup.");
const expected = `${origin(options.webhookOrigin())}/api/chat-webhooks/${publicId}/slack`;
if (object(object(row.manifest.settings).event_subscriptions).request_url !== expected)
throw conflict("The Slack webhook address changed. Restore its configured address or update the Slack app and use manual setup.");
}
async function audit(row: Registration, actor: SlackSetupActor, action: string, code?: string) {
await logActivity(db, { companyId: row.companyId, actorType: "user", actorId: actor.userId,
action: `chat_slack.${action}`, entityType: "chat_endpoint", entityId: row.endpointId,
details: { endpointId: row.endpointId, appId: row.appId, ...(code ? { code } : {}) } });
}
async function api(method: string, fields: Record<string, string> | FormData, bearer?: string) {
const response = await fetchImpl(`https://slack.com/api/${method}`, {
method: "POST", redirect: "error", signal: AbortSignal.timeout(timeoutMs),
headers: { ...(fields instanceof FormData ? {} : { "content-type": "application/x-www-form-urlencoded" }), ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },
body: fields instanceof FormData ? fields : new URLSearchParams(fields),
});
const result = object(await response.json());
if (!response.ok || result.ok !== true) {
const code = knownProviderErrors[String(result.error)] ?? (response.status === 429 ? "slack_setup_rate_limited" : "slack_provider_failure");
throw providerFailure(code);
}
return result;
}
async function saveSecrets(row: Registration, values: Record<string, string>, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard,
patch: Partial<Registration> = {}, account?: SlackAccountState) {
await db.transaction(async tx => {
await lease.assertOwned(tx);
const current = (await tx.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, row.endpointId)).for("update"))[0];
if (!current || current.requestId !== row.requestId || current.status === "removed") throw conflict("Slack setup changed. Resume the saved connection.");
const ids = { ...current.secretIds };
for (const [key, value] of Object.entries(values)) {
const result = await writeConnectionCredential(tx, { companyId: row.companyId, connectionName: "Slack app registration",
configPath: `slack_registration.${key}`, label: key, value, actor: { userId: actor.userId },
...(ids[key] ? { existingRef: { secretId: ids[key], configPath: `slack_registration.${key}` } } : {}) });
ids[key] = result.secret.id;
}
await tx.update(chatSlackRegistrations).set({ ...patch, secretIds: ids, updatedAt: new Date() }).where(eq(chatSlackRegistrations.endpointId, row.endpointId));
if (account) {
const saved = (await tx.select().from(chatEndpoints).where(and(eq(chatEndpoints.id, row.endpointId), eq(chatEndpoints.companyId, row.companyId))).for("update"))[0];
if (!saved || saved.status === "archived") throw conflict("Slack setup changed");
// Reauthorization never changes an established personal account binding.
if (saved.setup.slackAccount?.status !== "linked") await tx.update(chatEndpoints).set({ setup: { ...saved.setup, slackAccount: account }, updatedAt: new Date() }).where(eq(chatEndpoints.id, row.endpointId));
}
await lease.assertOwned(tx);
});
}
async function readSecret(row: Registration, key: string) {
if (!row.secretIds[key]) throw conflict("Slack setup credentials are unavailable. Resume the saved connection.");
return vault.resolveSecretValue(row.companyId, row.secretIds[key], "latest", {
accessContext: { consumerType: "system", consumerId: `slack-registration:${row.endpointId}`, configPath: `slack_registration.${key}`, actorType: "system" },
});
}
async function setFailure(row: Registration, status: Registration["status"], code: string, lease: CredentialMutationLeaseGuard) {
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ status, errorCode: code, updatedAt: new Date() })
.where(and(eq(chatSlackRegistrations.endpointId, row.endpointId), eq(chatSlackRegistrations.requestId, row.requestId)));
}
async function saveAvatar(row: Registration, avatar: SlackAvatarState, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
await endpoint(row.endpointId, actor);
await db.transaction(async tx => {
await lease.assertOwned(tx);
const current = (await tx.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, row.endpointId)).for("update"))[0];
if (!current || current.requestId !== row.requestId || current.status === "removed") throw conflict("Slack setup changed. Resume the saved connection.");
const saved = (await tx.select().from(chatEndpoints).where(and(eq(chatEndpoints.id, row.endpointId), eq(chatEndpoints.companyId, row.companyId))).for("update"))[0];
if (!saved || saved.status === "archived" || saved.setup.slackSetupMethod !== "automatic") throw conflict("Slack setup changed. Resume the saved connection.");
await tx.update(chatEndpoints).set({ setup: { ...saved.setup, slackAvatar: avatar }, updatedAt: new Date() })
.where(and(eq(chatEndpoints.id, row.endpointId), eq(chatEndpoints.companyId, row.companyId)));
await lease.assertOwned(tx);
});
}
async function create(endpointId: string, actor: SlackSetupActor, input: SlackRegistrationInput) {
return options.withLock(endpointId, async lease => {
const current = await endpoint(endpointId, actor);
const previous = await registration(endpointId);
if (previous?.status === "removed") throw conflict("This registration was removed. Continue the selected manual setup.");
if (previous?.appId) {
if (previous.errorCode === "slack_manifest_update_pending") {
await configureManifest(previous, actor, input.credentials.configurationToken, lease);
}
return;
}
if (previous?.requestId === input.requestId) return;
if (previous && ["creating", "uncertain"].includes(previous.status) && !input.confirmedNoAppCreated) {
await setFailure(previous, "uncertain", "slack_creation_uncertain", lease);
return;
}
if (current.endpoint.status !== "draft" || current.endpoint.botExternalId || current.endpoint.setup.slackSetupMethod !== "automatic")
throw conflict("Automatic creation is only available for a new Slack connection");
const app = slackAppConfigurationSchema.parse(current.endpoint.setup.slackApp);
const redirect = callbackUri();
const manifest = buildSlackAppManifest({ app, agentName: current.agentName,
webhookUrl: `${origin(options.webhookOrigin())}/api/chat-webhooks/${current.endpoint.publicId}/slack`, redirectUri: redirect });
// Slack cannot authenticate a challenge until its creation response gives us
// the signing secret. Add event subscriptions only after that secret is durable.
const { event_subscriptions: _events, ...creationSettings } = manifest.settings;
const creationManifest = { ...manifest, settings: creationSettings };
try { await api("apps.manifest.validate", { manifest: JSON.stringify(manifest) }, input.credentials.configurationToken); }
catch (error) {
if (error instanceof Error && "status" in error) throw error;
throw providerFailure("slack_provider_failure");
}
// No provider creation has happened until this intent is durable.
await endpoint(endpointId, actor);
await lease.assertOwned();
const values = { companyId: current.endpoint.companyId, requestId: input.requestId, status: "creating" as const,
manifest, manifestHash: createHash("sha256").update(JSON.stringify(manifest)).digest("hex"), callbackUri: redirect,
createdByUserId: actor.userId, errorCode: null, updatedAt: new Date() };
const [row] = await db.insert(chatSlackRegistrations).values({ endpointId, ...values })
.onConflictDoUpdate({ target: chatSlackRegistrations.endpointId, set: values }).returning();
await audit(row, actor, "creation_started");
let createdAppId: string;
try {
const result = await api("apps.manifest.create", { manifest: JSON.stringify(creationManifest) }, input.credentials.configurationToken);
const credentials = object(result.credentials);
if (typeof result.app_id !== "string" || !/^A[A-Z0-9]+$/.test(result.app_id)
|| typeof credentials.client_id !== "string" || !/^\d+\.\d+$/.test(credentials.client_id)
|| typeof credentials.client_secret !== "string" || !credentials.client_secret
|| typeof credentials.signing_secret !== "string" || !credentials.signing_secret)
throw new Error("Incomplete Slack creation response");
await endpoint(endpointId, actor);
await saveSecrets(row, { signingSecret: credentials.signing_secret, clientSecret: credentials.client_secret }, actor, lease,
{ appId: result.app_id, clientId: credentials.client_id, status: "install", errorCode: "slack_manifest_update_pending" });
createdAppId = result.app_id;
} catch (error) {
// Only documented rejection responses prove that creation did not happen.
const code = object(object(error).details).code;
const rejected = typeof code === "string" && Object.values(knownProviderErrors).includes(code);
await setFailure(row, rejected ? "failed" : "uncertain", rejected ? code : "slack_creation_uncertain", lease);
await audit(row, actor, "creation_failed", rejected ? code : "slack_creation_uncertain");
return;
}
// The app and credentials are durable before optional icon provisioning.
// A retry/restart always reuses this app, even if icon upload is interrupted.
const created = { ...row, appId: createdAppId };
if (!await configureManifest(created, actor, input.credentials.configurationToken, lease)) return;
await saveAvatar(created, { status: "pending" }, actor, lease);
let avatar: SlackAvatarState;
try {
await endpoint(endpointId, actor);
await lease.assertOwned();
// Cloud ingress requires a tenant session. Send the preset PNG bytes so
// Slack does not need to fetch an authenticated Paperclip URL.
const render = options.renderAvatar ?? (avatarPool ??= createAgentAvatarPool()).render;
const appearance = { ...resolveAgentAppearance(current.agentAppearance, current.endpoint.assignedAgentId) };
delete appearance.customAvatarAssetId; // The preset renderer cannot read private uploaded assets.
const png = await render({ appearance,
size: 512, scale: 1, pose: "rest", muted: false, background: "paperclip-dark" });
await endpoint(endpointId, actor);
await lease.assertOwned();
const upload = new FormData();
upload.set("app_id", createdAppId);
upload.set("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "agent-avatar.png");
await api("apps.icon.set", upload, input.credentials.configurationToken);
avatar = { status: "uploaded", uploadedAt: new Date().toISOString() };
} catch {
// Provider echoes (including tokens) never become saved state or activity.
avatar = { status: "failed", errorCode: "slack_avatar_upload_failed" };
}
await saveAvatar(created, avatar, actor, lease);
try { await audit(created, actor, avatar.status === "uploaded" ? "avatar_uploaded" : "avatar_upload_failed", avatar.status === "failed" ? avatar.errorCode : undefined); }
catch { logger.warn({ endpointId, appId: createdAppId }, "Slack avatar activity could not be recorded"); }
// An audit outage cannot change the saved creation outcome.
try { await audit({ ...row, appId: createdAppId }, actor, "app_created"); }
catch { logger.warn({ endpointId, appId: createdAppId }, "Slack app creation activity could not be recorded"); }
});
}
async function configureManifest(row: Registration, actor: SlackSetupActor, configurationToken: string, lease: CredentialMutationLeaseGuard) {
const current = await endpoint(row.endpointId, actor);
if (current.endpoint.status !== "draft" || current.endpoint.setup.slackSetupMethod !== "automatic")
throw conflict("Resume the saved Slack connection before configuring its app");
assertOrigins(row, current.endpoint.publicId);
await lease.assertOwned();
try {
await api("apps.manifest.update", { app_id: row.appId!, manifest: JSON.stringify(row.manifest) }, configurationToken);
} catch {
// The pending marker was saved with the app secrets before dispatch. Retrying
// the same manifest is safe even when Slack's response was lost.
await audit(row, actor, "manifest_update_failed", "slack_manifest_update_pending");
return false;
}
await endpoint(row.endpointId, actor);
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ errorCode: null, updatedAt: new Date() })
.where(and(eq(chatSlackRegistrations.endpointId, row.endpointId), eq(chatSlackRegistrations.requestId, row.requestId)));
await audit(row, actor, "manifest_updated");
return true;
}
async function install(endpointId: string, actor: SlackSetupActor) {
return options.withLock(endpointId, async lease => {
const current = await endpoint(endpointId, actor);
const row = await registration(endpointId);
if (!row?.appId || !row.clientId || row.status === "removed") throw conflict("Create this Slack app before installing it");
if (row.errorCode === "slack_manifest_update_pending") throw conflict("Finish configuring the saved Slack app before installing it");
if (current.endpoint.setup.slackSetupMethod !== "automatic" || current.endpoint.status === "paused") throw conflict("Resume this connection before installing it");
assertOrigins(row, current.endpoint.publicId);
const state = `${prefix}${randomBytes(32).toString("base64url")}`;
const expiresAt = new Date(Date.now() + 10 * 60_000);
const scopes = object(object(row.manifest.oauth_config).scopes).bot as string[];
await db.transaction(async tx => {
await lease.assertOwned(tx);
await tx.delete(toolOauthStates).where(and(eq(toolOauthStates.connectionId, current.connection.id), like(toolOauthStates.state, `${prefix}%`)));
await tx.insert(toolOauthStates).values({ state, companyId: row.companyId, connectionId: current.connection.id,
codeVerifier: JSON.stringify({ endpointId, requestId: row.requestId, appId: row.appId, callbackUri: row.callbackUri,
endpointStatus: current.endpoint.status, runtimeGeneration: object(current.endpoint.setup).runtimeGeneration ?? 0 }),
createdByActorType: "user", createdByActorId: actor.userId, createdBySessionId: actor.sessionId,
requestedScopes: scopes, expiresAt });
await tx.update(chatSlackRegistrations).set({ errorCode: null, updatedAt: new Date() }).where(eq(chatSlackRegistrations.endpointId, endpointId));
});
const url = new URL("https://slack.com/oauth/v2/authorize");
url.search = new URLSearchParams({ client_id: row.clientId, scope: scopes.join(","), state, redirect_uri: row.callbackUri,
...(row.workspaceId ? { team: row.workspaceId } : {}) }).toString();
await audit(row, actor, "installation_started");
return { authorizationUrl: url.toString(), expiresAt: expiresAt.toISOString() };
});
}
async function expiredReturn(state: string, actor: SlackSetupActor) {
if (!/^slack-install\.[A-Za-z0-9_-]{43}$/.test(state)) return null;
const [attempt] = await db.select().from(toolOauthStates).where(eq(toolOauthStates.state, state));
if (!attempt || attempt.expiresAt.getTime() > Date.now() || attempt.createdByActorId !== actor.userId || attempt.createdBySessionId !== actor.sessionId) return null;
const binding = object(JSON.parse(attempt.codeVerifier));
const current = await endpoint(String(binding.endpointId), actor);
return options.withLock(current.endpoint.id, async lease => {
const latest = await endpoint(current.endpoint.id, actor);
const row = await registration(current.endpoint.id);
if (!row || row.status === "removed" || row.requestId !== binding.requestId || row.companyId !== attempt.companyId || latest.connection.id !== attempt.connectionId
|| latest.endpoint.setup.slackSetupMethod !== "automatic" || row.appId !== binding.appId || row.callbackUri !== binding.callbackUri) return null;
assertOrigins(row, latest.endpoint.publicId);
await lease.assertOwned();
await db.delete(toolOauthStates).where(eq(toolOauthStates.state, state));
await setFailure(row, row.status, "slack_install_expired", lease);
await audit(row, actor, "installation_failed", "slack_install_expired");
return returnPath(row.endpointId);
});
}
async function pending(state: string, actor: SlackSetupActor) {
if (!/^slack-install\.[A-Za-z0-9_-]{43}$/.test(state)) throw badRequest("Invalid Slack authorization state");
const [attempt] = await db.select().from(toolOauthStates).where(and(eq(toolOauthStates.state, state), gt(toolOauthStates.expiresAt, new Date())));
if (!attempt || attempt.createdByActorId !== actor.userId || attempt.createdBySessionId !== actor.sessionId)
throw forbidden("Slack authorization expired or belongs to another session. Resume setup and install again.");
const binding = object(JSON.parse(attempt.codeVerifier));
const current = await endpoint(String(binding.endpointId), actor);
const row = await registration(current.endpoint.id);
if (!row || row.status === "removed" || current.endpoint.setup.slackSetupMethod !== "automatic"
|| current.endpoint.status === "paused"
|| current.endpoint.status === "revoked" && binding.endpointStatus !== "revoked"
|| binding.runtimeGeneration !== (object(current.endpoint.setup).runtimeGeneration ?? 0)
|| row.requestId !== binding.requestId || row.appId !== binding.appId || row.callbackUri !== binding.callbackUri
|| row.callbackUri !== callbackUri() || attempt.companyId !== row.companyId || attempt.connectionId !== current.connection.id)
throw conflict("Slack setup changed. Resume the saved connection and install again.");
assertOrigins(row, current.endpoint.publicId);
return { attempt, current, row };
}
async function saveAccount(row: Registration, account: SlackAccountState, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
await endpoint(row.endpointId, actor);
await db.transaction(async tx => {
await lease.assertOwned(tx);
const saved = (await tx.select().from(chatEndpoints).where(and(eq(chatEndpoints.id, row.endpointId), eq(chatEndpoints.companyId, row.companyId))).for("update"))[0];
const registrationNow = (await tx.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, row.endpointId)))[0];
if (!saved || saved.status === "archived" || registrationNow?.status === "removed" || registrationNow?.requestId !== row.requestId) throw conflict("Slack setup changed");
await tx.update(chatEndpoints).set({ setup: { ...saved.setup, slackAccount: account }, updatedAt: new Date() }).where(eq(chatEndpoints.id, row.endpointId));
await lease.assertOwned(tx);
});
}
async function linkAccount(row: Registration, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
const current = await endpoint(row.endpointId, actor);
const account = current.endpoint.setup.slackAccount;
if (!account) throw providerFailure("slack_install_account_missing");
if (account.status === "linked") return;
const token = row.secretIds.botToken ? await readSecret(row, "botToken") : await options.runtimeBotToken(row.endpointId);
const user = object((await api("users.info", { user: account.externalUserId }, token)).user);
if (user.id !== account.externalUserId || user.team_id !== row.workspaceId || user.is_bot !== false || user.is_app_user === true || user.deleted !== false) throw providerFailure("slack_install_account_missing");
await endpoint(row.endpointId, actor);
await options.linkInstaller(row.endpointId, user, { ...actor, userId: account.paperclipUserId }, lease);
await saveAccount(row, { ...account, status: "linked" }, actor, lease);
try { await audit(row, actor, "account_linked"); }
catch { logger.warn({ endpointId: row.endpointId, appId: row.appId }, "Slack account activity could not be recorded"); }
}
async function sendSetupMessage(row: Registration, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard, kind: "welcome" | "verification") {
const current = await endpoint(row.endpointId, actor);
const account = current.endpoint.setup.slackAccount;
if (!account || account.status !== "linked") return;
if (kind === "verification" && (!current.endpoint.setup.webhookVerifiedAt || ["pending", "sending"].includes(account.welcomeStatus))) return;
const field = kind === "welcome" ? "welcomeStatus" : "verificationStatus";
const status = account[field] ?? "pending";
if (status === "sending") {
await saveAccount(row, { ...account, [field]: "uncertain" }, actor, lease);
return; // Never replay an ambiguous dispatch after a process restart.
}
if (status !== "pending") return;
await saveAccount(row, { ...account, [field]: "sending" }, actor, lease);
let result: SlackAccountState;
try {
await endpoint(row.endpointId, actor);
await lease.assertOwned();
if (!await options.canWelcome(row.endpointId, account)) throw forbidden("Slack account access changed");
const sent = await api("chat.postMessage", { channel: account.dmChannelId ?? account.externalUserId,
text: kind === "verification" ? "Your Slack connection is working! Now ask me a question about your Paperclip instance."
: `Hi, I’m ${current.agentName}. Your Slack account is connected to Paperclip.`,
unfurl_links: "false", unfurl_media: "false" }, await options.runtimeBotToken(row.endpointId));
if (typeof sent.channel !== "string" || !/^D[A-Z0-9]+$/.test(sent.channel)) throw new Error("Incomplete message response");
result = { ...account, [field]: "sent", dmChannelId: sent.channel };
} catch (error) {
result = { ...account, [field]: error instanceof Error && "status" in error ? "failed" : "uncertain" };
}
await saveAccount(row, result, actor, lease);
try { await audit(row, actor, `${kind}_${result[field] === "sent" ? "sent" : "failed"}`); }
catch { logger.warn({ endpointId: row.endpointId, appId: row.appId }, "Slack setup message activity could not be recorded"); }
}
async function welcome(row: Registration, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
await sendSetupMessage(row, actor, lease, "welcome");
await sendSetupMessage(row, actor, lease, "verification");
}
async function notifyVerified(endpointId: string) {
return options.withLock(endpointId, async lease => {
const row = await registration(endpointId);
if (!row || row.status !== "configured") return;
const [saved] = await db.select({ setup: chatEndpoints.setup, status: chatEndpoints.status }).from(chatEndpoints).where(eq(chatEndpoints.id, endpointId));
const account = saved?.setup.slackAccount;
if (!account || !["verifying", "active"].includes(saved.status)) return;
await sendSetupMessage(row, { userId: account.paperclipUserId, sessionId: null, bypassPermissionCheck: false }, lease, "verification");
});
}
async function processPendingVerificationMessages(limit = 25) {
const pending = await db.select({ endpointId: chatEndpoints.id }).from(chatEndpoints)
.innerJoin(chatSlackRegistrations, and(eq(chatSlackRegistrations.endpointId, chatEndpoints.id), eq(chatSlackRegistrations.companyId, chatEndpoints.companyId)))
.where(and(eq(chatSlackRegistrations.status, "configured"), inArray(chatEndpoints.status, ["verifying", "active"]),
sql`${chatEndpoints.setup}->'slackAccount'->>'verificationStatus' in ('pending', 'sending')`)).limit(limit);
for (const row of pending) {
try { await notifyVerified(row.endpointId); }
catch { logger.warn({ endpointId: row.endpointId }, "Slack verification message could not be processed"); }
}
}
async function resumeLocked(endpointId: string, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
const current = await endpoint(endpointId, actor);
const row = await registration(endpointId);
if (!row || row.status === "removed") throw conflict("Slack registration is unavailable");
if (row.status === "configured") { await cleanupStaged(endpointId, lease); await welcome(row, actor, lease); return; }
if (row.status !== "credentials_saved") throw conflict("Install this Slack app before connecting it");
try {
assertOrigins(row, current.endpoint.publicId);
const botToken = await readSecret(row, "botToken");
const auth = await api("auth.test", {}, botToken);
if (auth.team_id !== row.workspaceId || auth.user_id !== row.botUserId) throw providerFailure("slack_install_identity_mismatch");
await options.configure(endpointId, { botToken, signingSecret: row.secretIds.signingSecret
? await readSecret(row, "signingSecret") : await options.runtimeSigningSecret(endpointId) }, actor, {
assertOwned: async database => {
await lease.assertOwned(database);
await endpoint(endpointId, actor);
assertOrigins(row, current.endpoint.publicId);
},
});
await linkAccount(row, actor, lease);
} catch (error) {
const code = object(object(error).details).code;
const safeCode = code === "slack_install_account_missing" ? code : code === "chat_identity_link_conflict" || code === "chat_identity_already_linked" ? "slack_install_account_conflict" : code === "slack_install_identity_mismatch" || code === "chat_bot_identity_changed"
? "slack_install_identity_mismatch" : code === "chat_provider_permissions_missing" ? "slack_install_scopes_missing"
: code === "chat_bot_identity_in_use" ? "slack_bot_already_connected" : "slack_configuration_incomplete";
await setFailure(row, "credentials_saved", safeCode, lease);
await audit(row, actor, "configuration_failed", safeCode);
return;
}
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ status: "configured", errorCode: null, updatedAt: new Date() }).where(eq(chatSlackRegistrations.endpointId, endpointId));
// Runtime now owns a separate vaulted copy. Keep the registration IDs until
// deletion succeeds so cleanup itself is retryable.
await cleanupStaged(endpointId, lease);
try { await audit(row, actor, "installation_completed"); }
catch { logger.warn({ endpointId, appId: row.appId }, "Slack installation activity could not be recorded"); }
await welcome(row, actor, lease);
}
async function cleanupStaged(endpointId: string, lease: CredentialMutationLeaseGuard) {
const row = await registration(endpointId);
if (!row || row.status !== "configured") return;
const ids = { ...row.secretIds };
for (const key of ["botToken", "signingSecret"]) {
if (ids[key]) { await lease.assertOwned(); await vault.remove(ids[key]); delete ids[key]; }
}
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ secretIds: ids }).where(eq(chatSlackRegistrations.endpointId, endpointId));
}
async function complete(state: string, code: string | null, error: string | null, actor: SlackSetupActor) {
const before = await pending(state, actor);
return options.withLock(before.row.endpointId, async lease => {
const { row, attempt, current } = await pending(state, actor);
const [claimed] = await db.delete(toolOauthStates).where(and(eq(toolOauthStates.state, state), gt(toolOauthStates.expiresAt, new Date()))).returning();
if (!claimed) throw conflict("This Slack authorization was already used");
if (error) {
const failureCode = error === "access_denied" ? "slack_install_declined" : "slack_install_failed";
await setFailure(row, row.status, failureCode, lease);
await audit(row, actor, "installation_failed", failureCode);
return row.endpointId;
}
try {
if (!code || code.length > 4096) throw providerFailure("slack_install_failed");
const result = await api("oauth.v2.access", { code, client_id: row.clientId!, client_secret: await readSecret(row, "clientSecret"), redirect_uri: row.callbackUri });
const teamId = object(result.team).id;
const installerId = object(result.authed_user).id;
if (result.app_id !== row.appId || result.token_type !== "bot" || typeof result.access_token !== "string" || !result.access_token.startsWith("xoxb-")
|| typeof teamId !== "string" || !/^T[A-Z0-9]+$/.test(teamId) || typeof result.bot_user_id !== "string" || !/^[UW][A-Z0-9]+$/.test(result.bot_user_id)
|| row.workspaceId && row.workspaceId !== teamId || row.botUserId && row.botUserId !== result.bot_user_id)
throw providerFailure("slack_install_identity_mismatch");
const granted = new Set(String(result.scope ?? "").split(","));
if ((attempt.requestedScopes ?? []).some(scope => !granted.has(scope))) throw providerFailure("slack_install_scopes_missing");
if (current.endpoint.providerAccountId && current.endpoint.providerAccountId !== teamId
|| current.endpoint.botExternalId && current.endpoint.botExternalId !== result.bot_user_id)
throw providerFailure("slack_install_identity_mismatch");
if (typeof installerId !== "string" || !/^[UW][A-Z0-9]+$/.test(installerId) || installerId === result.bot_user_id) throw providerFailure("slack_install_account_missing");
await endpoint(row.endpointId, actor);
// Reauthorization reuses the runtime signing secret after staging was cleaned.
await saveSecrets(row, { botToken: result.access_token }, actor, lease,
{ status: "credentials_saved", workspaceId: teamId, botUserId: result.bot_user_id, errorCode: null },
{ externalUserId: installerId, paperclipUserId: actor.userId, status: "pending", welcomeStatus: "pending" });
} catch (failure) {
const code = object(object(failure).details).code;
const safeCode = typeof code === "string" && code.startsWith("slack_install_") ? code : "slack_install_failed";
await setFailure(row, row.status, safeCode, lease);
await audit(row, actor, "installation_failed", safeCode);
return row.endpointId;
}
await resumeLocked(row.endpointId, actor, lease);
return row.endpointId;
});
}
const cleanup = (endpointId: string, lease: CredentialMutationLeaseGuard) => removeSlackRegistration(db, endpointId, lease);
async function returnPath(endpointId: string) {
const [row] = await db.select({ prefix: companies.issuePrefix }).from(chatEndpoints)
.innerJoin(companies, eq(companies.id, chatEndpoints.companyId)).where(eq(chatEndpoints.id, endpointId));
if (!row) throw notFound("Slack connection not found");
return `/${encodeURIComponent(row.prefix)}/apps/chat/connect?provider=slack&resume=${encodeURIComponent(endpointId)}`;
}
return { create, install, pending, expiredReturn, complete, cleanup, returnPath, registration, notifyVerified, processPendingVerificationMessages,
close: async () => { await avatarPool?.close(); },
resume: (endpointId: string, actor: SlackSetupActor) => options.withLock(endpointId, lease => resumeLocked(endpointId, actor, lease)) };
}
// Compatibility boundary: both provisioning paths converge on the same Slack runtime.
export { slackChatRegistrationService } from "./connectors/slack/setup/service.js";
export { slackRegistrationProjection, type SlackSetupActor } from "./connectors/slack/setup/registration.js";
@@ -0,0 +1,151 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import { chatEndpoints, chatSlackRegistrations } from "@paperclipai/db";
import { SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES, type SlackAccountState } from "@paperclipai/shared";
import { conflict, forbidden } from "../../../../errors.js";
import { logger } from "../../../../middleware/logger.js";
import { secretService } from "../../../secrets.js";
import type { CredentialMutationLeaseGuard } from "../../../chat-credential-mutation-lease.js";
import { object, providerFailure, type Registration, type SlackSetupActor, type SlackRegistrationStore } from "./registration.js";
export function createSlackCompletion(store: SlackRegistrationStore) {
const { db, options, endpoint, registration, assertOrigins, api, readSecret, audit, setFailure } = store;
const vault = secretService(db);
async function saveAccount(row: Registration, account: SlackAccountState, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
await endpoint(row.endpointId, actor);
await db.transaction(async tx => {
await lease.assertOwned(tx);
const saved = (await tx.select().from(chatEndpoints).where(and(eq(chatEndpoints.id, row.endpointId), eq(chatEndpoints.companyId, row.companyId))).for("update"))[0];
const registrationNow = (await tx.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, row.endpointId)))[0];
if (!saved || saved.status === "archived" || registrationNow?.status === "removed" || registrationNow?.requestId !== row.requestId) throw conflict("Slack setup changed");
await tx.update(chatEndpoints).set({ setup: { ...saved.setup, slackAccount: account }, updatedAt: new Date() }).where(eq(chatEndpoints.id, row.endpointId));
await lease.assertOwned(tx);
});
}
async function linkAccount(row: Registration, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
const current = await endpoint(row.endpointId, actor);
const account = current.endpoint.setup.slackAccount;
if (!account) throw providerFailure("slack_install_account_missing");
if (account.status === "linked") return;
const token = row.secretIds.botToken ? await readSecret(row, "botToken") : await options.runtimeBotToken(row.endpointId);
const user = object((await api("users.info", { user: account.externalUserId }, token)).user);
if (user.id !== account.externalUserId || user.team_id !== row.workspaceId || user.is_bot !== false || user.is_app_user === true || user.deleted !== false) throw providerFailure("slack_install_account_missing");
await endpoint(row.endpointId, actor);
await options.linkInstaller(row.endpointId, user, { ...actor, userId: account.paperclipUserId }, lease);
await saveAccount(row, { ...account, status: "linked" }, actor, lease);
try { await audit(row, actor, "account_linked"); }
catch { logger.warn({ endpointId: row.endpointId, appId: row.appId }, "Slack account activity could not be recorded"); }
}
async function sendSetupMessage(row: Registration, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard, kind: "welcome" | "verification") {
const current = await endpoint(row.endpointId, actor);
const account = current.endpoint.setup.slackAccount;
if (!account || account.status !== "linked") return;
if (kind === "verification" && (!current.endpoint.setup.webhookVerifiedAt || ["pending", "sending"].includes(account.welcomeStatus))) return;
const field = kind === "welcome" ? "welcomeStatus" : "verificationStatus";
const status = account[field] ?? "pending";
if (status === "sending") {
await saveAccount(row, { ...account, [field]: "uncertain" }, actor, lease);
return; // Never replay an ambiguous dispatch after a process restart.
}
if (status !== "pending") return;
await saveAccount(row, { ...account, [field]: "sending" }, actor, lease);
let result: SlackAccountState;
try {
await endpoint(row.endpointId, actor);
await lease.assertOwned();
if (!await options.canWelcome(row.endpointId, account)) throw forbidden("Slack account access changed");
const sent = await api("chat.postMessage", { channel: account.dmChannelId ?? account.externalUserId,
text: kind === "verification" ? "Your Slack connection is working! Now ask me a question about your Paperclip instance."
: `Hi, I’m ${current.agentName}. Your Slack account is connected to Paperclip.`,
unfurl_links: "false", unfurl_media: "false" }, await options.runtimeBotToken(row.endpointId));
if (typeof sent.channel !== "string" || !/^D[A-Z0-9]+$/.test(sent.channel)) throw new Error("Incomplete message response");
result = { ...account, [field]: "sent", dmChannelId: sent.channel };
} catch (error) {
result = { ...account, [field]: error instanceof Error && "status" in error ? "failed" : "uncertain" };
}
await saveAccount(row, result, actor, lease);
try { await audit(row, actor, `${kind}_${result[field] === "sent" ? "sent" : "failed"}`); }
catch { logger.warn({ endpointId: row.endpointId, appId: row.appId }, "Slack setup message activity could not be recorded"); }
}
async function welcome(row: Registration, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
await sendSetupMessage(row, actor, lease, "welcome");
await sendSetupMessage(row, actor, lease, "verification");
}
async function notifyVerified(endpointId: string) {
return options.withLock(endpointId, async lease => {
const row = await registration(endpointId);
if (!row || row.status !== "configured") return;
const [saved] = await db.select({ setup: chatEndpoints.setup, status: chatEndpoints.status }).from(chatEndpoints).where(eq(chatEndpoints.id, endpointId));
const account = saved?.setup.slackAccount;
if (!account || !["verifying", "active"].includes(saved.status)) return;
await sendSetupMessage(row, { userId: account.paperclipUserId, sessionId: null, bypassPermissionCheck: false }, lease, "verification");
});
}
async function processPendingVerificationMessages(limit = 25) {
const pending = await db.select({ endpointId: chatEndpoints.id }).from(chatEndpoints)
.innerJoin(chatSlackRegistrations, and(eq(chatSlackRegistrations.endpointId, chatEndpoints.id), eq(chatSlackRegistrations.companyId, chatEndpoints.companyId)))
.where(and(eq(chatSlackRegistrations.status, "configured"), inArray(chatEndpoints.status, ["verifying", "active"]),
sql`${chatEndpoints.setup}->'slackAccount'->>'verificationStatus' in ('pending', 'sending')`)).limit(limit);
for (const row of pending) {
try { await notifyVerified(row.endpointId); }
catch { logger.warn({ endpointId: row.endpointId }, "Slack verification message could not be processed"); }
}
}
async function resumeLocked(endpointId: string, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
const current = await endpoint(endpointId, actor);
const row = await registration(endpointId);
if (!row || row.status === "removed") throw conflict("Slack registration is unavailable");
if (row.status === "configured") { await cleanupStaged(endpointId, lease); await welcome(row, actor, lease); return; }
if (row.status !== "credentials_saved") throw conflict("Install this Slack app before connecting it");
try {
assertOrigins(row, current.endpoint.publicId);
const botToken = await readSecret(row, "botToken");
const auth = await api("auth.test", {}, botToken, row.managerGrantId ? [...SLACK_CHAT_BOT_SCOPES, ...SLACK_BOT_TOOL_SCOPES] : undefined);
if (auth.team_id !== row.workspaceId || row.botUserId && auth.user_id !== row.botUserId || typeof auth.user_id !== "string" || !/^[UW][A-Z0-9]+$/.test(auth.user_id)) throw providerFailure("slack_install_identity_mismatch");
if (row.managerGrantId) {
if (typeof auth.bot_id !== "string" || !/^B[A-Z0-9]+$/.test(auth.bot_id)) throw providerFailure("slack_install_identity_mismatch");
const bot = object((await api("bots.info", { bot: auth.bot_id }, botToken)).bot);
if (bot.id !== auth.bot_id || bot.app_id !== row.appId || bot.user_id !== auth.user_id || bot.deleted !== false) throw providerFailure("slack_install_identity_mismatch");
}
if (!row.botUserId) {
if (!row.managerGrantId) throw providerFailure("slack_install_identity_mismatch");
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ botUserId: auth.user_id }).where(eq(chatSlackRegistrations.endpointId, endpointId));
}
await options.configure(endpointId, { botToken, signingSecret: row.secretIds.signingSecret
? await readSecret(row, "signingSecret") : await options.runtimeSigningSecret(endpointId) }, actor, {
assertOwned: async database => {
await lease.assertOwned(database);
await endpoint(endpointId, actor);
assertOrigins(row, current.endpoint.publicId);
},
});
await linkAccount(row, actor, lease);
} catch (error) {
const code = object(object(error).details).code;
const safeCode = code === "slack_install_account_missing" ? code : code === "chat_identity_link_conflict" || code === "chat_identity_already_linked" ? "slack_install_account_conflict" : code === "slack_install_identity_mismatch" || code === "chat_bot_identity_changed"
? "slack_install_identity_mismatch" : (code === "chat_provider_permissions_missing" || code === "slack_install_scopes_missing") ? "slack_install_scopes_missing"
: code === "chat_bot_identity_in_use" ? "slack_bot_already_connected" : "slack_configuration_incomplete";
await setFailure(row, "credentials_saved", safeCode, lease);
await audit(row, actor, "configuration_failed", safeCode);
return;
}
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ status: "configured", errorCode: null, updatedAt: new Date() }).where(eq(chatSlackRegistrations.endpointId, endpointId));
// Runtime now owns a separate vaulted copy. Keep the registration IDs until
// deletion succeeds so cleanup itself is retryable.
await cleanupStaged(endpointId, lease);
try { await audit(row, actor, "installation_completed"); }
catch { logger.warn({ endpointId, appId: row.appId }, "Slack installation activity could not be recorded"); }
await welcome(row, actor, lease);
}
async function cleanupStaged(endpointId: string, lease: CredentialMutationLeaseGuard) {
const row = await registration(endpointId);
if (!row || row.status !== "configured") return;
const ids = { ...row.secretIds };
for (const key of ["botToken", "signingSecret"]) {
if (ids[key]) { await lease.assertOwned(); await vault.remove(ids[key]); delete ids[key]; }
}
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ secretIds: ids }).where(eq(chatSlackRegistrations.endpointId, endpointId));
}
return { resumeLocked, notifyVerified, processPendingVerificationMessages };
}
@@ -0,0 +1,134 @@
import { createHash } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { chatSlackRegistrations } from "@paperclipai/db";
import { resolveAgentAppearance, buildSlackAppManifest, slackAppConfigurationSchema, type SlackRegistrationInput, type SlackAvatarState } from "@paperclipai/shared";
import { conflict } from "../../../../errors.js";
import { logger } from "../../../../middleware/logger.js";
import type { CredentialMutationLeaseGuard } from "../../../chat-credential-mutation-lease.js";
import { object, knownProviderErrors, providerFailure, type Registration, type SlackSetupActor, type SlackRegistrationStore } from "./registration.js";
export function createCustomerOwnedSetup(store: SlackRegistrationStore) {
const { db, options, endpoint, registration, callbackUri, origin, api, audit, saveSecrets, setFailure, saveAvatar, assertOrigins, renderAvatar } = store;
async function create(endpointId: string, actor: SlackSetupActor, input: SlackRegistrationInput, managed?: { grantId: string; workspaceId: string; request: typeof api }) {
return options.withLock(endpointId, async lease => {
const api = managed?.request ?? store.api;
const current = await endpoint(endpointId, actor);
const previous = await registration(endpointId);
const method = managed ? "managed" : "automatic";
if (current.endpoint.setup.slackSetupMethod !== method) throw conflict("Resume the selected Slack setup method");
if (previous && previous.managerGrantId !== (managed?.grantId ?? null)) throw conflict("Resume setup with the original Slack workspace");
if (previous?.status === "removed") throw conflict("This registration was removed. Continue the selected manual setup.");
if (previous?.appId) {
if (previous.errorCode === "slack_manifest_update_pending") {
await configureManifest(previous, actor, input.credentials.configurationToken, lease, managed ? "managed" : "automatic", api);
}
return;
}
if (previous?.requestId === input.requestId) return;
if (previous && ["creating", "uncertain"].includes(previous.status) && !input.confirmedNoAppCreated) {
await setFailure(previous, "uncertain", "slack_creation_uncertain", lease);
return;
}
if (current.endpoint.status !== "draft" || current.endpoint.botExternalId || current.endpoint.setup.slackSetupMethod !== method)
throw conflict("Automatic creation is only available for a new Slack connection");
const app = slackAppConfigurationSchema.parse(current.endpoint.setup.slackApp);
const redirect = callbackUri();
const manifest = buildSlackAppManifest({ app, agentName: current.agentName,
webhookUrl: `${origin(options.webhookOrigin())}/api/chat-webhooks/${current.endpoint.publicId}/slack`, redirectUri: redirect });
// Slack cannot authenticate a challenge until its creation response gives us
// the signing secret. Add event subscriptions only after that secret is durable.
const { event_subscriptions: _events, ...creationSettings } = manifest.settings;
const creationManifest = { ...manifest, settings: creationSettings };
try { await api("apps.manifest.validate", { manifest: JSON.stringify(manifest) }, input.credentials.configurationToken); }
catch (error) {
if (error instanceof Error && "status" in error) throw error;
throw providerFailure("slack_provider_failure");
}
// No provider creation has happened until this intent is durable.
await endpoint(endpointId, actor);
await lease.assertOwned();
const values = { companyId: current.endpoint.companyId, requestId: input.requestId, status: "creating" as const,
manifest, manifestHash: createHash("sha256").update(JSON.stringify(manifest)).digest("hex"), callbackUri: redirect,
createdByUserId: actor.userId, managerGrantId: managed?.grantId ?? null, workspaceId: managed?.workspaceId ?? null, errorCode: null, updatedAt: new Date() };
const [row] = await db.insert(chatSlackRegistrations).values({ endpointId, ...values })
.onConflictDoUpdate({ target: chatSlackRegistrations.endpointId, set: values }).returning();
await audit(row, actor, "creation_started");
let createdAppId: string;
try {
const result = await api("apps.manifest.create", { manifest: JSON.stringify(creationManifest) }, input.credentials.configurationToken);
const credentials = object(result.credentials);
if (typeof result.app_id !== "string" || !/^A[A-Z0-9]+$/.test(result.app_id)
|| typeof credentials.client_id !== "string" || !/^\d+\.\d+$/.test(credentials.client_id)
|| typeof credentials.client_secret !== "string" || !credentials.client_secret
|| typeof credentials.signing_secret !== "string" || !credentials.signing_secret)
throw new Error("Incomplete Slack creation response");
if (managed && result.team_id !== managed.workspaceId) throw new Error("Slack creation workspace mismatch");
await endpoint(endpointId, actor);
await saveSecrets(row, { signingSecret: credentials.signing_secret, clientSecret: credentials.client_secret }, actor, lease,
{ appId: result.app_id, clientId: credentials.client_id, status: "install", errorCode: "slack_manifest_update_pending" });
createdAppId = result.app_id;
} catch (error) {
// Only documented rejection responses prove that creation did not happen.
const code = object(object(error).details).code;
const rejected = typeof code === "string" && [...Object.values(knownProviderErrors), "slack_manager_reauthorize"].includes(code);
await setFailure(row, rejected ? "failed" : "uncertain", rejected ? code : "slack_creation_uncertain", lease);
await audit(row, actor, "creation_failed", rejected ? code : "slack_creation_uncertain");
return;
}
// The app and credentials are durable before optional icon provisioning.
// A retry/restart always reuses this app, even if icon upload is interrupted.
const created = { ...row, appId: createdAppId };
if (!await configureManifest(created, actor, input.credentials.configurationToken, lease, method, api)) return;
await saveAvatar(created, { status: "pending" }, actor, lease);
let avatar: SlackAvatarState;
try {
await endpoint(endpointId, actor);
await lease.assertOwned();
// Cloud ingress requires a tenant session. Send the preset PNG bytes so
// Slack does not need to fetch an authenticated Paperclip URL.
const render = renderAvatar;
const appearance = { ...resolveAgentAppearance(current.agentAppearance, current.endpoint.assignedAgentId) };
delete appearance.customAvatarAssetId; // The preset renderer cannot read private uploaded assets.
const png = await render({ appearance,
size: 512, scale: 1, pose: "rest", muted: false, background: "paperclip-dark" });
await endpoint(endpointId, actor);
await lease.assertOwned();
const upload = new FormData();
upload.set("app_id", createdAppId);
upload.set("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "agent-avatar.png");
await api("apps.icon.set", upload, input.credentials.configurationToken);
avatar = { status: "uploaded", uploadedAt: new Date().toISOString() };
} catch {
// Provider echoes (including tokens) never become saved state or activity.
avatar = { status: "failed", errorCode: "slack_avatar_upload_failed" };
}
await saveAvatar(created, avatar, actor, lease);
try { await audit(created, actor, avatar.status === "uploaded" ? "avatar_uploaded" : "avatar_upload_failed", avatar.status === "failed" ? avatar.errorCode : undefined); }
catch { logger.warn({ endpointId, appId: createdAppId }, "Slack avatar activity could not be recorded"); }
// An audit outage cannot change the saved creation outcome.
try { await audit({ ...row, appId: createdAppId }, actor, "app_created"); }
catch { logger.warn({ endpointId, appId: createdAppId }, "Slack app creation activity could not be recorded"); }
});
}
async function configureManifest(row: Registration, actor: SlackSetupActor, configurationToken: string, lease: CredentialMutationLeaseGuard, method: "automatic" | "managed" = "automatic", api = store.api) {
const current = await endpoint(row.endpointId, actor);
if (current.endpoint.status !== "draft" || current.endpoint.setup.slackSetupMethod !== method)
throw conflict("Resume the saved Slack connection before configuring its app");
assertOrigins(row, current.endpoint.publicId);
await lease.assertOwned();
try {
await api("apps.manifest.update", { app_id: row.appId!, manifest: JSON.stringify(row.manifest) }, configurationToken);
} catch {
// The pending marker was saved with the app secrets before dispatch. Retrying
// the same manifest is safe even when Slack's response was lost.
await audit(row, actor, "manifest_update_failed", "slack_manifest_update_pending");
return false;
}
await endpoint(row.endpointId, actor);
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ errorCode: null, updatedAt: new Date() })
.where(and(eq(chatSlackRegistrations.endpointId, row.endpointId), eq(chatSlackRegistrations.requestId, row.requestId)));
await audit(row, actor, "manifest_updated");
return true;
}
return { create, configureManifest };
}
@@ -0,0 +1,54 @@
import { type SlackManagedProvisionInput, type SlackManagedResult } from "@paperclipai/shared";
import { conflict } from "../../../../errors.js";
import type { createCustomerOwnedSetup } from "./customer-owned.js";
import type { createSlackManagerGrants } from "./manager-grants.js";
import type { createSlackCompletion } from "./completion.js";
import { object, providerFailure, type SlackRegistrationStore, type SlackSetupActor } from "./registration.js";
/** Managed provisioning ends at the same saved-credential boundary as child OAuth. */
export function createManagedSlackSetup(store: SlackRegistrationStore, grants: ReturnType<typeof createSlackManagerGrants>,
provisioner: ReturnType<typeof createCustomerOwnedSetup>, completion: ReturnType<typeof createSlackCompletion>,
installFallback: (endpointId: string, actor: SlackSetupActor) => Promise<{ authorizationUrl: string; expiresAt: string }>) {
async function provision(endpointId: string, actor: SlackSetupActor, input: SlackManagedProvisionInput): Promise<SlackManagedResult> {
const current = await store.endpoint(endpointId, actor);
if (current.endpoint.setup.slackSetupMethod !== "managed") throw conflict("Resume the selected Slack setup method");
const authorized = await grants.token(input.grantId, current.endpoint.companyId, actor);
await provisioner.create(endpointId, actor, { requestId: input.requestId, confirmedNoAppCreated: input.confirmedNoAppCreated,
credentials: { configurationToken: authorized.token } }, { grantId: authorized.grant.id, workspaceId: authorized.grant.workspaceId, request: (method, fields) => grants.request(input.grantId, current.endpoint.companyId, actor, method, fields) });
let fallback = false;
await store.options.withLock(endpointId, async lease => {
const latest = await store.endpoint(endpointId, actor);
const row = await store.registration(endpointId);
if (!row?.appId || row.status === "removed" || row.errorCode === "slack_manifest_update_pending") return;
if (row.managerGrantId !== authorized.grant.id || latest.endpoint.setup.slackSetupMethod !== "managed") throw conflict("Slack setup changed");
store.assertOrigins(row, latest.endpoint.publicId);
if (row.status === "configured" || row.status === "credentials_saved") {
await completion.resumeLocked(endpointId, actor, lease);
return;
}
const { grant } = await grants.token(input.grantId, row.companyId, actor);
try {
await lease.assertOwned();
const result = await grants.request(grant.id, row.companyId, actor, "apps.managedInstall", { app_id: row.appId, team_id: grant.workspaceId });
const botToken = object(result.api_access_tokens).bot_access_token;
if (result.app_id !== row.appId || result.team_id !== grant.workspaceId || typeof botToken !== "string" || !botToken.startsWith("xoxb-")) throw providerFailure("slack_install_identity_mismatch");
if ((await grants.get(grant.id, row.companyId, actor)).status !== "active") throw providerFailure("slack_manager_reauthorize");
await store.endpoint(endpointId, actor);
// Vault before auth.test/inventory so network failures never lose this installation.
await store.saveSecrets(row, { botToken }, actor, lease, { status: "credentials_saved", workspaceId: grant.workspaceId, errorCode: null },
{ externalUserId: grant.slackUserId, paperclipUserId: actor.userId, status: "pending", welcomeStatus: "pending" });
} catch (error) {
const code = object(object(error).details).code;
const safe = typeof code === "string" ? code : "slack_install_failed";
await store.setFailure(row, row.status, safe, lease);
await store.audit(row, actor, "installation_failed", safe);
fallback = ["slack_approval_required", "slack_approval_pending", "slack_approval_denied"].includes(safe);
return;
}
await completion.resumeLocked(endpointId, actor, lease);
});
// OAuth's state/actor binding is ours; never trust a provider-supplied redirect.
return fallback ? { authorization: await installFallback(endpointId, actor) } : {};
}
return { provision };
}
@@ -0,0 +1,227 @@
import { randomBytes, randomUUID } from "node:crypto";
import { and, eq, gt, like, sql } from "drizzle-orm";
import { chatEndpoints, chatSlackManagerGrants, companySecrets, toolOauthStates } from "@paperclipai/db";
import { SLACK_MANAGER_SCOPES, type SlackSetupOptions as SetupChoices } from "@paperclipai/shared";
import { conflict, forbidden } from "../../../../errors.js";
import { getCloudRuntimeIdentity } from "../../../cloud-runtime-identity.js";
import { createPaperclipCloudConnector, paperclipCloudConnectorConfigFromEnv, type PaperclipCloudConnector, type SealedConnectorCredentials } from "../../../paperclip-cloud-connector.js";
import { instanceSettingsService } from "../../../instance-settings.js";
import { accessService } from "../../../access.js";
import { secretService } from "../../../secrets.js";
import { writeConnectionCredential } from "../../../connection-credentials.js";
import { logActivity } from "../../../activity-log.js";
import { object, providerFailure, type SlackRegistrationStore, type SlackSetupActor } from "./registration.js";
export const SLACK_MANAGER_STATE_PREFIX = "slack-manager.";
export function createSlackManagerGrants(store: SlackRegistrationStore) {
const { db, options, endpoint, origin, api } = store;
const vault = secretService(db);
function broker(): PaperclipCloudConnector | null {
if (options.managed) return options.managed.enabled ? options.managed.broker : null;
// Open-source instances never contact a hosted service to discover this path.
if (!getCloudRuntimeIdentity() || process.env.PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED !== "true") return null;
const config = paperclipCloudConnectorConfigFromEnv();
return config ? createPaperclipCloudConnector({ config }) : null;
}
async function access(companyId: string, actor: SlackSetupActor) {
if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) throw forbidden("Chat connectors are disabled");
if (!actor.bypassPermissionCheck && !await accessService(db).hasPermission(companyId, "user", actor.userId, "tools:manage_connections")) throw forbidden("Missing permission: tools:manage_connections");
}
async function available() {
const client = broker();
if (!client || !(await instanceSettingsService(db).getExperimental()).enableChatConnectors) return false;
try { origin(options.publicOrigin()); origin(options.webhookOrigin()); return Boolean(await client.getSlackManagerAppId()); }
catch { return false; }
}
async function requiredBroker() {
if (!await available()) throw providerFailure("slack_managed_unavailable");
return broker()!;
}
async function choices(companyId: string, actor: SlackSetupActor): Promise<SetupChoices> {
await access(companyId, actor);
const managedAvailable = await available();
const managerAppId = managedAvailable ? await broker()!.getSlackManagerAppId() : null;
const grants = managedAvailable && managerAppId ? await db.select().from(chatSlackManagerGrants).where(and(eq(chatSlackManagerGrants.companyId, companyId), eq(chatSlackManagerGrants.userId, actor.userId), eq(chatSlackManagerGrants.status, "active"), eq(chatSlackManagerGrants.managerAppId, managerAppId))) : [];
return { managedAvailable, defaultMethod: managedAvailable ? "managed" : "automatic", workspaces: grants.map(g => ({ grantId: g.id, workspaceId: g.workspaceId, workspaceName: g.workspaceName, userId: g.slackUserId })) };
}
const callbackUri = () => `${origin(options.publicOrigin())}/api/chat-slack/managed/oauth/callback`;
async function authorize(endpointId: string, actor: SlackSetupActor) {
const client = await requiredBroker();
return options.withLock(endpointId, async lease => {
const current = await endpoint(endpointId, actor);
if (current.endpoint.setup.slackSetupMethod !== "managed") throw conflict("Resume the selected Slack setup method");
const row = await store.registration(endpointId);
const revisions = await db.select({ id: chatSlackManagerGrants.id, revision: chatSlackManagerGrants.revision }).from(chatSlackManagerGrants)
.where(and(eq(chatSlackManagerGrants.companyId, current.endpoint.companyId), eq(chatSlackManagerGrants.userId, actor.userId)));
const state = `${SLACK_MANAGER_STATE_PREFIX}${randomBytes(32).toString("base64url")}`;
const expiresAt = new Date(Date.now() + 10 * 60_000);
await lease.assertOwned();
await db.insert(toolOauthStates).values({ state, companyId: current.endpoint.companyId, connectionId: current.connection.id,
codeVerifier: JSON.stringify({ endpointId, revisions, requestId: row?.requestId ?? null, callbackUri: callbackUri(), webhookOrigin: origin(options.webhookOrigin()), runtimeGeneration: object(current.endpoint.setup).runtimeGeneration ?? 0 }),
createdByActorType: "user", createdByActorId: actor.userId, createdBySessionId: actor.sessionId, requestedScopes: [...SLACK_MANAGER_SCOPES], expiresAt });
try { return await client.startAuthorization({ profile: "slack.manager", subject: actor.userId, companyId: current.endpoint.companyId, returnUri: callbackUri(), returnState: state }); }
catch { await db.delete(toolOauthStates).where(eq(toolOauthStates.state, state)); throw providerFailure("slack_manager_reauthorize"); }
});
}
async function pending(state: string, actor: SlackSetupActor, allowExpired = false) {
if (!/^slack-manager\.[A-Za-z0-9_-]{43}$/.test(state)) throw forbidden("Invalid Slack authorization state");
const [attempt] = await db.select().from(toolOauthStates).where(and(eq(toolOauthStates.state, state), ...(allowExpired ? [] : [gt(toolOauthStates.expiresAt, new Date())])));
if (!attempt || attempt.createdByActorId !== actor.userId || attempt.createdBySessionId !== actor.sessionId) throw forbidden("Slack authorization expired or belongs to another session");
const binding = object(JSON.parse(attempt.codeVerifier));
const current = await endpoint(String(binding.endpointId), actor);
const row = await store.registration(current.endpoint.id);
if (current.endpoint.setup.slackSetupMethod !== "managed" || current.connection.id !== attempt.connectionId || current.endpoint.companyId !== attempt.companyId
|| ["paused", "revoked"].includes(current.endpoint.status) || row?.status === "removed"
|| (row?.requestId ?? null) !== binding.requestId || binding.callbackUri !== callbackUri() || binding.webhookOrigin !== origin(options.webhookOrigin())
|| binding.runtimeGeneration !== (object(current.endpoint.setup).runtimeGeneration ?? 0)) throw conflict("Slack setup changed. Resume authorization.");
return { attempt, current, row, binding };
}
async function expiredReturn(state: string, actor: SlackSetupActor) {
const { current, attempt } = await pending(state, actor, true);
if (attempt.expiresAt.getTime() > Date.now()) return null;
return options.withLock(current.endpoint.id, async lease => {
const latest = await pending(state, actor, true);
await lease.assertOwned();
await db.delete(toolOauthStates).where(eq(toolOauthStates.state, state));
await db.update(chatEndpoints).set({ setup: { ...latest.current.endpoint.setup, slackManagerError: "slack_install_expired" } }).where(eq(chatEndpoints.id, current.endpoint.id));
return current.endpoint.id;
});
}
async function complete(state: string, claimId: string | null, error: string | null, actor: SlackSetupActor) {
const client = await requiredBroker();
const before = await pending(state, actor);
return options.withLock(before.current.endpoint.id, async lease => {
const { current, row, binding } = await pending(state, actor);
await lease.assertOwned();
const [claimed] = await db.delete(toolOauthStates).where(and(eq(toolOauthStates.state, state), gt(toolOauthStates.expiresAt, new Date()))).returning();
if (!claimed) throw conflict("Slack authorization was already used");
async function outcome(code: string | null) {
await lease.assertOwned();
const latest = await endpoint(current.endpoint.id, actor);
await db.update(chatEndpoints).set({ setup: { ...latest.endpoint.setup, slackManagerError: code ?? undefined } }).where(eq(chatEndpoints.id, current.endpoint.id));
if (code) await logActivity(db, { companyId: current.endpoint.companyId, actorType: "user", actorId: actor.userId, action: "chat_slack.manager_authorization_failed", entityType: "chat_endpoint", entityId: current.endpoint.id, details: { code } });
return current.endpoint.id;
}
if (error || !claimId || claimId.length > 4096) return outcome(error === "access_denied" ? "slack_install_declined" : "slack_manager_reauthorize");
try {
let grant: SealedConnectorCredentials;
try { grant = await client.claim({ profile: "slack.manager", subject: actor.userId, companyId: current.endpoint.companyId, claimId, redemptionId: randomUUID() }); }
catch { throw providerFailure("slack_manager_reauthorize"); }
const identity = grant.slackManager;
if (!identity || identity.appId !== await client.getSlackManagerAppId() || !/^A[A-Z0-9]+$/.test(identity.appId) || !/^T[A-Z0-9]+$/.test(identity.workspaceId) || !/^[UW][A-Z0-9]+$/.test(identity.userId) || typeof identity.workspaceName !== "string" || !identity.workspaceName || identity.workspaceName.length > 255) throw providerFailure("slack_manager_reauthorize");
if (row?.managerGrantId) {
const existing = await get(row.managerGrantId, current.endpoint.companyId, actor);
if (existing.managerAppId !== identity.appId || existing.workspaceId !== identity.workspaceId || existing.slackUserId !== identity.userId) throw providerFailure("slack_install_identity_mismatch");
}
await endpoint(current.endpoint.id, actor);
await db.transaction(async tx => {
await lease.assertOwned(tx);
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`slack-manager:${current.endpoint.companyId}:${actor.userId}:${identity.appId}:${identity.workspaceId}`}, 0))`);
const [existing] = await tx.select().from(chatSlackManagerGrants).where(and(eq(chatSlackManagerGrants.companyId, current.endpoint.companyId), eq(chatSlackManagerGrants.userId, actor.userId), eq(chatSlackManagerGrants.managerAppId, identity.appId), eq(chatSlackManagerGrants.workspaceId, identity.workspaceId)));
if (existing) {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`slack-manager-refresh:${existing.id}`}, 0))`);
const [latest] = await tx.select().from(chatSlackManagerGrants).where(eq(chatSlackManagerGrants.id, existing.id));
const revision = Array.isArray(binding.revisions) ? binding.revisions.map(object).find(value => value.id === existing.id)?.revision : undefined;
if (!latest || latest.revision !== revision) throw conflict("Workspace authorization changed. Start again.");
}
const [saved] = await tx.insert(chatSlackManagerGrants).values({ companyId: current.endpoint.companyId, userId: actor.userId, slackUserId: identity.userId, workspaceId: identity.workspaceId, workspaceName: identity.workspaceName, managerAppId: identity.appId })
.onConflictDoUpdate({ target: [chatSlackManagerGrants.companyId, chatSlackManagerGrants.userId, chatSlackManagerGrants.managerAppId, chatSlackManagerGrants.workspaceId], set: { updatedAt: new Date() } }).returning();
// A reauthorization must never change which Slack person this grant represents.
if (saved.slackUserId !== identity.userId) throw conflict("Reconnect using the original Slack account");
await access(current.endpoint.companyId, actor);
await save(tx, saved, grant, actor);
});
await logActivity(db, { companyId: current.endpoint.companyId, actorType: "user", actorId: actor.userId, action: "chat_slack.manager_authorized", entityType: "chat_endpoint", entityId: current.endpoint.id, details: { workspaceId: identity.workspaceId, managerAppId: identity.appId } });
return outcome(null);
} catch { return outcome("slack_manager_reauthorize"); }
});
}
type Grant = typeof chatSlackManagerGrants.$inferSelect;
async function get(id: string, companyId: string, actor: SlackSetupActor) {
await access(companyId, actor);
const [grant] = await db.select().from(chatSlackManagerGrants).where(and(eq(chatSlackManagerGrants.id, id), eq(chatSlackManagerGrants.companyId, companyId), eq(chatSlackManagerGrants.userId, actor.userId)));
if (!grant) throw forbidden("This Slack workspace authorization belongs to another account");
return grant;
}
async function save(tx: Parameters<Parameters<typeof db.transaction>[0]>[0], row: Grant, credentials: SealedConnectorCredentials, actor: SlackSetupActor) {
if (credentials.tokenType !== "user" || !credentials.accessToken || !credentials.refreshToken || !credentials.accessTokenExpiresAt || !Number.isFinite(Date.parse(credentials.accessTokenExpiresAt)) || Date.parse(credentials.accessTokenExpiresAt) <= Date.now() || credentials.provider !== "slack" || credentials.profile !== "slack.manager" || credentials.subject !== row.userId || credentials.companyId !== row.companyId || SLACK_MANAGER_SCOPES.some(scope => !credentials.scopes.includes(scope))) throw providerFailure("slack_manager_reauthorize");
const write = (key: string, value: string, secretId: string | null) => writeConnectionCredential(tx, { companyId: row.companyId, ownerUserId: row.userId, actor: { userId: actor.userId }, connectionName: "Slack workspace management", configPath: `slack_manager.${key}`, definitionKey: `slack_manager.${row.id}.${key}`, label: key, value, ...(secretId ? { existingRef: { secretId, configPath: `slack_manager.${key}` } } : {}) });
const accessToken = await write("access_token", credentials.accessToken, row.accessSecretId);
const refreshToken = credentials.refreshToken ? await write("refresh_token", credentials.refreshToken, row.refreshSecretId) : null;
await tx.update(chatSlackManagerGrants).set({ accessSecretId: accessToken.secret.id, refreshSecretId: refreshToken?.secret.id ?? row.refreshSecretId, expiresAt: credentials.accessTokenExpiresAt ? new Date(credentials.accessTokenExpiresAt) : null, status: "active", revision: row.revision + 1, updatedAt: new Date() }).where(eq(chatSlackManagerGrants.id, row.id));
}
async function secret(row: Grant, id: string | null) {
if (!id) throw providerFailure("slack_manager_reauthorize");
const [ref] = await db.select().from(companySecrets).where(and(eq(companySecrets.id, id), eq(companySecrets.companyId, row.companyId), eq(companySecrets.scope, "user"), eq(companySecrets.ownerUserId, row.userId)));
if (!ref?.userSecretDefinitionId) throw providerFailure("slack_manager_reauthorize");
// Owner-scoped system consumer; the durable grant is its authority, not a tool binding.
const value = await vault.resolveUserSecretValue(row.companyId, { definitionId: ref.userSecretDefinitionId, responsibleUserId: row.userId }, { consumerType: "system", consumerId: `slack-manager:${row.id}`, actorType: "user", actorId: row.userId, responsibleUserId: row.userId });
if (!value) throw providerFailure("slack_manager_reauthorize");
return value.value;
}
async function token(id: string, companyId: string, actor: SlackSetupActor) {
const client = await requiredBroker();
// Cross-endpoint serialization is required because rotated refresh tokens are single use.
return db.transaction(async tx => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`slack-manager-refresh:${id}`}, 0))`);
const grant = await get(id, companyId, actor);
if (grant.managerAppId !== await client.getSlackManagerAppId()) throw providerFailure("slack_manager_reauthorize");
if (grant.status !== "active") throw providerFailure("slack_manager_reauthorize");
if (!grant.expiresAt || grant.expiresAt.getTime() > Date.now() + 60_000) return { grant, token: await secret(grant, grant.accessSecretId) };
// Mark before dispatch. A lost refresh response requires fresh consent, never replay.
await db.update(chatSlackManagerGrants).set({ status: "reauthorize" }).where(eq(chatSlackManagerGrants.id, id));
try {
const refreshed = await client.refresh({ profile: "slack.manager", subject: actor.userId, companyId, refreshToken: await secret(grant, grant.refreshSecretId) });
await access(companyId, actor);
await save(tx, grant, refreshed, actor);
return { grant, token: refreshed.accessToken };
} catch { return null; }
}).then(result => { if (!result) throw providerFailure("slack_manager_reauthorize"); return result; });
}
async function revoke(id: string, companyId: string, actor: SlackSetupActor) {
let providerRevoked = true;
const grant = await db.transaction(async tx => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`slack-manager-refresh:${id}`}, 0))`);
const current = await get(id, companyId, actor);
await tx.update(chatSlackManagerGrants).set({ status: "revoked", revision: current.revision + 1, updatedAt: new Date() }).where(eq(chatSlackManagerGrants.id, id));
await tx.delete(toolOauthStates).where(and(eq(toolOauthStates.companyId, companyId), eq(toolOauthStates.createdByActorId, actor.userId), like(toolOauthStates.state, `${SLACK_MANAGER_STATE_PREFIX}%`)));
const client = broker();
for (const secretId of [current.accessSecretId, current.refreshSecretId]) if (secretId) {
try {
if (!client) throw providerFailure("slack_managed_unavailable");
await client.revoke({ subject: actor.userId, companyId, profile: "slack.manager", token: await secret(current, secretId) });
} catch { providerRevoked = false; }
await vault.remove(secretId);
}
await tx.update(chatSlackManagerGrants).set({ accessSecretId: null, refreshSecretId: null }).where(eq(chatSlackManagerGrants.id, id));
return current;
});
await logActivity(db, { companyId, actorType: "user", actorId: actor.userId, action: "chat_slack.manager_revoked", entityType: "slack_manager_grant", entityId: id, details: { workspaceId: grant.workspaceId, providerRevoked } });
}
async function request(id: string, companyId: string, actor: SlackSetupActor, method: string, fields: Record<string, string> | FormData) {
const authorized = await token(id, companyId, actor);
const { grant } = authorized;
// Slack shares a method budget across manager tokens in the same workspace.
// Persist Retry-After across grants and process restarts; never retry a dispatch.
const result = await db.transaction(async tx => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`slack-manager-api:${companyId}:${grant.managerAppId}:${grant.workspaceId}:${method}`}, 0))`);
// Serialize provider dispatch against refresh/revocation for this personal grant.
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`slack-manager-refresh:${id}`}, 0))`);
const peers = await tx.select().from(chatSlackManagerGrants).where(and(eq(chatSlackManagerGrants.companyId, companyId), eq(chatSlackManagerGrants.managerAppId, grant.managerAppId), eq(chatSlackManagerGrants.workspaceId, grant.workspaceId))).orderBy(chatSlackManagerGrants.id);
if (peers.some(peer => Date.parse(peer.rateLimits[method] ?? "") > Date.now())) return { error: providerFailure("slack_setup_rate_limited") };
if ((await get(id, companyId, actor)).status !== "active") return { error: providerFailure("slack_manager_reauthorize") };
try { return { value: await api(method, fields, authorized.token) }; }
catch (error) {
const details = object(object(error).details);
if (details.code === "slack_setup_rate_limited") {
const until = new Date(Date.now() + Math.min(Number(details.retryAfterSeconds) || 60, 86_400) * 1000).toISOString();
for (const peer of peers) await tx.update(chatSlackManagerGrants).set({ rateLimits: sql`${chatSlackManagerGrants.rateLimits} || ${JSON.stringify({ [method]: until })}::jsonb` }).where(eq(chatSlackManagerGrants.id, peer.id));
}
return { error: details.code === "slack_configuration_token_invalid" ? providerFailure("slack_manager_reauthorize") : error };
}
});
if ("error" in result) throw result.error;
return result.value!;
}
return { choices, available, authorize, pending, expiredReturn, complete, get, token, revoke, request };
}
@@ -0,0 +1,58 @@
import { slackRegistrationErrorMessage } from "@paperclipai/shared";
import { unprocessable } from "../../../../errors.js";
export const object = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
export const providerFailure = (code: string) => unprocessable(slackRegistrationErrorMessage(code), { code });
export const knownProviderErrors: Record<string, string> = {
app_approval_request_eligible: "slack_approval_required", app_approval_request_pending: "slack_approval_pending",
app_approval_request_denied: "slack_approval_denied", admin_approval_required: "slack_approval_required",
manager_app_not_eligible: "slack_managed_unavailable", feature_not_enabled: "slack_managed_unavailable",
invalid_auth: "slack_configuration_token_invalid", token_expired: "slack_configuration_token_invalid",
token_revoked: "slack_configuration_token_invalid", not_authed: "slack_configuration_token_invalid",
invalid_manifest: "slack_manifest_invalid", invalid_app: "slack_manifest_invalid",
ratelimited: "slack_setup_rate_limited", no_permission: "slack_setup_permission_denied",
missing_scope: "slack_setup_permission_denied", not_allowed_token_type: "slack_configuration_token_invalid",
};
const timeoutMs = 20_000;
export function createSlackSetupClient(fetchImpl: typeof fetch = fetch) {
return async function api(method: string, fields: Record<string, string> | FormData, bearer?: string, requiredScopes?: readonly string[]) {
const response = await fetchImpl(`https://slack.com/api/${method}`, {
method: "POST", redirect: "error", signal: AbortSignal.timeout(timeoutMs),
headers: { ...(fields instanceof FormData ? {} : { "content-type": "application/x-www-form-urlencoded" }), ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },
body: fields instanceof FormData ? fields : new URLSearchParams(fields),
});
// Bound the streamed response as well as the request lifetime.
const reader = response.body?.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
if (reader) {
try {
while (true) {
const part = await reader.read();
if (part.done) break;
size += part.value.byteLength;
if (size > 1_048_576) { await reader.cancel(); throw providerFailure("slack_provider_failure"); }
chunks.push(part.value);
}
} finally { reader.releaseLock(); }
}
let result: Record<string, unknown>;
try { result = object(JSON.parse(Buffer.concat(chunks).toString("utf8"))); }
catch { result = {}; }
if (!response.ok || result.ok !== true) {
const code = knownProviderErrors[String(result.error)] ?? (response.status === 429 ? "slack_setup_rate_limited" : "slack_provider_failure");
const retry = Number(response.headers.get("retry-after"));
if (response.status === 429 || result.error === "ratelimited") {
throw unprocessable(slackRegistrationErrorMessage("slack_setup_rate_limited"), {
code: "slack_setup_rate_limited", retryAfterSeconds: Number.isFinite(retry) && retry > 0 ? Math.ceil(retry) : 60,
});
}
throw providerFailure(code);
}
if (requiredScopes) {
const granted = new Set((response.headers.get("x-oauth-scopes") ?? "").split(/[, ]+/));
if (requiredScopes.some(scope => !granted.has(scope))) throw providerFailure("slack_install_scopes_missing");
}
return result;
}
}
@@ -0,0 +1,134 @@
import { createAgentAvatarPool } from "../../../agent-avatar-pool.js";
import type { AgentAvatarRequest } from "../../../agent-avatars.js";
import { and, eq } from "drizzle-orm";
import { agents, chatEndpoints, chatSlackRegistrations, toolConnections, type Db } from "@paperclipai/db";
import { slackRegistrationErrorMessage, type SlackRegistrationState, type SlackAvatarState, type SlackAccountState, isProvisionedSlackSetup } from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound, unprocessable } from "../../../../errors.js";
import { accessService } from "../../../access.js";
import { logActivity } from "../../../activity-log.js";
import { instanceSettingsService } from "../../../instance-settings.js";
import { secretService } from "../../../secrets.js";
import { writeConnectionCredential } from "../../../connection-credentials.js";
import type { CredentialMutationLeaseGuard } from "../../../chat-credential-mutation-lease.js";
export interface SlackSetupActor { userId: string; sessionId: string | null; bypassPermissionCheck: boolean }
export type Registration = typeof chatSlackRegistrations.$inferSelect;
export { object, providerFailure, knownProviderErrors } from "./provider-client.js";
import { object } from "./provider-client.js";
export function slackRegistrationProjection(row: Registration): SlackRegistrationState {
return {
status: row.status === "creating" && Date.now() - row.updatedAt.getTime() > 60_000 ? "uncertain" : row.status,
appId: row.appId,
...(row.managerGrantId ? { managerGrantId: row.managerGrantId } : {}),
managementUrl: row.appId ? `https://api.slack.com/apps/${encodeURIComponent(row.appId)}` : "https://api.slack.com/apps",
errorCode: row.status === "creating" && Date.now() - row.updatedAt.getTime() > 60_000 ? "slack_creation_uncertain" : row.errorCode,
};
}
import { createSlackSetupClient } from "./provider-client.js";
export type SlackSetupOptions = {
managed?: { enabled: boolean; broker: import("../../../paperclip-cloud-connector.js").PaperclipCloudConnector };
publicOrigin: () => string | null;
webhookOrigin: () => string | null;
fetch?: typeof fetch;
renderAvatar?: (request: AgentAvatarRequest) => Promise<Buffer>;
withLock: <T>(endpointId: string, work: (lease: CredentialMutationLeaseGuard) => Promise<T>) => Promise<T>;
runtimeSigningSecret: (endpointId: string) => Promise<string>;
runtimeBotToken: (endpointId: string) => Promise<string>;
canWelcome: (endpointId: string, account: SlackAccountState) => Promise<boolean>;
linkInstaller: (endpointId: string, user: Record<string, unknown>, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) => Promise<void>;
configure: (endpointId: string, credentials: Record<string, string>, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) => Promise<unknown>;
};
export function createSlackRegistrationStore(db: Db, options: SlackSetupOptions) {
const fetchImpl = options.fetch ?? fetch;
const vault = secretService(db);
let avatarPool: ReturnType<typeof createAgentAvatarPool> | undefined;
function origin(value: string | null) {
if (!value) throw badRequest("Configure a public HTTPS URL before creating a Slack app");
const url = new URL(value);
if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash)
throw badRequest("Slack setup requires a configured public HTTPS origin");
return url.origin;
}
const callbackUri = () => `${origin(options.publicOrigin())}/api/chat-slack/oauth/callback`;
async function registration(endpointId: string) {
return (await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId)))[0];
}
async function endpoint(endpointId: string, actor: SlackSetupActor) {
if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) throw forbidden("Chat connectors are disabled");
const [row] = await db.select({ endpoint: chatEndpoints, connection: toolConnections, agentName: agents.name, agentAppearance: agents.appearance })
.from(chatEndpoints).innerJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId), eq(toolConnections.companyId, chatEndpoints.companyId)))
.innerJoin(agents, and(eq(agents.id, chatEndpoints.assignedAgentId), eq(agents.companyId, chatEndpoints.companyId)))
.where(and(eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "slack")));
if (!row || row.endpoint.status === "archived" || row.connection.status === "archived") throw notFound("Slack connection not found");
if (!actor.bypassPermissionCheck && !await accessService(db).hasPermission(row.endpoint.companyId, "user", actor.userId, "tools:manage_connections"))
throw forbidden("Missing permission: tools:manage_connections");
return row;
}
function assertOrigins(row: Registration, publicId: string) {
if (row.callbackUri !== callbackUri()) throw conflict("The Paperclip URL changed. Restore its configured address or update the Slack app and use manual setup.");
const expected = `${origin(options.webhookOrigin())}/api/chat-webhooks/${publicId}/slack`;
if (object(object(row.manifest.settings).event_subscriptions).request_url !== expected)
throw conflict("The Slack webhook address changed. Restore its configured address or update the Slack app and use manual setup.");
}
async function audit(row: Registration, actor: SlackSetupActor, action: string, code?: string) {
await logActivity(db, { companyId: row.companyId, actorType: "user", actorId: actor.userId,
action: `chat_slack.${action}`, entityType: "chat_endpoint", entityId: row.endpointId,
details: { endpointId: row.endpointId, appId: row.appId, ...(code ? { code } : {}) } });
}
const api = createSlackSetupClient(fetchImpl);
async function saveSecrets(row: Registration, values: Record<string, string>, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard,
patch: Partial<Registration> = {}, account?: SlackAccountState) {
await db.transaction(async tx => {
await lease.assertOwned(tx);
const current = (await tx.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, row.endpointId)).for("update"))[0];
if (!current || current.requestId !== row.requestId || current.status === "removed") throw conflict("Slack setup changed. Resume the saved connection.");
const ids = { ...current.secretIds };
for (const [key, value] of Object.entries(values)) {
const result = await writeConnectionCredential(tx, { companyId: row.companyId, connectionName: "Slack app registration",
configPath: `slack_registration.${key}`, label: key, value, actor: { userId: actor.userId },
...(ids[key] ? { existingRef: { secretId: ids[key], configPath: `slack_registration.${key}` } } : {}) });
ids[key] = result.secret.id;
}
await tx.update(chatSlackRegistrations).set({ ...patch, secretIds: ids, updatedAt: new Date() }).where(eq(chatSlackRegistrations.endpointId, row.endpointId));
if (account) {
const saved = (await tx.select().from(chatEndpoints).where(and(eq(chatEndpoints.id, row.endpointId), eq(chatEndpoints.companyId, row.companyId))).for("update"))[0];
if (!saved || saved.status === "archived") throw conflict("Slack setup changed");
// Reauthorization never changes an established personal account binding.
if (saved.setup.slackAccount?.status !== "linked") await tx.update(chatEndpoints).set({ setup: { ...saved.setup, slackAccount: account }, updatedAt: new Date() }).where(eq(chatEndpoints.id, row.endpointId));
}
await lease.assertOwned(tx);
});
}
async function readSecret(row: Registration, key: string) {
if (!row.secretIds[key]) throw conflict("Slack setup credentials are unavailable. Resume the saved connection.");
return vault.resolveSecretValue(row.companyId, row.secretIds[key], "latest", {
accessContext: { consumerType: "system", consumerId: `slack-registration:${row.endpointId}`, configPath: `slack_registration.${key}`, actorType: "system" },
});
}
async function setFailure(row: Registration, status: Registration["status"], code: string, lease: CredentialMutationLeaseGuard) {
await lease.assertOwned();
await db.update(chatSlackRegistrations).set({ status, errorCode: code, updatedAt: new Date() })
.where(and(eq(chatSlackRegistrations.endpointId, row.endpointId), eq(chatSlackRegistrations.requestId, row.requestId)));
}
async function saveAvatar(row: Registration, avatar: SlackAvatarState, actor: SlackSetupActor, lease: CredentialMutationLeaseGuard) {
await endpoint(row.endpointId, actor);
await db.transaction(async tx => {
await lease.assertOwned(tx);
const current = (await tx.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, row.endpointId)).for("update"))[0];
if (!current || current.requestId !== row.requestId || current.status === "removed") throw conflict("Slack setup changed. Resume the saved connection.");
const saved = (await tx.select().from(chatEndpoints).where(and(eq(chatEndpoints.id, row.endpointId), eq(chatEndpoints.companyId, row.companyId))).for("update"))[0];
if (!saved || saved.status === "archived" || !isProvisionedSlackSetup(saved.setup.slackSetupMethod)) throw conflict("Slack setup changed. Resume the saved connection.");
await tx.update(chatEndpoints).set({ setup: { ...saved.setup, slackAvatar: avatar }, updatedAt: new Date() })
.where(and(eq(chatEndpoints.id, row.endpointId), eq(chatEndpoints.companyId, row.companyId)));
await lease.assertOwned(tx);
});
}
const renderAvatar = (request: AgentAvatarRequest) => (options.renderAvatar ?? (avatarPool ??= createAgentAvatarPool()).render)(request);
return { db, options, origin, callbackUri, registration, endpoint, assertOrigins, audit, api, saveSecrets, readSecret, setFailure, saveAvatar, renderAvatar,
close: async () => { await avatarPool?.close(); } };
}
export type SlackRegistrationStore = ReturnType<typeof createSlackRegistrationStore>;
@@ -0,0 +1,151 @@
import { isProvisionedSlackSetup } from "@paperclipai/shared";
import { createSlackManagerGrants } from "./manager-grants.js";
import { createManagedSlackSetup } from "./managed.js";
import { randomBytes } from "node:crypto";
import { and, eq, gt, like } from "drizzle-orm";
import { chatEndpoints, chatSlackRegistrations, companies, toolOauthStates, type Db } from "@paperclipai/db";
import { badRequest, conflict, forbidden, notFound } from "../../../../errors.js";
import { removeSlackRegistration } from "../../../chat-slack-registration-cleanup.js";
import type { CredentialMutationLeaseGuard } from "../../../chat-credential-mutation-lease.js";
import { object, providerFailure, createSlackRegistrationStore, type SlackSetupOptions, type SlackSetupActor } from "./registration.js";
import { createCustomerOwnedSetup } from "./customer-owned.js";
import { createSlackCompletion } from "./completion.js";
const prefix = "slack-install.";
export function slackChatRegistrationService(db: Db, options: SlackSetupOptions) {
const store = createSlackRegistrationStore(db, options);
const { endpoint, registration, assertOrigins, callbackUri, audit, api, readSecret, setFailure, saveSecrets } = store;
const provisioner = createCustomerOwnedSetup(store);
const { create } = provisioner;
const completion = createSlackCompletion(store);
const { resumeLocked, notifyVerified, processPendingVerificationMessages } = completion;
const managerGrants = createSlackManagerGrants(store);
const managed = createManagedSlackSetup(store, managerGrants, provisioner, completion, install);
async function install(endpointId: string, actor: SlackSetupActor) {
return options.withLock(endpointId, async lease => {
const current = await endpoint(endpointId, actor);
const row = await registration(endpointId);
if (!row?.appId || !row.clientId || row.status === "removed") throw conflict("Create this Slack app before installing it");
if (row.errorCode === "slack_manifest_update_pending") throw conflict("Finish configuring the saved Slack app before installing it");
if (!isProvisionedSlackSetup(current.endpoint.setup.slackSetupMethod) || current.endpoint.status === "paused") throw conflict("Resume this connection before installing it");
if (row.managerGrantId) await managerGrants.token(row.managerGrantId, row.companyId, actor);
assertOrigins(row, current.endpoint.publicId);
const state = `${prefix}${randomBytes(32).toString("base64url")}`;
const expiresAt = new Date(Date.now() + 10 * 60_000);
const scopes = object(object(row.manifest.oauth_config).scopes).bot as string[];
await db.transaction(async tx => {
await lease.assertOwned(tx);
await tx.delete(toolOauthStates).where(and(eq(toolOauthStates.connectionId, current.connection.id), like(toolOauthStates.state, `${prefix}%`)));
await tx.insert(toolOauthStates).values({ state, companyId: row.companyId, connectionId: current.connection.id,
codeVerifier: JSON.stringify({ endpointId, requestId: row.requestId, appId: row.appId, callbackUri: row.callbackUri,
endpointStatus: current.endpoint.status, runtimeGeneration: object(current.endpoint.setup).runtimeGeneration ?? 0 }),
createdByActorType: "user", createdByActorId: actor.userId, createdBySessionId: actor.sessionId,
requestedScopes: scopes, expiresAt });
await tx.update(chatSlackRegistrations).set({ errorCode: row.managerGrantId ? row.errorCode : null, updatedAt: new Date() }).where(eq(chatSlackRegistrations.endpointId, endpointId));
});
const url = new URL("https://slack.com/oauth/v2/authorize");
url.search = new URLSearchParams({ client_id: row.clientId, scope: scopes.join(","), state, redirect_uri: row.callbackUri,
...(row.workspaceId ? { team: row.workspaceId } : {}) }).toString();
await audit(row, actor, "installation_started");
return { authorizationUrl: url.toString(), expiresAt: expiresAt.toISOString() };
});
}
async function expiredReturn(state: string, actor: SlackSetupActor) {
if (!/^slack-install\.[A-Za-z0-9_-]{43}$/.test(state)) return null;
const [attempt] = await db.select().from(toolOauthStates).where(eq(toolOauthStates.state, state));
if (!attempt || attempt.expiresAt.getTime() > Date.now() || attempt.createdByActorId !== actor.userId || attempt.createdBySessionId !== actor.sessionId) return null;
const binding = object(JSON.parse(attempt.codeVerifier));
const current = await endpoint(String(binding.endpointId), actor);
return options.withLock(current.endpoint.id, async lease => {
const latest = await endpoint(current.endpoint.id, actor);
const row = await registration(current.endpoint.id);
if (!row || row.status === "removed" || row.requestId !== binding.requestId || row.companyId !== attempt.companyId || latest.connection.id !== attempt.connectionId
|| !isProvisionedSlackSetup(latest.endpoint.setup.slackSetupMethod) || row.appId !== binding.appId || row.callbackUri !== binding.callbackUri) return null;
assertOrigins(row, latest.endpoint.publicId);
await lease.assertOwned();
await db.delete(toolOauthStates).where(eq(toolOauthStates.state, state));
await setFailure(row, row.status, "slack_install_expired", lease);
await audit(row, actor, "installation_failed", "slack_install_expired");
return returnPath(row.endpointId);
});
}
async function pending(state: string, actor: SlackSetupActor) {
if (!/^slack-install\.[A-Za-z0-9_-]{43}$/.test(state)) throw badRequest("Invalid Slack authorization state");
const [attempt] = await db.select().from(toolOauthStates).where(and(eq(toolOauthStates.state, state), gt(toolOauthStates.expiresAt, new Date())));
if (!attempt || attempt.createdByActorId !== actor.userId || attempt.createdBySessionId !== actor.sessionId)
throw forbidden("Slack authorization expired or belongs to another session. Resume setup and install again.");
const binding = object(JSON.parse(attempt.codeVerifier));
const current = await endpoint(String(binding.endpointId), actor);
const row = await registration(current.endpoint.id);
if (!row || row.status === "removed" || !isProvisionedSlackSetup(current.endpoint.setup.slackSetupMethod)
|| current.endpoint.status === "paused"
|| current.endpoint.status === "revoked" && binding.endpointStatus !== "revoked"
|| binding.runtimeGeneration !== (object(current.endpoint.setup).runtimeGeneration ?? 0)
|| row.requestId !== binding.requestId || row.appId !== binding.appId || row.callbackUri !== binding.callbackUri
|| row.callbackUri !== callbackUri() || attempt.companyId !== row.companyId || attempt.connectionId !== current.connection.id)
throw conflict("Slack setup changed. Resume the saved connection and install again.");
if (row.managerGrantId) await managerGrants.token(row.managerGrantId, row.companyId, actor);
assertOrigins(row, current.endpoint.publicId);
return { attempt, current, row };
}
async function complete(state: string, code: string | null, error: string | null, actor: SlackSetupActor) {
const before = await pending(state, actor);
return options.withLock(before.row.endpointId, async lease => {
const { row, attempt, current } = await pending(state, actor);
const [claimed] = await db.delete(toolOauthStates).where(and(eq(toolOauthStates.state, state), gt(toolOauthStates.expiresAt, new Date()))).returning();
if (!claimed) throw conflict("This Slack authorization was already used");
if (error) {
const failureCode = error === "access_denied" ? "slack_install_declined" : "slack_install_failed";
await setFailure(row, row.status, failureCode, lease);
await audit(row, actor, "installation_failed", failureCode);
return row.endpointId;
}
try {
if (!code || code.length > 4096) throw providerFailure("slack_install_failed");
const result = await api("oauth.v2.access", { code, client_id: row.clientId!, client_secret: await readSecret(row, "clientSecret"), redirect_uri: row.callbackUri });
const teamId = object(result.team).id;
const installerId = object(result.authed_user).id;
if (result.app_id !== row.appId || result.token_type !== "bot" || typeof result.access_token !== "string" || !result.access_token.startsWith("xoxb-")
|| typeof teamId !== "string" || !/^T[A-Z0-9]+$/.test(teamId) || typeof result.bot_user_id !== "string" || !/^[UW][A-Z0-9]+$/.test(result.bot_user_id)
|| row.workspaceId && row.workspaceId !== teamId || row.botUserId && row.botUserId !== result.bot_user_id)
throw providerFailure("slack_install_identity_mismatch");
const granted = new Set(String(result.scope ?? "").split(","));
if ((attempt.requestedScopes ?? []).some(scope => !granted.has(scope))) throw providerFailure("slack_install_scopes_missing");
if (current.endpoint.providerAccountId && current.endpoint.providerAccountId !== teamId
|| current.endpoint.botExternalId && current.endpoint.botExternalId !== result.bot_user_id)
throw providerFailure("slack_install_identity_mismatch");
if (typeof installerId !== "string" || !/^[UW][A-Z0-9]+$/.test(installerId) || installerId === result.bot_user_id) throw providerFailure("slack_install_account_missing");
if (row.managerGrantId) {
const grant = await managerGrants.get(row.managerGrantId, row.companyId, actor);
if (installerId !== grant.slackUserId || teamId !== grant.workspaceId) throw providerFailure("slack_install_identity_mismatch");
}
await endpoint(row.endpointId, actor);
// Reauthorization reuses the runtime signing secret after staging was cleaned.
await saveSecrets(row, { botToken: result.access_token }, actor, lease,
{ status: "credentials_saved", workspaceId: teamId, botUserId: result.bot_user_id, errorCode: null },
{ externalUserId: installerId, paperclipUserId: actor.userId, status: "pending", welcomeStatus: "pending" });
} catch (failure) {
const code = object(object(failure).details).code;
const safeCode = typeof code === "string" && code.startsWith("slack_install_") ? code : "slack_install_failed";
await setFailure(row, row.status, safeCode, lease);
await audit(row, actor, "installation_failed", safeCode);
return row.endpointId;
}
await resumeLocked(row.endpointId, actor, lease);
return row.endpointId;
});
}
const cleanup = (endpointId: string, lease: CredentialMutationLeaseGuard) => removeSlackRegistration(db, endpointId, lease);
async function returnPath(endpointId: string) {
const [row] = await db.select({ prefix: companies.issuePrefix }).from(chatEndpoints)
.innerJoin(companies, eq(companies.id, chatEndpoints.companyId)).where(eq(chatEndpoints.id, endpointId));
if (!row) throw notFound("Slack connection not found");
return `/${encodeURIComponent(row.prefix)}/apps/chat/connect?provider=slack&resume=${encodeURIComponent(endpointId)}`;
}
return { create, managerGrants, managed, install, pending, expiredReturn, complete, cleanup, returnPath, registration, notifyVerified, processPendingVerificationMessages,
close: store.close,
resume: (endpointId: string, actor: SlackSetupActor) => options.withLock(endpointId, async lease => {
const row = await registration(endpointId);
if (row?.managerGrantId) await managerGrants.token(row.managerGrantId, row.companyId, actor);
return resumeLocked(endpointId, actor, lease);
}) };
}
@@ -7,6 +7,7 @@ import {
randomBytes,
type KeyObject,
} from "node:crypto";
import { SLACK_MANAGER_SCOPES } from "@paperclipai/shared";
import { describe, expect, it, vi } from "vitest";
import { readFileSync } from "node:fs";
@@ -406,6 +407,16 @@ describe("Paperclip Cloud connector", () => {
})).rejects.toMatchObject({ code: "CONNECTOR_BAD_RESPONSE" });
});
it("opens Slack manager handoffs with their exact profile and personal identity", async () => {
const keys = config();
const credentials = { v: 1, accessToken: "manager-access-canary", refreshToken: "manager-refresh-canary", tokenType: "user", accessTokenExpiresAt: "2030-01-01T00:00:00.000Z", refreshTokenExpiresAt: null,
scopes: [...SLACK_MANAGER_SCOPES], subject, companyId, instanceId, environment: "staging", provider: "slack", profile: "slack.manager",
slackManager: { appId: "AMANAGER", workspaceId: "TWORKSPACE", workspaceName: "Paperclip", userId: "UOWNER" } };
const sealed = seal(credentials, keys.sealPublicKey, "initial", keys.config, "slack.manager");
const connector = createPaperclipCloudConnector({ config: keys.config, request: vi.fn(async () => Response.json({ claimId: "claim", scopes: [...SLACK_MANAGER_SCOPES], sealed })) as typeof fetch });
await expect(connector.claim({ subject, companyId, profile: "slack.manager", claimId: "claim", redemptionId: "manager-state" })).resolves.toEqual(credentials);
await expect(connector.claim({ subject: "another-user", companyId, profile: "slack.manager", claimId: "claim", redemptionId: "manager-state" })).rejects.toThrow();
});
it("opens an instance-sealed claim and verifies its user, company, and exact scopes", async () => {
const keys = config();
const credentials = {
@@ -612,7 +623,7 @@ function seal(
recipientPublicKey: KeyObject,
purpose: "initial" | "access",
configValue: PaperclipCloudConnectorConfig,
profile: keyof typeof GOOGLE_WORKSPACE_CONNECTOR_PROFILES,
profile: keyof typeof GOOGLE_WORKSPACE_CONNECTOR_PROFILES | "slack.manager",
) {
const ephemeral = generateKeyPairSync("x25519");
const ephemeralJwk = ephemeral.publicKey.export({ format: "jwk" }) as { x: string };
@@ -625,9 +636,9 @@ function seal(
purpose,
configValue.instanceId,
configValue.environment,
"google",
profile === "slack.manager" ? "slack" : "google",
profile,
[...GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes].sort().join(" "),
[...(profile === "slack.manager" ? SLACK_MANAGER_SCOPES : GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes)].sort().join(" "),
].join("\n"));
const key = Buffer.from(hkdfSync(
"sha256",
@@ -644,7 +655,7 @@ function seal(
v: 1,
alg: "X25519-HKDF-SHA256-A256GCM",
purpose,
provider: "google",
provider: profile === "slack.manager" ? "slack" : "google",
profile,
epk: ephemeralJwk.x,
iv: iv.toString("base64url"),
@@ -1,4 +1,4 @@
import { ASANA_CONNECTOR_SCOPES, isAsanaConnectorProfileId, type AsanaConnectorProfileId } from "@paperclipai/shared";
import { SLACK_MANAGER_SCOPES, ASANA_CONNECTOR_SCOPES, isAsanaConnectorProfileId, type AsanaConnectorProfileId } from "@paperclipai/shared";
import {
createDecipheriv,
createHash,
@@ -34,8 +34,8 @@ export { GOOGLE_WORKSPACE_CONNECTOR_PROFILES };
export type PaperclipCloudConnectorEnvironment = "development" | "staging" | "production";
export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack";
export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId;
export type PaperclipCloudConnectorProvider = "google" | "github" | "asana";
export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | "slack.manager";
export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack";
export type PaperclipCloudConnectorConfig = {
baseUrl: string;
@@ -60,6 +60,7 @@ export type SealedConnectorCredentials = {
provider: PaperclipCloudConnectorProvider;
profile: string;
appSlug?: string;
slackManager?: { appId: string; workspaceId: string; workspaceName: string; userId: string };
};
export type SealedGmailCredentials = SealedConnectorCredentials & { provider: "google" };
@@ -95,6 +96,7 @@ type SealedEnvelope = {
};
type ConnectorResponse = {
slackManager?: unknown;
confirmationUrl?: unknown;
authorizationUrl?: unknown;
handoff?: unknown;
@@ -395,6 +397,13 @@ export function createPaperclipCloudConnector(input: {
typeof value === "string" && isPaperclipCloudConnectorProfileId(value) ? [value] : []
))];
},
async getSlackManagerAppId(): Promise<string | null> {
const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" });
const manager = response.slackManager;
if (response.active !== true || response.status !== "active" || !Array.isArray(response.profiles) || !response.profiles.includes("slack.manager")
|| !manager || typeof manager !== "object" || !("appId" in manager) || typeof manager.appId !== "string" || !/^A[A-Z0-9]+$/.test(manager.appId)) return null;
return manager.appId;
},
async startAuthorization(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; returnUri: string; returnState: string }) {
const profile = values.profile ?? "gmail.draft";
const response = await call("session", { ...values, profile });
@@ -755,6 +764,7 @@ function connectorProfileDefinition(profile: PaperclipCloudConnectorProfileId):
provider: PaperclipCloudConnectorProvider;
scopes: readonly string[];
} {
if (profile === "slack.manager") return { provider: "slack", scopes: SLACK_MANAGER_SCOPES };
if (isAsanaConnectorProfileId(profile)) {
return { provider: "asana", scopes: ASANA_CONNECTOR_SCOPES };
}
@@ -768,6 +778,7 @@ function isExpectedProviderAuthorizationUrl(
profile: PaperclipCloudConnectorProfileId,
url: URL,
): boolean {
if (profile === "slack.manager") return url.origin === "https://slack.com" && url.pathname === "/oauth/v2/authorize";
if (isAsanaConnectorProfileId(profile)) {
return url.origin === "https://app.asana.com" && url.pathname === "/-/oauth_authorize";
}
@@ -778,7 +789,7 @@ function isExpectedProviderAuthorizationUrl(
}
function isPaperclipCloudConnectorProfileId(value: string): value is PaperclipCloudConnectorProfileId {
return isGoogleWorkspaceConnectorProfileId(value) || isGitHubConnectorProfileId(value) || isAsanaConnectorProfileId(value);
return value === "slack.manager" || isGoogleWorkspaceConnectorProfileId(value) || isGitHubConnectorProfileId(value) || isAsanaConnectorProfileId(value);
}
async function sha256Base64Url(value: string): Promise<string> {