UNPKG

@sellable/install

Version:

One-command installer for Sellable MCP in Claude Code, Codex, and Hermes

324 lines (298 loc) • 10.5 kB
import { createHash } from "node:crypto"; export const SLACK_WORKSPACE_CLIENTS_ID = "sellable-agent-slack-workspace-clients/v1"; const sha256 = (value) => createHash("sha256").update(value).digest("hex"); const REGISTRY_STATE = new WeakMap(); const CREDENTIAL_FINGERPRINT = /^(?:[a-f0-9]{16}|[a-f0-9]{64})$/; export class SlackWorkspaceClientError extends Error { constructor(code, message, details = {}) { super(message); this.name = "SlackWorkspaceClientError"; this.code = code; this.details = Object.freeze({ ...details }); } } function deny(code, message, stage) { throw new SlackWorkspaceClientError(code, message, stage ? { stage } : {}); } function requiredId(value) { return ( typeof value === "string" && value.length > 0 && value.length <= 255 && !/[\u0000-\u001f\u007f]/.test(value) ); } function positiveGeneration(value) { return Number.isSafeInteger(value) && value >= 1; } function registryRecords(workspaces) { if (Array.isArray(workspaces)) return workspaces; if (workspaces instanceof Map) return [...workspaces.values()]; return null; } function isQuarantined(workspace) { return ( workspace?.quarantined === true || workspace?.status === "quarantined" || workspace?.code === "WORKSPACE_AUTH_QUARANTINED" ); } function assertNoRawCredential(workspace) { if ( workspace && typeof workspace === "object" && ["token", "accessToken", "botToken", "secret"].some((key) => Object.prototype.hasOwnProperty.call(workspace, key), ) ) { deny( "SLACK_WORKSPACE_RAW_CREDENTIAL_DENIED", "Workspace registry accepts authenticated clients, not credentials", "registry", ); } } /** * Builds an exact-team registry from independently authenticated clients. A * quarantined authentication result can be supplied beside healthy records, * but it never receives a selectable entry. The WeakMap snapshot prevents a * caller from adding a primary/default client after validation. */ export function createSlackWorkspaceClientRegistry(workspaces) { const records = registryRecords(workspaces); if (!records || records.length === 0) { deny("SLACK_WORKSPACE_REGISTRY_INVALID", "Workspace client registry is required", "registry"); } const publicRegistry = new Map(); const privateClients = new Map(); const quarantined = []; const credentialOwners = new Map(); for (const workspace of records) { assertNoRawCredential(workspace); if (isQuarantined(workspace)) { quarantined.push(Object.freeze({ teamId: requiredId(workspace?.expectedTeamId) ? workspace.expectedTeamId : requiredId(workspace?.teamId) ? workspace.teamId : null, installationId: requiredId(workspace?.installationId) ? workspace.installationId : null, code: "WORKSPACE_AUTH_QUARANTINED", })); continue; } if ( !requiredId(workspace?.teamId) || !requiredId(workspace?.installationId) || !requiredId(workspace?.botUserId) || !positiveGeneration(workspace?.oauthGeneration) || !CREDENTIAL_FINGERPRINT.test(workspace?.credentialFingerprint ?? "") || !workspace.client || (typeof workspace.client !== "object" && typeof workspace.client !== "function") ) { deny("SLACK_WORKSPACE_RECORD_INVALID", "Workspace client record is malformed", "registry"); } const existingTeam = privateClients.get(workspace.teamId); if (existingTeam) { if ( existingTeam.installationId !== workspace.installationId || existingTeam.credentialFingerprint !== workspace.credentialFingerprint || existingTeam.botUserId !== workspace.botUserId || existingTeam.oauthGeneration !== workspace.oauthGeneration ) { deny( "SLACK_WORKSPACE_TEAM_DIVERGENT", "Slack team has divergent authenticated ownership", "registry", ); } deny("SLACK_WORKSPACE_TEAM_AMBIGUOUS", "Slack team has more than one client", "registry"); } const credentialOwner = credentialOwners.get(workspace.credentialFingerprint); if ( credentialOwner && (credentialOwner.teamId !== workspace.teamId || credentialOwner.installationId !== workspace.installationId) ) { deny( "SLACK_WORKSPACE_CREDENTIAL_REUSED", "Slack credential fingerprint has divergent installation ownership", "registry", ); } const selected = Object.freeze({ teamId: workspace.teamId, installationId: workspace.installationId, botUserId: workspace.botUserId, oauthGeneration: workspace.oauthGeneration, credentialFingerprint: workspace.credentialFingerprint, client: workspace.client, }); credentialOwners.set(workspace.credentialFingerprint, selected); privateClients.set(workspace.teamId, selected); publicRegistry.set(workspace.teamId, selected); } if (privateClients.size === 0) { deny( "SLACK_WORKSPACE_NO_HEALTHY_CLIENTS", "No authenticated Slack workspace client is available", "registry", ); } Object.defineProperties(publicRegistry, { registryId: { value: SLACK_WORKSPACE_CLIENTS_ID, enumerable: false }, quarantined: { value: Object.freeze(quarantined), enumerable: false }, }); REGISTRY_STATE.set(publicRegistry, privateClients); return Object.freeze(publicRegistry); } export function selectSlackWorkspaceClient({ registry, teamId, installationId, oauthGeneration, botUserId, credentialFingerprint, }) { const clients = REGISTRY_STATE.get(registry); if (!clients || !requiredId(teamId)) { deny("SLACK_WORKSPACE_CLIENT_UNKNOWN", "Exact Slack workspace client is unavailable", "client_select"); } const selected = clients.get(teamId); if (!selected) { deny("SLACK_WORKSPACE_CLIENT_UNKNOWN", "Exact Slack workspace client is unavailable", "client_select"); } if ( selected.installationId !== installationId || selected.oauthGeneration !== oauthGeneration || selected.botUserId !== botUserId || (credentialFingerprint !== undefined && selected.credentialFingerprint !== credentialFingerprint) ) { deny("SLACK_WORKSPACE_CLIENT_STALE", "Slack workspace client identity is stale", "client_select"); } return selected; } const OPERATION_METHODS = Object.freeze({ message: "postMessage", status: "setStatus", reaction: "addReaction", file: "uploadFile", reply: "postReply", }); const EFFECT_ROUTING_KEYS = Object.freeze([ "teamId", "installationId", "botUserId", "channelId", "threadId", "profileId", "revisionId", ]); function assertPrincipal(principal) { if ( !principal || typeof principal !== "object" || !requiredId(principal.teamId) || !requiredId(principal.installationId) || !requiredId(principal.botUserId) || !requiredId(principal.channelId) || (principal.threadId !== null && !requiredId(principal.threadId)) || !requiredId(principal.profileId) || !requiredId(principal.revisionId) || !requiredId(principal.routeHash) || !positiveGeneration(principal.oauthGeneration) || !CREDENTIAL_FINGERPRINT.test(principal.credentialFingerprint ?? "") ) { deny("SLACK_EFFECT_PRINCIPAL_INVALID", "Slack effect requires a guarded principal", "egress"); } } export async function dispatchSlackWorkspaceEffect({ registry, principal, effect, revalidate }) { assertPrincipal(principal); if (!effect || typeof effect !== "object" || Array.isArray(effect)) { deny("SLACK_EFFECT_INVALID", "Slack effect requires a closed operation", "egress"); } const method = OPERATION_METHODS[effect.type]; if (!method || !requiredId(effect.effectId)) { deny("SLACK_EFFECT_INVALID", "Slack effect type or identity is invalid", "egress"); } if (EFFECT_ROUTING_KEYS.some((key) => Object.prototype.hasOwnProperty.call(effect, key))) { deny( "SLACK_EFFECT_ROUTING_OVERRIDE", "Slack effect cannot override its guarded route", "egress", ); } if (typeof revalidate !== "function") { deny("SLACK_EFFECT_REVALIDATION_REQUIRED", "Slack egress requires route revalidation", "egress"); } let current; try { current = await revalidate(principal); } catch (error) { if ( error && typeof error.code === "string" && ["SLACK_EGRESS_ROUTE_STALE", "SLACK_EGRESS_REVALIDATION_INVALID"].includes(error.code) ) { deny(error.code, "Slack route changed before egress", "egress_revalidate"); } deny( "SLACK_EFFECT_REVALIDATION_FAILED", "Slack route could not be revalidated before egress", "egress_revalidate", ); } if (!current || current.status !== "current" || current.routeHash !== principal.routeHash) { deny("SLACK_EFFECT_ROUTE_STALE", "Slack route changed before egress", "egress_revalidate"); } const workspace = selectSlackWorkspaceClient({ registry, teamId: principal.teamId, installationId: principal.installationId, oauthGeneration: principal.oauthGeneration, botUserId: principal.botUserId, credentialFingerprint: principal.credentialFingerprint, }); if (typeof workspace.client[method] !== "function") { deny("SLACK_EFFECT_OPERATION_UNSUPPORTED", "Slack client operation is unavailable", "egress"); } const exactRoute = Object.freeze({ teamId: principal.teamId, installationId: principal.installationId, botUserId: principal.botUserId, channelId: principal.channelId, threadId: principal.threadId, profileId: principal.profileId, revisionId: principal.revisionId, routeGeneration: principal.routeGeneration, oauthGeneration: principal.oauthGeneration, lifecycleGeneration: principal.lifecycleGeneration, routeHash: principal.routeHash, }); try { await workspace.client[method]({ route: exactRoute, effect }); } catch { deny("SLACK_EFFECT_SEND_FAILED", "Slack client operation failed", "egress_send"); } return Object.freeze({ status: "sent", teamId: principal.teamId, botUserId: principal.botUserId, effectId: effect.effectId, effectType: effect.type, receiptDigest: sha256( [ principal.routeHash, principal.teamId, principal.installationId, principal.profileId, principal.revisionId, effect.effectId, effect.type, ].join("\u0000"), ), }); }