mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
Recover Slack form custody and discharge completed receipt work
This commit is contained in:
1 parent
07dc097eb0
commit
6f4ec722b5
11 files changed
+227
-31
No files matched your search
@@ -273,3 +273,26 @@ describe("retained form consumer identity", () => {
|
||||
expect(result.owner).toEqual({ subject: "github-bot-events", companyId: "company", binding: null, requiresDelivery: true });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
it("retained session selection keeps unfinished GC custody but completed exact receipt history supplies no consumer", () => {
|
||||
const f = closedProofFixture(), proof = prepareSlackFormProofAcceptance(f.intent, f.operation, "instance");
|
||||
const receipt = { version: 1 as const, kind: "slack_form_finalized" as const, binding: f.intent.binding, environment: "test" as const,
|
||||
operationId: f.intent.operationId, deliveryId: f.intent.deliveryId, appReceiptId: f.row.id, grantId: f.intent.grantId,
|
||||
publicationId: f.intent.publicationId, interactionId: f.intent.interactionId, userId: f.intent.userId,
|
||||
viewDigest: hash(JSON.stringify([f.intent.view!.id, f.intent.view!.hash, f.intent.view!.externalId])),
|
||||
terminalDigest: proof.terminalDigest, outcome: "closed" as const, finalizedAt: f.operation.acceptedAt };
|
||||
const base = { ...f.row, payload: { ...f.row.payload, environment: "test" }, result: { ...f.row.result, cloudProofAcceptance: proof,
|
||||
formAck: { version: 1, phase: "transferred", leaseId: "exact-lease", deliveryId: receipt.deliveryId, receiptJws: "a.b.c", receipt }, nextAttemptAt: null } };
|
||||
const identity = { instanceId: "instance", environment: "test" as const };
|
||||
expect(selectSlackFormRetainedConsumer([base], identity)).toEqual({ owner: null, attention: [] });
|
||||
for (const phase of ["accepted", "gc_pending"]) {
|
||||
const pending = { ...base, result: { ...base.result, formAck: { ...base.result.formAck, phase }, nextAttemptAt: f.operation.acceptedAt } };
|
||||
expect(selectSlackFormRetainedConsumer([pending], identity).owner).toMatchObject({ companyId: f.row.companyId, subject: "github-bot-events", requiresDelivery: false });
|
||||
}
|
||||
const malformed = { ...base, result: { ...base.result, formAck: { ...base.result.formAck, receipt: { ...receipt, binding: { ...receipt.binding, companyId: "foreign" } } } } };
|
||||
const result = selectSlackFormRetainedConsumer([malformed], identity);
|
||||
expect(result.owner !== null || result.attention.length > 0).toBe(true);
|
||||
const stillDue = { ...base, result: { ...base.result, nextAttemptAt: f.operation.acceptedAt } };
|
||||
expect(selectSlackFormRetainedConsumer([stillDue], identity).owner).not.toBeNull();
|
||||
});
|
||||
@@ -1,3 +1,8 @@
|
||||
import { readSlackFormRetainedConsumer } from "../services/chat-channels/slack/cloud-consumer.js";
|
||||
import { transferSlackFormAckReceipt } from "../services/chat-channels/slack/form-ack-work.js";
|
||||
import { parseSlackFormFinalizedReceipt, slackFormFinalizedReceiptDigest } from "../services/chat-channels/slack/ack-receipt.js";
|
||||
import { createPaperclipCloudConnector } from "../services/paperclip-cloud-connector.js";
|
||||
import { githubConnectionEventService } from "../services/github-connection-events.js";
|
||||
import { generateKeyPairSync, randomUUID, sign } from "node:crypto";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -212,4 +217,54 @@ if (process.env.SLACK_GATE_EXPECT_PRELOAD === "1" && !external) throw new Error(
|
||||
await transferSlackFormRetirement(db, await row(), identity, protocol); expect((await row()).result?.phase).toBe("transferred"); expect(releases).toBe(1);
|
||||
});
|
||||
|
||||
it("a real paused endpoint polls reconstructed GC debt but completed exact session history stops recurring empty leases", async () => {
|
||||
await acceptSlackFormRetirementLocally(db, await row(), identity, compactJws);
|
||||
const retirementDigest = slackFormRetirementReceipt(binding, identity.environment, actorId).receiptId;
|
||||
const retirementProtocol = async (input: { operation: Record<string, unknown> }) => input.operation.refreshRetirementReceipt
|
||||
? { retirementReceiptJws: compactJws } : input.operation.acceptedRetirementReceipt
|
||||
? { acceptedRetirementDigest: retirementDigest } : { releasedRetirementDigest: retirementDigest };
|
||||
await transferSlackFormRetirement(db, await row(), identity, retirementProtocol);
|
||||
await transferSlackFormRetirement(db, await row(), identity, retirementProtocol);
|
||||
expect((await row()).result?.phase).toBe("transferred");
|
||||
expect((await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpointId)))[0]?.status).toBe("paused");
|
||||
const sessionId = randomUUID(), operationId = "c".repeat(64), deliveryId = `slack_form_${operationId}`, now = new Date().toISOString();
|
||||
const receipt = parseSlackFormFinalizedReceipt({ version: 1, kind: "slack_form_finalized", environment: identity.environment, binding,
|
||||
operationId, deliveryId, appReceiptId: sessionId, grantId: "grant", publicationId: "publication", interactionId: "interaction", userId: "UTEST",
|
||||
viewDigest: null, terminalDigest: "d".repeat(64), outcome: "no_effect", finalizedAt: now });
|
||||
const pair = generateKeyPairSync("ed25519"), kid = "session-canonical-control";
|
||||
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
const input = encode({ alg: "EdDSA", typ: "paperclip-connector-ack-receipt+jwt", kid }) + "." + encode({ v: 1, iss: "paperclip-cloud", aud: "paperclip-connector-ack-receipt/v1", sub: identity.instanceId, receipt });
|
||||
const receiptJws = input + "." + sign(null, Buffer.from(input), pair.privateKey).toString("base64url");
|
||||
const terminalIntent = { version: 1, binding, operationId, deliveryId, userId: "UTEST", grantId: "grant", publicationId: "publication", interactionId: "interaction",
|
||||
appReceiptId: sessionId, view: null, outcome: "no_effect", submitReceiptId: null, rejectionDigest: receipt.terminalDigest, encryptedEvidence: null };
|
||||
await db.insert(chatActions).values({ id: sessionId, companyId, endpointId, kind: "slack_form_session", providerActionId: `slack-form-session:${operationId}`,
|
||||
status: "failed", payload: { binding, environment: identity.environment, operationId, userId: "UTEST", grantId: "grant", publicationId: "publication", interactionId: "interaction" },
|
||||
result: { phase: "not_opened", terminalIntent,
|
||||
cloudProofAcceptance: { version: 1, binding, operationId, appReceiptId: sessionId, outcome: "no_effect", terminalDigest: receipt.terminalDigest, acceptedAt: now },
|
||||
formAck: { version: 1, phase: "gc_pending", leaseId: "exact-session-lease", deliveryId, receiptJws, receipt }, nextAttemptAt: now } });
|
||||
const signing = generateKeyPairSync("ed25519"), sealing = generateKeyPairSync("x25519");
|
||||
const signPrivateKey = signing.privateKey.export({ format: "jwk" }).d, sealPrivateKey = sealing.privateKey.export({ format: "jwk" }).d;
|
||||
if (!signPrivateKey || !sealPrivateKey) throw new Error("normal controlled connector private keys absent");
|
||||
const connector = createPaperclipCloudConnector({ config: { baseUrl: "https://broker.example.test", instanceId: identity.instanceId,
|
||||
environment: identity.environment, signPrivateKey, sealPrivateKey }, request: async () => { throw new Error("Unexpected external connector request"); } });
|
||||
const lease = vi.spyOn(connector, "leaseEvents").mockResolvedValue(null);
|
||||
expect((await readSlackFormRetainedConsumer(db, connector)).owner).toMatchObject({ companyId, requiresDelivery: false });
|
||||
const pendingWorker = githubConnectionEventService(db, { connector, env: { PAPERCLIP_GITHUB_EVENT_POLLING: "1" } });
|
||||
await pendingWorker.pollOnce(); expect(lease).toHaveBeenCalledTimes(1); expect(pendingWorker.nextPollAt()).not.toBeNull();
|
||||
let releases = 0;
|
||||
await transferSlackFormAckReceipt(db, { companyId, actionId: sessionId, instanceId: identity.instanceId, protocol: async values => {
|
||||
expect(values.subject).toBe("github-bot-events"); expect(values.companyId).toBe(companyId);
|
||||
expect(values.operation).toEqual({ kind: "receipt", binding, operationId, deliveryId,
|
||||
releaseAckFact: { leaseId: "exact-session-lease", receiptDigest: slackFormFinalizedReceiptDigest(receipt), appReceiptId: sessionId } });
|
||||
releases++; return { releasedAckDigest: slackFormFinalizedReceiptDigest(receipt) };
|
||||
} });
|
||||
const [completed] = await db.select().from(chatActions).where(and(eq(chatActions.id, sessionId), eq(chatActions.companyId, companyId)));
|
||||
expect(completed?.result?.formAck).toMatchObject({ phase: "transferred", leaseId: "exact-session-lease", receipt });
|
||||
expect(completed?.result?.nextAttemptAt).toBeNull(); expect(releases).toBe(1);
|
||||
expect(await readSlackFormRetainedConsumer(db, connector)).toEqual({ owner: null, attention: [] });
|
||||
const completedWorker = githubConnectionEventService(db, { connector, env: { PAPERCLIP_GITHUB_EVENT_POLLING: "1" } });
|
||||
await completedWorker.pollOnce(); expect(lease).toHaveBeenCalledTimes(2); expect(completedWorker.nextPollAt()).toBeNull();
|
||||
await completedWorker.pollOnce(); expect(lease).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -2514,6 +2514,19 @@ for (const operation of githubBotOperations) {
|
||||
});
|
||||
}
|
||||
|
||||
registry.registerPath({
|
||||
"x-paperclip-transport": "rest",
|
||||
"x-paperclip-connection-management": "connections:configure",
|
||||
method: "post",
|
||||
path: "/api/chat-endpoints/{endpointId}/provider-work/{actionId}/retry",
|
||||
tags: ["chat-channels"],
|
||||
summary: "Retry retained provider receipt work",
|
||||
description: "Requires current company connection-management access. Rearms only the same authorized retained Slack receipt or cleanup responsibility. Does not create a new form or spend a trigger. Revoked, foreign, or changed ownership is refused.",
|
||||
request: { params: z.object({ endpointId: z.string().uuid(), actionId: z.string().uuid() }), body: jsonBody(z.object({}).strict()) },
|
||||
responses: { 200: r.ok(z.object({ actionId: z.string().uuid(), state: z.enum(["scheduled", "already_scheduled", "complete"]) })),
|
||||
400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
"x-paperclip-transport": "rest",
|
||||
"x-paperclip-connection-management": "connections:configure",
|
||||
|
||||
@@ -1045,12 +1045,20 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ id: chatActions.id });
|
||||
if (cloudForm && attempt) {
|
||||
if (cloudForm) {
|
||||
if (!lease || !cloudForm.environment) throw new SlackCloudReceiptError("form_credential_lease_unavailable", "retry");
|
||||
const held = await stageSlackFormSession(tx, { operation: cloudForm.operation, currentBinding: cloudForm.currentBinding,
|
||||
principalId: principal.principal.id, resolved, lease, environment: cloudForm.environment });
|
||||
cloudForm.sessionActionId = held.actionId;
|
||||
if (held.kind !== "update") return { kind: "duplicate" as const };
|
||||
if (!attempt) {
|
||||
const [retainedAttempt] = await tx.select().from(chatActions).where(and(eq(chatActions.companyId, record.endpoint.companyId),
|
||||
eq(chatActions.endpointId, record.endpoint.id), eq(chatActions.conversationId, conversation.id),
|
||||
eq(chatActions.principalId, principal.principal.id), eq(chatActions.kind, "question_form_open_attempt"),
|
||||
eq(chatActions.providerActionId, attemptProviderActionId))).for("update");
|
||||
if (!retainedAttempt || retainedAttempt.status !== "processing") throw new SlackCloudReceiptError("form_open_attempt_unresolved", "attention");
|
||||
return { kind: "ready" as const, attemptActionId: retainedAttempt.id, resolved };
|
||||
}
|
||||
}
|
||||
return attempt
|
||||
? {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { completedSlackFormSessionReceipt } from "./form-idle-history.js";
|
||||
import { and, inArray, sql } from "drizzle-orm";
|
||||
import { chatActions, type Db } from "@paperclipai/db";
|
||||
import { projectSlackFormRetainedOwner, type SlackFormRetainedRow } from "./form-session.js";
|
||||
@@ -25,6 +26,8 @@ export function selectSlackFormRetainedConsumer(rows: readonly SlackFormRetained
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const value = projectSlackFormRetainedOwner(row, identity.instanceId, identity.environment);
|
||||
if (value && row.kind === "slack_form_session" && row.result?.formAck && typeof row.result.formAck === "object"
|
||||
&& Reflect.get(row.result.formAck, "phase") === "transferred" && completedSlackFormSessionReceipt(row)) continue;
|
||||
if (value && !owner) owner = value;
|
||||
} catch {
|
||||
attention.push({ actionId: row.id, code: "form_retained_owner_invalid" });
|
||||
|
||||
@@ -46,3 +46,13 @@ export function completedSlackFormHistoryActionIds(rows: readonly SlackFormHisto
|
||||
}
|
||||
return [...completed].sort();
|
||||
}
|
||||
|
||||
export function completedSlackFormSessionReceipt(session: Pick<SlackFormHistoryRow, "id" | "companyId" | "endpointId" | "kind" | "payload" | "result" | "status">) {
|
||||
if (session.kind !== "slack_form_session" || !["processed", "cancelled", "failed"].includes(session.status)) return null;
|
||||
const binding = parseSlackFormBinding(session.payload.binding), work = parseSlackFormAckWork(session.result?.formAck);
|
||||
if (session.status === "failed" && work.receipt?.outcome !== "no_effect") return null;
|
||||
if (binding.companyId !== session.companyId || binding.endpointId !== session.endpointId || work.phase !== "transferred"
|
||||
|| !work.receiptJws || !work.receipt || session.result?.nextAttemptAt !== null) return null;
|
||||
assertSlackFormReceiptHistory(session, work.receipt);
|
||||
return work.receipt;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
|
||||
import { stageSlackFormNormalAck, acceptSlackFormAckReceipt } from "./form-ack-work.js";
|
||||
import { slackFormConnectorIdentity } from "./cloud-consumer.js";
|
||||
import { SlackCloudReceiptError } from "./cloud-event.js";
|
||||
|
||||
export async function acknowledgeSlackFormDeliveries(db: Db, input: { connector: PaperclipCloudConnector;
|
||||
values: { subject: string; companyId: string; leaseId: string; deliveryIds: string[] }; companies: ReadonlyMap<string, string> }): Promise<void> {
|
||||
const formIds = input.values.deliveryIds.filter(id => /^slack_form_[a-f0-9]{64}$/.test(id));
|
||||
const values = input.values;
|
||||
if (!formIds.length) await input.connector.acknowledgeEvents(values);
|
||||
else {
|
||||
const identity = slackFormConnectorIdentity(input.connector), detailed = Reflect.get(input.connector, "acknowledgeEventsWithReceipts");
|
||||
if (!identity || typeof detailed !== "function") throw new SlackCloudReceiptError("form_ack_receipts_unsupported", "attention");
|
||||
for (const deliveryId of formIds) {
|
||||
const companyId = input.companies.get(deliveryId);
|
||||
if (!companyId) throw new SlackCloudReceiptError("form_ack_company_missing", "attention");
|
||||
await db.transaction(tx => stageSlackFormNormalAck(tx, { companyId, instanceId: identity.instanceId, leaseId: values.leaseId, deliveryIds: [deliveryId] }));
|
||||
}
|
||||
const response: unknown = await Reflect.apply(detailed, input.connector, [values]);
|
||||
if (!response || typeof response !== "object" || Array.isArray(response) || !Array.isArray(Reflect.get(response, "formReceipts")))
|
||||
throw new SlackCloudReceiptError("form_ack_receipts_invalid", "attention");
|
||||
const receipts: unknown = Reflect.get(response, "formReceipts");
|
||||
if (!Array.isArray(receipts) || receipts.length !== formIds.length) throw new SlackCloudReceiptError("form_ack_receipts_invalid", "attention");
|
||||
const seen = new Set<string>();
|
||||
for (const value of receipts) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new SlackCloudReceiptError("form_ack_receipts_invalid", "attention");
|
||||
const deliveryId: unknown = Reflect.get(value, "deliveryId"), receiptJws: unknown = Reflect.get(value, "receiptJws");
|
||||
if (typeof deliveryId !== "string" || !formIds.includes(deliveryId) || seen.has(deliveryId) || typeof receiptJws !== "string")
|
||||
throw new SlackCloudReceiptError("form_ack_receipts_invalid", "attention");
|
||||
seen.add(deliveryId);
|
||||
const companyId = input.companies.get(deliveryId);
|
||||
if (!companyId) throw new SlackCloudReceiptError("form_ack_company_missing", "attention");
|
||||
await db.transaction(tx => acceptSlackFormAckReceipt(tx, { companyId, instanceId: identity.instanceId, leaseId: values.leaseId, receiptJws }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,11 @@ export async function stageSlackFormSession(tx: FormTx, input: {
|
||||
await closeSlackFormSession(tx, { companyId: binding.companyId, endpointId: binding.endpointId, principalId: principal.id, operationId: op.id }, op.closed.view);
|
||||
return { kind: "closed", actionId: old.id };
|
||||
}
|
||||
if (old.status === "processing" && old.result?.phase === "update_attempted" && op.phase === "confirmed" && op.view
|
||||
&& isDeepStrictEqual(old.result.view, op.view)) {
|
||||
await input.lease.assertOwned(tx);
|
||||
return { kind: "update", actionId: old.id, view: op.view };
|
||||
}
|
||||
return { kind: old.status === "cancelled" ? "closed" : "retained", actionId: old.id };
|
||||
}
|
||||
if (["reserved", "attempted"].includes(op.phase) && !op.closed) throw new SlackCloudReceiptError("form_receipt_pending", "retry");
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { parseSlackFormOperation } from "./chat-channels/slack/cloud-forms.js";
|
||||
import { stageSlackFormNormalAck, acceptSlackFormAckReceipt } from "./chat-channels/slack/form-ack-work.js";
|
||||
import { slackFormConnectorIdentity } from "./chat-channels/slack/cloud-consumer.js";
|
||||
import { acknowledgeSlackFormDeliveries } from "./chat-channels/slack/form-normal-ack.js";
|
||||
import { readSlackFormRetainedConsumer } from "./chat-channels/slack/cloud-consumer.js";
|
||||
import { reconcileRegisteredSlackFormWork } from "./chat-channels/slack/form-owner.js";
|
||||
import { SlackCloudReceiptError } from "./chat-channels/slack/cloud-event.js";
|
||||
@@ -647,34 +646,8 @@ export function githubConnectionEventService(
|
||||
}
|
||||
}
|
||||
if (acknowledge.length > 0) {
|
||||
const formIds = acknowledge.filter(id => /^slack_form_[a-f0-9]{64}$/.test(id));
|
||||
const values = { subject: first.subject, companyId: first.companyId, leaseId: lease.leaseId, deliveryIds: acknowledge };
|
||||
if (!formIds.length) await connector.acknowledgeEvents(values);
|
||||
else {
|
||||
const identity = slackFormConnectorIdentity(connector), detailed = Reflect.get(connector, "acknowledgeEventsWithReceipts");
|
||||
if (!identity || typeof detailed !== "function") throw new SlackCloudReceiptError("form_ack_receipts_unsupported", "attention");
|
||||
for (const deliveryId of formIds) {
|
||||
const companyId = formCompanies.get(deliveryId);
|
||||
if (!companyId) throw new SlackCloudReceiptError("form_ack_company_missing", "attention");
|
||||
await db.transaction(tx => stageSlackFormNormalAck(tx, { companyId, instanceId: identity.instanceId, leaseId: lease.leaseId, deliveryIds: [deliveryId] }));
|
||||
}
|
||||
const response: unknown = await Reflect.apply(detailed, connector, [values]);
|
||||
if (!response || typeof response !== "object" || Array.isArray(response) || !Array.isArray(Reflect.get(response, "formReceipts")))
|
||||
throw new SlackCloudReceiptError("form_ack_receipts_invalid", "attention");
|
||||
const receipts: unknown = Reflect.get(response, "formReceipts");
|
||||
if (!Array.isArray(receipts) || receipts.length !== formIds.length) throw new SlackCloudReceiptError("form_ack_receipts_invalid", "attention");
|
||||
const seen = new Set<string>();
|
||||
for (const value of receipts) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new SlackCloudReceiptError("form_ack_receipts_invalid", "attention");
|
||||
const deliveryId: unknown = Reflect.get(value, "deliveryId"), receiptJws: unknown = Reflect.get(value, "receiptJws");
|
||||
if (typeof deliveryId !== "string" || !formIds.includes(deliveryId) || seen.has(deliveryId) || typeof receiptJws !== "string")
|
||||
throw new SlackCloudReceiptError("form_ack_receipts_invalid", "attention");
|
||||
seen.add(deliveryId);
|
||||
const companyId = formCompanies.get(deliveryId);
|
||||
if (!companyId) throw new SlackCloudReceiptError("form_ack_company_missing", "attention");
|
||||
await db.transaction(tx => acceptSlackFormAckReceipt(tx, { companyId, instanceId: identity.instanceId, leaseId: lease.leaseId, receiptJws }));
|
||||
}
|
||||
}
|
||||
await acknowledgeSlackFormDeliveries(db, { connector,
|
||||
values: { subject: first.subject, companyId: first.companyId, leaseId: lease.leaseId, deliveryIds: acknowledge }, companies: formCompanies });
|
||||
}
|
||||
for (const deliveryId of lease.failedEventIds ?? []) {
|
||||
logger.warn({ deliveryId, reason: "inner_event_authentication_failed" },
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
generateKeyPairSync,
|
||||
hkdfSync,
|
||||
randomBytes,
|
||||
sign,
|
||||
type KeyObject,
|
||||
} from "node:crypto";
|
||||
import { SLACK_MANAGER_SCOPES } from "@paperclipai/shared";
|
||||
@@ -22,6 +23,9 @@ import {
|
||||
type PaperclipCloudConnectorConfig,
|
||||
} from "./paperclip-cloud-connector.js";
|
||||
|
||||
import { parseSlackFormFinalizedReceipt } from "./chat-channels/slack/ack-receipt.js";
|
||||
import { verifySlackFormFinalizedReceipt } from "./chat-channels/slack/receipt-authority.js";
|
||||
|
||||
const instanceId = "inst_test";
|
||||
const companyId = "company_test";
|
||||
const subject = "user_test";
|
||||
@@ -860,3 +864,56 @@ describe("sealed Slack event connector transport", () => {
|
||||
expect(JSON.parse(String(init.body))).toMatchObject({ enrollment: JSON.stringify(enrollment) });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("Slack form normal connector terminal reply contracts", () => {
|
||||
it("returns current signed refresh and GC-only replies through the actual signed connector", async () => {
|
||||
const keys = config(), pair = generateKeyPairSync("ed25519"), kid = "connector-terminal-reply";
|
||||
const canonical = parseSlackFormFinalizedReceipt({ version: 1, kind: "slack_form_finalized", environment: keys.config.environment,
|
||||
binding: { version: 1, instanceId, companyId, endpointId: "endpoint", publicId: "p".repeat(43), connectionId: "connection",
|
||||
runtimeGeneration: 1, teamId: "TTEST", appId: "ATEST", eventBindingId: "slack-event:" + "b".repeat(64), credentialFingerprint: "c".repeat(64) },
|
||||
operationId: "a".repeat(64), deliveryId: "slack_form_" + "a".repeat(64), appReceiptId: "11111111-1111-4111-8111-111111111111",
|
||||
grantId: "grant", publicationId: "publication", interactionId: "interaction", userId: "UTEST", viewDigest: null,
|
||||
terminalDigest: "d".repeat(64), outcome: "no_effect", finalizedAt: "2026-11-07T00:00:00.000Z" });
|
||||
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
const unsigned = encode({ alg: "EdDSA", typ: "paperclip-connector-ack-receipt+jwt", kid }) + "."
|
||||
+ encode({ v: 1, iss: "paperclip-cloud", aud: "paperclip-connector-ack-receipt/v1", sub: instanceId, receipt: canonical });
|
||||
const compactJws = unsigned + "." + sign(null, Buffer.from(unsigned), pair.privateKey).toString("base64url");
|
||||
const operations: Record<string, unknown>[] = [];
|
||||
let reply: unknown = { ackReceiptJws: compactJws };
|
||||
const request = vi.fn<typeof fetch>(async (_url, init) => {
|
||||
const body = JSON.parse(String(init?.body));
|
||||
const parts = String(body.request).split("."); expect(parts).toHaveLength(3);
|
||||
const claims = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8"));
|
||||
expect(claims.sub).toBe(subject); expect(claims.cid).toBe(companyId);
|
||||
expect(claims.sh).toBe(createHash("sha256").update(body.operation).digest("base64url"));
|
||||
operations.push(JSON.parse(body.operation));
|
||||
return Response.json({ slackForm: reply });
|
||||
});
|
||||
const connector = createPaperclipCloudConnector({ config: keys.config, request });
|
||||
const refresh = { kind: "receipt", binding: { instanceId }, operationId: canonical.operationId, refreshAckReceipt: true };
|
||||
await expect(connector.slackFormOperation({ subject, companyId, operation: refresh })).resolves.toEqual({ ackReceiptJws: compactJws });
|
||||
const digest = "d".repeat(64);
|
||||
reply = { releasedAckDigest: digest };
|
||||
const release = { kind: "receipt", binding: { instanceId }, operationId: canonical.operationId, releaseAckFact: true };
|
||||
await expect(connector.slackFormOperation({ subject, companyId, operation: release })).resolves.toEqual({ releasedAckDigest: digest });
|
||||
expect(operations).toEqual([refresh, release]); expect(request).toHaveBeenCalledTimes(2);
|
||||
expect(verifySlackFormFinalizedReceipt({ compactJws, env: { PAPERCLIP_CLOUD_STACK_ID: instanceId,
|
||||
PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS: JSON.stringify({ keys: [{ ...pair.publicKey.export({ format: "jwk" }), kid, alg: "EdDSA", use: "sig" }] }) } })).toEqual(canonical);
|
||||
});
|
||||
it("does not confuse refresh, release, acceptance or sealed operation responses", async () => {
|
||||
const keys = config(); let reply: unknown;
|
||||
const connector = createPaperclipCloudConnector({ config: keys.config, request: vi.fn<typeof fetch>(async () => Response.json({ slackForm: reply })) });
|
||||
const call = (operation: Record<string, unknown>) => connector.slackFormOperation({ subject, companyId, operation: { kind: "receipt", ...operation } });
|
||||
for (const invalid of [{ releasedAckDigest: "d".repeat(64) }, { ackReceiptJws: "missing.signature" },
|
||||
{ ackReceiptJws: "a.b.c", extra: true }, { acceptedReceiptDigest: "d".repeat(64), needsTerminalOriginal: false }, { sealed: {} }]) {
|
||||
reply = invalid; await expect(call({ refreshAckReceipt: true })).rejects.toBeInstanceOf(PaperclipCloudConnectorError);
|
||||
}
|
||||
for (const invalid of [{ ackReceiptJws: "a.b.c" }, { releasedAckDigest: "invalid" }, { releasedAckDigest: "d".repeat(64), extra: true }]) {
|
||||
reply = invalid; await expect(call({ releaseAckFact: true })).rejects.toBeInstanceOf(PaperclipCloudConnectorError);
|
||||
}
|
||||
reply = { releasedAckDigest: "d".repeat(64) };
|
||||
await expect(call({ acceptedAckReceipt: "a.b.c" })).rejects.toBeInstanceOf(PaperclipCloudConnectorError);
|
||||
await expect(call({})).rejects.toBeInstanceOf(PaperclipCloudConnectorError);
|
||||
});
|
||||
});
|
||||
@@ -420,6 +420,18 @@ export function createPaperclipCloudConnector(input: {
|
||||
async slackFormOperation(values: { subject: string; companyId: string; operation: Record<string, unknown> }) {
|
||||
const response = await call("slack-forms", values, { field: "operation", value: JSON.stringify(values.operation) });
|
||||
if (!isRecord(response.slackForm)) throw badEnvelope();
|
||||
if (values.operation.kind === "receipt" && values.operation.refreshAckReceipt !== undefined) {
|
||||
if (values.operation.acceptedAckReceipt !== undefined || values.operation.releaseAckFact !== undefined
|
||||
|| Object.keys(response.slackForm).join() !== "ackReceiptJws" || typeof response.slackForm.ackReceiptJws !== "string"
|
||||
|| Buffer.byteLength(response.slackForm.ackReceiptJws, "ascii") > 12000
|
||||
|| !/^[A-Za-z0-9_-]+[.][A-Za-z0-9_-]+[.][A-Za-z0-9_-]+$/.test(response.slackForm.ackReceiptJws)) throw badEnvelope();
|
||||
return response.slackForm;
|
||||
}
|
||||
if (values.operation.kind === "receipt" && values.operation.releaseAckFact !== undefined) {
|
||||
if (values.operation.acceptedAckReceipt !== undefined || Object.keys(response.slackForm).join() !== "releasedAckDigest"
|
||||
|| typeof response.slackForm.releasedAckDigest !== "string" || !/^[a-f0-9]{64}$/.test(response.slackForm.releasedAckDigest)) throw badEnvelope();
|
||||
return response.slackForm;
|
||||
}
|
||||
if (values.operation.kind === "receipt" && values.operation.acceptedAckReceipt !== undefined) {
|
||||
if (Object.keys(response.slackForm).sort().join() !== "acceptedReceiptDigest,needsTerminalOriginal" || typeof response.slackForm.acceptedReceiptDigest !== "string"
|
||||
|| !/^[a-f0-9]{64}$/.test(response.slackForm.acceptedReceiptDigest) || typeof response.slackForm.needsTerminalOriginal !== "boolean") throw badEnvelope();
|
||||
|
||||
Reference in new issue
Block a user