diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index 5d1638defc5..07cbfa2e92c 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -1122,7 +1122,7 @@ const support = await getEmbeddedPostgresTestSupport(); expect(f.transport.configureTool.mock.calls.slice(-3).every((call) => Boolean(call[3]))).toBe(true); }); - it("moves only receipt-owned tools and lifecycle hooks when the callback origin changes", async () => { + it.each(["current", "legacy"])("moves only receipt-owned %s tools and hooks when callback origin and signing secret change", async proofVersion => { const f = await nativeServiceFixture(); const tools: {id: string; name: string; source: {kind: string; url: string}}[] = []; f.transport.listTools.mockImplementation(async () => structuredClone(tools) as never[]); @@ -1135,10 +1135,18 @@ const support = await getEmbeddedPostgresTestSupport(); const input = {companyId: f.companyId, endpointId: f.endpointId, agentId: "agent_test", callbackUrl: "https://old-tunnel.example.test/tools", signingSecret: "whsec_fixture", client: f.transport, assertOwned: async () => {}}; await configureSpekoSessionTools(db, input); const oldIds = tools.map(t => t.id); - await configureSpekoSessionTools(db, {...input, callbackUrl: "https://new-tunnel.example.test/tools"}); + if (proofVersion === "legacy") { + const actions = await db.select().from(chatActions).where(eq(chatActions.endpointId, f.endpointId)); + for (const action of actions) await db.update(chatActions).set({payload: {name: action.payload.name, fingerprint: action.payload.fingerprint}}).where(eq(chatActions.id, action.id)); + } + const rotated = {...input, callbackUrl: "https://new-tunnel.example.test/tools", signingSecret: "whsec_rotated", + ...(proofVersion === "legacy" ? {previousSigningSecret: input.signingSecret} : {})}; + await configureSpekoSessionTools(db, rotated); + expect(f.transport.configureTool.mock.calls.slice(-3).every(call => call[2] === "whsec_rotated")).toBe(true); expect(tools.map(t => t.id)).toEqual(oldIds); expect(tools.every(t => t.source.url === "https://new-tunnel.example.test/tools")).toBe(true); expect(f.transport.configureWebhook.mock.calls.at(-1)?.[3]).toBe("hook_test"); + expect(f.transport.configureWebhook.mock.calls.at(-1)?.[2]).toBe("whsec_rotated"); // Even the same provider ID is no longer ours if its URL was changed outside // Paperclip. A historical ID alone cannot authorize overwriting it. tools[0]!.source.url = "https://another-app.example.test/tools"; diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index 4f5cda8716f..51c4b86af2f 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -9521,6 +9521,8 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { verifiedCurrentIdentity = storedIdentity; } + const previousSpekoSigningSecret = endpoint.provider === "speko" + ? (await resolveCredentials(endpoint).catch(() => ({} as Record))).signingSecret : undefined; let credentials = input.credentials && Object.keys(input.credentials).length > 0 ? await normalizedCredentials(endpoint, input.credentials) @@ -9754,7 +9756,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { if (next.endpoint.provider === "speko") { const webhookPublicBaseUrl = getWebhookPublicBaseUrl(); if (!webhookPublicBaseUrl?.startsWith("https://")) throw unprocessable("Speko needs an explicitly configured public HTTPS callback origin"); - await configureSpekoSessionTools(db, { companyId: endpoint.companyId, endpointId: endpoint.id, agentId: credentials.agentId, callbackUrl: `${webhookPublicBaseUrl}/api/voice-webhooks/${endpoint.publicId}/tools`, signingSecret: credentials.signingSecret, client: createSpekoProvider(credentials.apiKey, fetchImpl), assertOwned: () => credentialLease.assertOwned() }); + await configureSpekoSessionTools(db, { companyId: endpoint.companyId, endpointId: endpoint.id, agentId: credentials.agentId, callbackUrl: `${webhookPublicBaseUrl}/api/voice-webhooks/${endpoint.publicId}/tools`, signingSecret: credentials.signingSecret, previousSigningSecret: previousSpekoSigningSecret, client: createSpekoProvider(credentials.apiKey, fetchImpl), assertOwned: () => credentialLease.assertOwned() }); } if (next.endpoint.provider === "discord") await reconcileDiscordCommands(endpoint.id, credentialLease, true); diff --git a/server/src/services/voice/speko-tool-setup.ts b/server/src/services/voice/speko-tool-setup.ts index 8a81d16efc5..b56d6b239bf 100644 --- a/server/src/services/voice/speko-tool-setup.ts +++ b/server/src/services/voice/speko-tool-setup.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { and, eq } from "drizzle-orm"; +import { and, eq, or, sql } from "drizzle-orm"; import { chatActions, type Db } from "@paperclipai/db"; import { conflict } from "../../errors.js"; import { spekoToolDefinitions } from "./speko-protocol.js"; @@ -8,6 +8,7 @@ import { createSpekoProvider, SpekoProviderError } from "./speko-provider.js"; /** Called while the existing connection credential lease is held. */ export async function configureSpekoSessionTools(db: Db, input: { companyId: string; endpointId: string; agentId: string; callbackUrl: string; signingSecret: string; + previousSigningSecret?: string; client: ReturnType; assertOwned(): Promise; }) { const definitions = spekoToolDefinitions(input.callbackUrl); @@ -30,18 +31,31 @@ export async function configureSpekoSessionTools(db: Db, input: { // definition and provider ID have a completed receipt on this endpoint. const oldDefinition = existing.source.kind === "webhook" && existing.source.url ? spekoToolDefinitions(existing.source.url).find(tool => tool.name === definition.name) : null; - const oldFingerprint = oldDefinition && createHash("sha256").update(JSON.stringify({agentId: input.agentId, definition: oldDefinition, signingSecret: input.signingSecret})).digest("hex"); - const [owned] = oldFingerprint ? await db.select().from(chatActions).where(and(eq(chatActions.companyId, input.companyId), eq(chatActions.endpointId, input.endpointId), eq(chatActions.providerActionId, `speko_tool:${definition.name}:${oldFingerprint}`))) : []; + const oldFingerprint = oldDefinition && createHash("sha256").update(JSON.stringify({agentId: input.agentId, definition: oldDefinition, signingSecret: input.previousSigningSecret ?? input.signingSecret})).digest("hex"); + const oldDefinitionHash = oldDefinition && createHash("sha256").update(JSON.stringify(oldDefinition)).digest("hex"); + const [owned] = oldFingerprint ? await db.select().from(chatActions).where(and( + eq(chatActions.companyId, input.companyId), eq(chatActions.endpointId, input.endpointId), + eq(chatActions.kind, "speko_tool_setup"), eq(chatActions.status, "completed"), + sql`${chatActions.result}->>'toolId' = ${existing.id}`, + or(eq(chatActions.providerActionId, `speko_tool:${definition.name}:${oldFingerprint}`), + and(sql`${chatActions.payload}->>'ownershipAgentId' = ${input.agentId}`, + sql`${chatActions.payload}->>'ownershipDefinitionHash' = ${oldDefinitionHash}`)) + )).limit(1) : []; if (owned?.status !== "completed" || owned.result?.toolId !== existing.id) { throw conflict("This Speko voice agent has tools connected elsewhere. Choose a dedicated voice agent."); } + // Upgrade legacy proof before changing the provider callback. A failed + // PATCH/retry no longer depends on the secret being replaced. + await input.assertOwned(); + await db.update(chatActions).set({payload: {...owned.payload, ownershipAgentId: input.agentId, + ownershipDefinitionHash: oldDefinitionHash}, updatedAt: new Date()}).where(eq(chatActions.id, owned.id)); } const fingerprint = createHash("sha256").update(JSON.stringify({ agentId: input.agentId, definition, signingSecret: input.signingSecret })).digest("hex"); const actionId = `speko_tool:${definition.name}:${fingerprint}`; let [action] = await db.select().from(chatActions).where(and(eq(chatActions.companyId, input.companyId), eq(chatActions.endpointId, input.endpointId), eq(chatActions.providerActionId, actionId))); if (action && action.status !== "failed" && !existing) throw conflict("A previous Speko tool setup has an uncertain outcome. Inspect the voice agent's tools before reconnecting."); if (!action) { - [action] = await db.insert(chatActions).values({ companyId: input.companyId, endpointId: input.endpointId, kind: "speko_tool_setup", providerActionId: actionId, status: "processing", payload: { name: definition.name, fingerprint } }).returning(); + [action] = await db.insert(chatActions).values({ companyId: input.companyId, endpointId: input.endpointId, kind: "speko_tool_setup", providerActionId: actionId, status: "processing", payload: { name: definition.name, fingerprint, ownershipAgentId: input.agentId, ownershipDefinitionHash: createHash("sha256").update(JSON.stringify(definition)).digest("hex") } }).returning(); } // A recovered matching tool is repaired with an idempotent PATCH. GET does // not expose the secret, so presence alone cannot verify the signing key. @@ -70,16 +84,27 @@ export async function configureSpekoSessionTools(db: Db, input: { for (const hook of scoped) { if (hook.allAgents || hook.agentIds.length !== 1 || Object.keys(hook.filterTags).length) continue; if (hook.url === callback.href) { matching.push(hook); continue; } - const oldFingerprint = createHash("sha256").update(JSON.stringify({agentId: input.agentId, url: hook.url, secret: input.signingSecret})).digest("hex"); - const [owned] = await db.select().from(chatActions).where(and(eq(chatActions.companyId, input.companyId), eq(chatActions.endpointId, input.endpointId), eq(chatActions.providerActionId, `speko_lifecycle:${oldFingerprint}`))); - if (owned?.status === "completed" && owned.result?.webhookId === hook.id) matching.push(hook); + const oldFingerprint = createHash("sha256").update(JSON.stringify({agentId: input.agentId, url: hook.url, secret: input.previousSigningSecret ?? input.signingSecret})).digest("hex"); + const [owned] = await db.select().from(chatActions).where(and( + eq(chatActions.companyId, input.companyId), eq(chatActions.endpointId, input.endpointId), + eq(chatActions.kind, "speko_lifecycle_setup"), eq(chatActions.status, "completed"), + sql`${chatActions.result}->>'webhookId' = ${hook.id}`, + or(eq(chatActions.providerActionId, `speko_lifecycle:${oldFingerprint}`), + and(sql`${chatActions.payload}->>'ownershipAgentId' = ${input.agentId}`, + sql`${chatActions.payload}->>'ownershipUrl' = ${hook.url}`)) + )).limit(1); + if (owned) { + await input.assertOwned(); + await db.update(chatActions).set({payload: {...owned.payload, ownershipAgentId: input.agentId, ownershipUrl: hook.url}, updatedAt: new Date()}).where(eq(chatActions.id, owned.id)); + matching.push(hook); + } } if (matching.length > 1 || scoped.some(hook => hook.events.includes("call.pre_call") && !matching.includes(hook))) throw conflict("This Speko persona already has another pre-call webhook. Use a dedicated voice persona."); const fingerprint = createHash("sha256").update(JSON.stringify({ agentId: input.agentId, url: callback.href, secret: input.signingSecret })).digest("hex"); const actionId = `speko_lifecycle:${fingerprint}`; const [previous] = await db.select().from(chatActions).where(and(eq(chatActions.companyId, input.companyId), eq(chatActions.endpointId, input.endpointId), eq(chatActions.providerActionId, actionId))); if (previous && previous.status !== "failed" && !matching.length) throw conflict("Speko webhook setup has an uncertain outcome. Inspect Webhooks in Speko before reconnecting."); - const action = previous ?? (await db.insert(chatActions).values({companyId: input.companyId, endpointId: input.endpointId, kind: "speko_lifecycle_setup", providerActionId: actionId, status: "processing", payload: { fingerprint }}).returning())[0]!; + const action = previous ?? (await db.insert(chatActions).values({companyId: input.companyId, endpointId: input.endpointId, kind: "speko_lifecycle_setup", providerActionId: actionId, status: "processing", payload: { fingerprint, ownershipAgentId: input.agentId, ownershipUrl: callback.href }}).returning())[0]!; await input.assertOwned(); try { const receipt = await input.client.configureWebhook(input.agentId, callback.href, input.signingSecret, matching[0]?.id);