fix(photon): enforce current resume cutoff before useful admission

This commit is contained in:
Dotta committed 2026-11-11 14:12:34 -06:00
1 parent bec8d35e7c
commit 5ffa707d75
4 files changed
+73 -3

No files matched your search

@@ -681,6 +681,58 @@ describe("iMessage Photon channel control plane", () => {
expect(secretSafe).not.toContain("private-line-token");
expect(secretSafe).not.toContain('"projectSecret"');
}, 30_000);
it("filters pause-window events through current Photon admission after a same-generation resume", async () => {
const t = await setup();
await t.start();
await t.qualify();
const [before] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, t.endpoint.id));
const [connectionBefore] = await db.select().from(toolConnections).where(eq(toolConnections.id, t.endpoint.connectionId));
if (!before || !connectionBefore) throw new Error("Missing configured Photon endpoint");
const wakeups = t.wakeup.mock.calls.length;
const deliveredBefore = await db.select({ id: chatDeliveries.id }).from(chatDeliveries)
.where(eq(chatDeliveries.endpointId, t.endpoint.id));
await t.service.configure(t.endpoint.id, { action: "pause" }, t.userId);
const [paused] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, t.endpoint.id));
if (!paused) throw new Error("Missing paused Photon endpoint");
const duringPause = { ...photonEvent(3, t.f.chat, "Queued while paused"), occurredAt: paused.updatedAt };
await t.service.configure(t.endpoint.id, { action: "resume" }, t.userId);
const [resumed] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, t.endpoint.id));
const [connectionResumed] = await db.select().from(toolConnections).where(eq(toolConnections.id, t.endpoint.connectionId));
if (!resumed || !connectionResumed) throw new Error("Missing resumed Photon endpoint");
const cutoffValue = Reflect.get(resumed.setup, "photonIntakeAfter");
if (typeof cutoffValue !== "string") throw new Error("Missing normal Photon resume cutoff");
const cutoff = Date.parse(cutoffValue);
expect(Number.isFinite(cutoff)).toBe(true);
expect(duringPause.occurredAt.getTime()).toBeLessThan(cutoff);
const generation = Reflect.get(before.setup, "runtimeGeneration");
expect(Number.isSafeInteger(generation)).toBe(true);
expect(Reflect.get(resumed.setup, "runtimeGeneration")).toBe(generation);
expect(resumed.connectionId).toBe(before.connectionId);
expect(connectionResumed.credentialSecretRefs).toEqual(connectionBefore.credentialSecretRefs);
const providerReads = t.f.client.chats.get.mock.calls.length;
// This is the actual normal callback used by external-owner.dispatch. The
// local receiver's catch-up cutoff is deliberately not the tested boundary.
await t.deliver(duringPause);
expect(t.wakeup.mock.calls.length, "pause-window input must not create useful work after resume").toBe(wakeups);
expect(await db.select({ id: chatDeliveries.id }).from(chatDeliveries)
.where(eq(chatDeliveries.endpointId, t.endpoint.id))).toEqual(deliveredBefore);
expect(t.f.client.chats.get).toHaveBeenCalledTimes(providerReads);
const boundary = { ...photonEvent(4, t.f.chat, "Exactly at the resumed boundary"), occurredAt: new Date(cutoff) };
await t.deliver(boundary);
expect(t.wakeup).toHaveBeenCalledTimes(wakeups + 1);
await t.deliver(boundary);
expect(t.wakeup).toHaveBeenCalledTimes(wakeups + 1);
await t.deliver({ ...photonEvent(5, t.f.chat, "Fresh after resume"), occurredAt: new Date(cutoff + 1) });
expect(t.wakeup).toHaveBeenCalledTimes(wakeups + 2);
await expect(t.callbacks().onPhotonEvent!({ ...photonEvent(6), occurredAt: new Date(NaN) }))
.rejects.toMatchObject({ code: "invalid_response" });
expect(t.wakeup).toHaveBeenCalledTimes(wakeups + 2);
await t.service.configure(t.endpoint.id, { action: "pause" }, t.userId);
// Authority still wins before timestamp validation while inactive.
await expect(t.callbacks().onPhotonEvent!({ ...photonEvent(7), occurredAt: new Date(NaN) }))
.rejects.toThrow("Photon receiver no longer owns this endpoint");
expect(t.wakeup).toHaveBeenCalledTimes(wakeups + 2);
}, 30_000);
it("preserves DM identity across restart, ignores echoes, and reserves a paused number", async () => {
const t = await setup();
const first = await t.start();
@@ -2,7 +2,7 @@ import { notifyChatEndpointConfiguration } from "./configuration-work-notificati
import { notifyChatConnectionHealth } from "./connection-health-notifications.js";
import type { ConnectionManagementContext } from "../connection-management.js";
import { CHAT_HUMAN_CREDENTIAL_FIELDS } from "./credentials.js";
import { preparePhotonConfiguration, createPhotonConfiguration } from "./imessage-photon/setup.js";
import { preparePhotonConfiguration, createPhotonConfiguration, photonIntakeAfter } from "./imessage-photon/setup.js";
import { slackRuntimeConfig } from "./slack/setup.js";
import { createTelegramSetup } from "./telegram/setup.js";
import { createGitHubSetup } from "./github/setup.js";
@@ -970,7 +970,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
if (endpoint.provider === "speko") throw conflict("Speko uses the voice runtime");
if (endpoint.provider === "imessage-photon") return {
provider: "imessage-photon", userName,
intakeAfter: Date.parse(String((endpoint.setup as InternalSetupState).photonIntakeAfter ?? endpoint.setup.testStartedAt ?? endpoint.createdAt.toISOString())),
intakeAfter: photonIntakeAfter(endpoint),
credentials: { allocation: credentials.allocation === "shared" ? "shared" : "dedicated", projectId: credentials.projectId, lineId: credentials.lineId, projectSecret: credentials.projectSecret, phoneNumber: endpoint.botExternalId! },
};
if (endpoint.provider === "slack")
@@ -1,3 +1,4 @@
import { photonIntakeAfter } from "./setup.js";
import { photonStateFor, PHOTON_EXTERNAL_STATE } from "./external-store.js";
import { credentialFingerprint } from "../credential-fingerprint.js";
import { stagePhotonResponseNotice } from "./response-notices.js";
@@ -725,6 +726,17 @@ export function createPhotonEvents(db: Db, options: PhotonEventsOptions) {
]);
if (!record)
throw new Error("Photon receiver no longer owns this endpoint");
// Cloud custody can survive a same-generation pause/resume. Use the
// authorized endpoint's CURRENT policy, never its older sealed binding.
const occurredAt = new Date(event.occurredAt).getTime();
if (!Number.isFinite(occurredAt))
throw new PhotonError("invalid_response", "Photon event timestamp is invalid");
const intakeAfter = photonIntakeAfter(record.endpoint);
if (!Number.isFinite(intakeAfter))
throw new PhotonError("invalid_response", "Photon intake boundary is invalid");
// A fulfilled no-effect admission still lets the ordinary external owner
// durably checkpoint this sequence and the normal caller ACK its delivery.
if (occurredAt < intakeAfter) return;
const adapter = context.endpointRuntime!.getProviderAdapter();
if (!(adapter instanceof PhotonChatAdapter))
throw new Error("Photon adapter unavailable");
@@ -1,6 +1,6 @@
import type { createPhotonCredentialChecks } from "./credentials.js";
import type { EndpointRow } from "../runtime-types.js";
import type { EndpointRow, InternalSetupState } from "../runtime-types.js";
import { type CredentialMutationLeaseGuard } from "../../chat-credential-mutation-lease.js";
@@ -28,6 +28,12 @@ import {
import type { EndpointRecord } from "../runtime-types.js";
/** Current endpoint policy, shared by local receiver construction and callback admission. */
export function photonIntakeAfter(endpoint: Pick<EndpointRow, "setup" | "createdAt">): number {
return Date.parse(String((endpoint.setup as InternalSetupState).photonIntakeAfter
?? endpoint.setup.testStartedAt ?? endpoint.createdAt.toISOString()));
}
type PhotonSetupInspectionOptions = {
endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;
inspectPhotonCredentials: ReturnType<typeof createPhotonCredentialChecks>["inspectPhotonCredentials"];