mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
Keep Slack form identity stable through database storage and retirement
This commit is contained in:
1 parent
902a67b00f
commit
07dc097eb0
7 files changed
+93
-10
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { isSlackFormEnrollmentActionId } from "./form-enrollment-identity.js";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { createHash } from "node:crypto";
|
||||
import { parseSlackFormBinding as parseFormBinding, parseSlackFormPublicEnrollment, type SlackFormBinding as FormBinding } from "./cloud-forms.js";
|
||||
@@ -53,7 +54,7 @@ export function slackFormRetirementHistoryReceipt(row: SlackRetirementHistoryRow
|
||||
if (enrollment.bindingId !== binding.eventBindingId
|
||||
|| ["instanceId", "companyId", "endpointId", "publicId", "connectionId", "runtimeGeneration", "teamId", "appId"].some(key => Reflect.get(enrollment, key) !== Reflect.get(binding, key))) throw new Error("Slack retirement enrollment history changed");
|
||||
}
|
||||
if (row.kind === "slack_form_owner" && row.providerActionId !== `slack-form-owner:${createHash("sha256").update(JSON.stringify(parseSlackFormPublicEnrollment(row.payload.enrollment))).digest("hex")}`)
|
||||
if (row.kind === "slack_form_owner" && !isSlackFormEnrollmentActionId(row.providerActionId, parseSlackFormPublicEnrollment(row.payload.enrollment)))
|
||||
throw new Error("Slack retirement history owner changed");
|
||||
return receipt;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect, it } from "vitest";
|
||||
import { parseSlackFormPublicEnrollment } from "./cloud-forms.js";
|
||||
import { slackFormEnrollmentActionId, slackFormEnrollmentCompatibleActionIds, isSlackFormEnrollmentActionId } from "./form-enrollment-identity.js";
|
||||
|
||||
const enrollment = parseSlackFormPublicEnrollment({ version: 1, instanceId: "instance", companyId: "company", endpointId: "endpoint",
|
||||
publicId: "p".repeat(43), connectionId: "connection", runtimeGeneration: 1, bindingId: "slack-event:" + "a".repeat(64), teamId: "TTEST", appId: "ATEST" });
|
||||
const legacyId = (value: unknown) => `slack-form-owner:${createHash("sha256").update(JSON.stringify(value)).digest("hex")}`;
|
||||
it("uses a complete typed tuple independent of input and JSONB object order", () => {
|
||||
const reversed = parseSlackFormPublicEnrollment(Object.fromEntries(Object.entries(enrollment).reverse()));
|
||||
const postgresOrder = parseSlackFormPublicEnrollment(Object.fromEntries(Object.entries(enrollment).sort(([a], [b]) => Buffer.byteLength(a) - Buffer.byteLength(b) || a.localeCompare(b))));
|
||||
expect(slackFormEnrollmentActionId(reversed)).toBe(slackFormEnrollmentActionId(enrollment));
|
||||
expect(slackFormEnrollmentActionId(postgresOrder)).toBe(slackFormEnrollmentActionId(enrollment));
|
||||
expect(legacyId(reversed)).not.toBe(legacyId(enrollment));
|
||||
});
|
||||
it("recognizes only the exact known legacy producer orders for the same full authority tuple", () => {
|
||||
const e = enrollment;
|
||||
const connectionFirst = { version: e.version, instanceId: e.instanceId, companyId: e.companyId, endpointId: e.endpointId,
|
||||
connectionId: e.connectionId, publicId: e.publicId, runtimeGeneration: e.runtimeGeneration, teamId: e.teamId, appId: e.appId, bindingId: e.bindingId };
|
||||
const publicFirst = { version: e.version, instanceId: e.instanceId, companyId: e.companyId, endpointId: e.endpointId,
|
||||
publicId: e.publicId, connectionId: e.connectionId, runtimeGeneration: e.runtimeGeneration, teamId: e.teamId, appId: e.appId, bindingId: e.bindingId };
|
||||
for (const previous of [enrollment, connectionFirst, publicFirst])
|
||||
expect(isSlackFormEnrollmentActionId(legacyId(previous), parseSlackFormPublicEnrollment(Object.fromEntries(Object.entries(previous).reverse())))).toBe(true);
|
||||
expect(slackFormEnrollmentCompatibleActionIds(enrollment)).toHaveLength(4);
|
||||
expect(isSlackFormEnrollmentActionId(legacyId(Object.fromEntries(Object.entries(enrollment).reverse())), enrollment)).toBe(false);
|
||||
expect(isSlackFormEnrollmentActionId("slack-form-owner:" + "0".repeat(64), enrollment)).toBe(false);
|
||||
});
|
||||
it("every authority field is bound for canonical and compatible identities", () => {
|
||||
const variants = { instanceId: "other-instance", companyId: "other-company", endpointId: "other-endpoint", publicId: "q".repeat(43),
|
||||
connectionId: "other-connection", runtimeGeneration: 2, bindingId: "slack-event:" + "b".repeat(64), teamId: "TOTHER", appId: "AOTHER" };
|
||||
for (const [key, value] of Object.entries(variants)) {
|
||||
const changed = parseSlackFormPublicEnrollment({ ...enrollment, [key]: value });
|
||||
for (const id of slackFormEnrollmentCompatibleActionIds(enrollment)) expect(isSlackFormEnrollmentActionId(id, changed)).toBe(false);
|
||||
}
|
||||
});
|
||||
it("does not accept a different schema version or extra authority keys", () => {
|
||||
expect(() => parseSlackFormPublicEnrollment({ ...enrollment, version: 2 })).toThrow();
|
||||
expect(() => parseSlackFormPublicEnrollment({ ...enrollment, unexpected: "authority" })).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { parseSlackFormPublicEnrollment, type SlackFormPublicEnrollment } from "./cloud-forms.js";
|
||||
|
||||
function actionId(value: readonly unknown[] | SlackFormPublicEnrollment): string {
|
||||
return `slack-form-owner:${createHash("sha256").update(JSON.stringify(value)).digest("hex")}`;
|
||||
}
|
||||
export function slackFormEnrollmentActionId(input: SlackFormPublicEnrollment): string {
|
||||
const e = parseSlackFormPublicEnrollment(input);
|
||||
return actionId(["slack-form-owner/v2", e.version, e.instanceId, e.companyId, e.endpointId, e.publicId,
|
||||
e.connectionId, e.runtimeGeneration, e.bindingId, e.teamId, e.appId]);
|
||||
}
|
||||
export function slackFormEnrollmentCompatibleActionIds(input: SlackFormPublicEnrollment): readonly string[] {
|
||||
const e = parseSlackFormPublicEnrollment(input);
|
||||
const projected: SlackFormPublicEnrollment = { version: e.version, instanceId: e.instanceId, companyId: e.companyId,
|
||||
endpointId: e.endpointId, publicId: e.publicId, connectionId: e.connectionId, runtimeGeneration: e.runtimeGeneration,
|
||||
bindingId: e.bindingId, teamId: e.teamId, appId: e.appId };
|
||||
const bindingDerived: SlackFormPublicEnrollment = { version: e.version, instanceId: e.instanceId, companyId: e.companyId,
|
||||
endpointId: e.endpointId, connectionId: e.connectionId, publicId: e.publicId, runtimeGeneration: e.runtimeGeneration,
|
||||
teamId: e.teamId, appId: e.appId, bindingId: e.bindingId };
|
||||
const publicFirstBinding: SlackFormPublicEnrollment = { version: e.version, instanceId: e.instanceId, companyId: e.companyId,
|
||||
endpointId: e.endpointId, publicId: e.publicId, connectionId: e.connectionId, runtimeGeneration: e.runtimeGeneration,
|
||||
teamId: e.teamId, appId: e.appId, bindingId: e.bindingId };
|
||||
return [slackFormEnrollmentActionId(e), actionId(projected), actionId(bindingDerived), actionId(publicFirstBinding)];
|
||||
}
|
||||
export function isSlackFormEnrollmentActionId(providerActionId: unknown, enrollment: SlackFormPublicEnrollment): boolean {
|
||||
return typeof providerActionId === "string" && slackFormEnrollmentCompatibleActionIds(enrollment).includes(providerActionId);
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { slackFormEnrollmentActionId, slackFormEnrollmentCompatibleActionIds } from "./form-enrollment-identity.js";
|
||||
import { acceptSlackFormRetirementLocally, transferSlackFormRetirement } from "./form-retirement-work.js";
|
||||
import { reconcileSlackFormNormalAck } from "./form-ack-work.js";
|
||||
import { HttpError } from "../../../errors.js";
|
||||
import { createPaperclipCloudConnector, paperclipCloudConnectorConfigFromEnv, PaperclipCloudConnectorError } from "../../paperclip-cloud-connector.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { chatActions, chatEndpoints, chatPublications, issueThreadInteractions, toolConnections, type Db } from "@paperclipai/db";
|
||||
import { notifyDeliveryWork, DELIVERY_QUEUES } from "../../delivery-work-notifications.js";
|
||||
import { resolveChatQuestionFormOpen, type ResolvedChatQuestionFormOpen } from "../../chat-question-forms.js";
|
||||
@@ -17,7 +17,6 @@ import { slackFormConnectorIdentity, type SlackFormConnectorIdentity } from "./c
|
||||
|
||||
type Tx = Pick<Db, "select" | "insert" | "update">;
|
||||
export type SlackFormProtocol = (input: { subject: string; companyId: string; operation: Record<string, unknown> }) => Promise<unknown>;
|
||||
const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
||||
function attention(code: string): never { throw new SlackCloudReceiptError(code, "attention"); }
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return attention("form_owner_response_invalid");
|
||||
@@ -45,8 +44,11 @@ export async function stageSlackFormEnrollment(tx: Tx, input: { enrollment: Slac
|
||||
|| endpoint.publicId !== enrollment.publicId || endpoint.connectionId !== enrollment.connectionId
|
||||
|| setup?.runtimeGeneration !== enrollment.runtimeGeneration || setup?.slackCloudInstanceId !== enrollment.instanceId
|
||||
|| setup?.slackCloudSubject !== input.subject || !isDeepStrictEqual(projectSlackFormPublicEnrollment(endpoint), enrollment)) return attention("form_owner_current_enrollment_changed");
|
||||
const providerActionId = `slack-form-owner:${hash(enrollment)}`;
|
||||
const [existing] = await tx.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id), eq(chatActions.companyId, endpoint.companyId), eq(chatActions.providerActionId, providerActionId))).for("update");
|
||||
const providerActionId = slackFormEnrollmentActionId(enrollment);
|
||||
const existingRows = await tx.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id), eq(chatActions.companyId, endpoint.companyId),
|
||||
inArray(chatActions.providerActionId, [...slackFormEnrollmentCompatibleActionIds(enrollment)]))).for("update");
|
||||
if (existingRows.length > 1) return attention("form_owner_identity_ambiguous");
|
||||
const [existing] = existingRows;
|
||||
const payload = { enrollment, subject: input.subject, environment: input.environment };
|
||||
if (existing) {
|
||||
if (existing.kind !== "slack_form_owner" || !Object.keys(payload).every(key => isDeepStrictEqual(existing.payload[key], Reflect.get(payload, key)))) return attention("form_owner_custody_changed");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { isSlackFormEnrollmentActionId } from "./form-enrollment-identity.js";
|
||||
import { replaceSlackFormReceiptSignature } from "./form-signature-refresh.js";
|
||||
import { parseSlackFormRetirementReceipt } from "./ack-retirement-receipt.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { chatActions, type Db } from "@paperclipai/db";
|
||||
@@ -24,8 +24,7 @@ export function assertSlackFormRetirementWorkAuthority(row: Row, identity: Slack
|
||||
throw new SlackCloudReceiptError("form_retirement_fingerprint_changed", "attention");
|
||||
if (row.result?.retirementReceipt !== undefined && !isDeepStrictEqual(row.result.retirementReceipt, receipt))
|
||||
throw new SlackCloudReceiptError("form_retirement_receipt_changed", "attention");
|
||||
const expectedAction = `slack-form-owner:${createHash("sha256").update(JSON.stringify(enrollment)).digest("hex")}`;
|
||||
if (row.providerActionId !== expectedAction) throw new SlackCloudReceiptError("form_retirement_owner_changed", "attention");
|
||||
if (!isSlackFormEnrollmentActionId(row.providerActionId, enrollment)) throw new SlackCloudReceiptError("form_retirement_owner_changed", "attention");
|
||||
}
|
||||
export function verifyRetainedSlackFormRetirement(compactJws: string) {
|
||||
try { return verifySlackFormRetirementReceipt({ compactJws }); }
|
||||
|
||||
@@ -72,3 +72,17 @@ it("only exact committed transfer discharges history and its retained consumer",
|
||||
expect(() => slackFormRetirementHistoryReceipt({ ...current, result: { ...current.result, retirement: { ...retirement, receiptDigest: "0".repeat(64) } } })).toThrow();
|
||||
expect(() => slackFormRetirementHistoryReceipt({ ...current, result: { phase: "transferred", nextAttemptAt: null } })).toThrow();
|
||||
});
|
||||
|
||||
it("preserves exact legacy custody through JSONB ordering for acceptance, polling and history", () => {
|
||||
const current = row();
|
||||
current.payload = { ...current.payload, enrollment: Object.fromEntries(Object.entries(enrollment).sort(([a], [b]) => Buffer.byteLength(a) - Buffer.byteLength(b) || a.localeCompare(b))) };
|
||||
expect(() => assertSlackFormRetirementWorkAuthority(current, identity, receipt)).not.toThrow();
|
||||
const input = signed();
|
||||
current.result = { phase: "retirement_accepted", retirementReceipt: receipt, retirementReceiptJws: input.compactJws, nextAttemptAt: new Date(0).toISOString() };
|
||||
expect(projectSlackFormRetainedOwner(current, identity.instanceId, identity.environment)?.requiresDelivery).toBe(false);
|
||||
current.status = "processed";
|
||||
current.result = { phase: "transferred", nextAttemptAt: null, retirement: { version: 1, binding, instanceId: identity.instanceId,
|
||||
environment: identity.environment, subject: receipt.subject, receiptDigest: receipt.receiptId, receipt } };
|
||||
expect(slackFormRetirementHistoryReceipt(current)).toEqual(receipt);
|
||||
expect(projectSlackFormRetainedOwner(current, identity.instanceId, identity.environment)).toBeNull();
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isSlackFormEnrollmentActionId } from "./form-enrollment-identity.js";
|
||||
import { parseSlackFormRetirementReceipt, slackFormRetirementHistoryReceipt } from "./ack-retirement-receipt.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { IssueThreadInteraction } from "@paperclipai/shared";
|
||||
@@ -334,7 +335,7 @@ export function projectSlackFormRetainedOwner(row: SlackFormRetainedRow, current
|
||||
const receipt = parseSlackFormRetirementReceipt(row.result.retirementReceipt), enrollment = parseSlackFormPublicEnrollment(row.payload.enrollment), binding = receipt.binding;
|
||||
if (receipt.binding.instanceId !== currentInstanceId || currentEnvironment !== undefined && receipt.environment !== currentEnvironment) return null;
|
||||
if (row.companyId !== binding.companyId || row.endpointId !== binding.endpointId || row.payload.subject !== receipt.subject
|
||||
|| row.providerActionId !== `slack-form-owner:${createHash("sha256").update(JSON.stringify(enrollment)).digest("hex")}`
|
||||
|| !isSlackFormEnrollmentActionId(row.providerActionId, enrollment)
|
||||
|| row.payload.environment !== receipt.environment || typeof row.result.retirementReceiptJws !== "string"
|
||||
|| Buffer.byteLength(row.result.retirementReceiptJws, "ascii") > 12000
|
||||
|| !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(row.result.retirementReceiptJws)
|
||||
|
||||
Reference in new issue
Block a user