diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 9e596bc3..e44ebbc1 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1778,6 +1778,54 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/event-subscriptions/{subscriptionId}/occurrences": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List matched occurrences for the signed-in owner's exact subscription + * @description Newest first. HTTP acceptance confirms receipt, not processing. Acknowledgment is independent. Webhook configuration and payloads are omitted. + * + * Requires the triggers:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_event_subscriptions_subscriptionId_occurrences"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/events/{eventId}/occurrence-summaries": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List bounded, payload-free Event occurrence summaries + * @description Newest first, with occurrence IDs and safe source classifications. The full occurrence endpoint is unchanged. + * + * Requires the triggers:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + get: operations["get_api_v1_events_eventId_occurrence_summaries"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/events": { parameters: { query?: never; @@ -6416,6 +6464,98 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_event_subscriptions_subscriptionId_occurrences: { + parameters: { + query?: { + limit?: number; + cursor?: string; + }; + header?: never; + path: { + subscriptionId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Subscription occurrence summaries */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + items: { + /** Format: uuid */ + id: string; + /** Format: date-time */ + occurredAt: string; + /** @enum {string} */ + source: "manual" | "schedule" | "github" | "linear" | "cloudflare" | "webhook" | "unknown"; + /** @enum {string} */ + delivery: "pending" | "sending" | "accepted" | "failed" | "cancelled"; + /** @enum {string} */ + acknowledgment: "off" | "pending" | "awaiting_ack" | "processed" | "waived" | "exhausted" | "cancelled"; + }[]; + nextCursor: string | null; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + /** @description Event subscription not found */ + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_events_eventId_occurrence_summaries: { + parameters: { + query?: { + limit?: number; + cursor?: string; + }; + header?: never; + path: { + eventId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Event occurrence summaries */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + items: { + /** Format: uuid */ + id: string; + /** Format: date-time */ + occurredAt: string; + /** @enum {string} */ + source: "manual" | "schedule" | "github" | "linear" | "cloudflare" | "webhook" | "unknown"; + }[]; + nextCursor: string | null; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + /** @description Event not found */ + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_events: { parameters: { query?: never; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 48194ef0..316be547 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1,3 +1,4 @@ +import { eventOccurrenceSummaryPage, subscriptionOccurrenceSummaryPage, occurrenceSummaryQuery } from "./event-contracts"; import { cloudflareCookieValue, cloudflareSelectInput, cloudflareStartInput, cloudflareStartResult, cloudflareStatus } from "./cloudflare-oauth"; import { cloneInfo, gitCredential } from "./git-https-contracts"; import { profileInput, profileResponse } from "./usernames"; @@ -699,6 +700,24 @@ export const API_ROUTES: RouteContract[] = [ responses: { "200": { description: "Event subscription", content: { "application/json": { schema: jsonSchema(eventSubscription, "output") } } }, "404": { description: "Event subscription not found" } }, }, (service, { params }) => service.getDashboardEventSubscription(params.subscriptionId), { ownerSession: true, parameters: z.object({ subscriptionId: eventSubscriptionId }) }), + route("GET", "/api/v1/event-subscriptions/{subscriptionId}/occurrences", "triggers:read", { + summary: "List matched occurrences for the signed-in owner's exact subscription", + description: "Newest first. HTTP acceptance confirms receipt, not processing. Acknowledgment is independent. Webhook configuration and payloads are omitted.", + responses: { + "200": { description: "Subscription occurrence summaries", content: { "application/json": { schema: jsonSchema(subscriptionOccurrenceSummaryPage, "output") } } }, + "404": { description: "Event subscription not found" }, + }, + }, (service, { params, query }) => service.listSubscriptionOccurrences(params.subscriptionId, query.limit, query.cursor), + { ownerSession: true, parameters: z.object({ subscriptionId: eventSubscriptionId }), query: occurrenceSummaryQuery }), + route("GET", "/api/v1/events/{eventId}/occurrence-summaries", "triggers:read", { + summary: "List bounded, payload-free Event occurrence summaries", + description: "Newest first, with occurrence IDs and safe source classifications. The full occurrence endpoint is unchanged.", + responses: { + "200": { description: "Event occurrence summaries", content: { "application/json": { schema: jsonSchema(eventOccurrenceSummaryPage, "output") } } }, + "404": { description: "Event not found" }, + }, + }, (service, { params, query }) => service.listEventOccurrenceSummaries(params.eventId, query.limit, query.cursor), + { parameters: z.object({ eventId: z.uuid() }), query: occurrenceSummaryQuery }), route("GET", "/api/v1/events", "triggers:read", { summary: "List Events", responses: { "200": { description: "Events and current revisions", content: { "application/json": { schema: jsonSchema(eventDefinitionList, "output") } } } } }, service => service.listEvents()), route("POST", "/api/v1/events", "triggers:write", { summary: "Create an Event", responses: { "201": { description: "Created Event", content: { "application/json": { schema: jsonSchema(eventDefinitionResponse, "output") } } } } }, (service, { body }) => service.createEvent(body), { body: eventDefinitionInput }), route("GET", "/api/v1/events/{eventId}", "triggers:read", { summary: "Get an Event", responses: { "200": { description: "Event", content: { "application/json": { schema: jsonSchema(eventDefinitionResponse, "output") } } } } }, (service, { params }) => service.getEvent(params.eventId), { parameters: z.object({ eventId: z.uuid() }) }), diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index 634282e1..bf0bedf4 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -1,3 +1,5 @@ +import { readOccurrenceSummaries } from "./postgres/occurrence-summary-repository"; +import { eventOccurrenceSummaryPage, subscriptionOccurrenceSummaryPage, parseOccurrenceSummaryCursor } from "./event-contracts"; import { cloudflareState, disconnectCloudflare, selectCloudflare, startCloudflare } from "./cloudflare-oauth"; import { initialIntegrationOverrides, lockOAuthPolicy } from "./oauth-reconnect"; import { deleteMcpGrantSubscriptions, lockMcpEventGrant } from "./postgres/mcp-event-outbox"; @@ -225,6 +227,27 @@ export class ApiService { async createEvent(input: unknown) { await this.authorize("triggers:write"); return publicValue(eventDefinitionResponse, await this.eventDefinitions().create(eventDefinitionInput.parse(input))); } async updateEvent(id: string, input: unknown) { await this.authorize("triggers:write"); const parsed = eventDefinitionUpdate.parse(input); try { const result = await this.eventDefinitions().update(id, parsed, parsed.expectedRevision); if (!result) throw new ServiceError(404, "not_found", "Event not found"); return publicValue(eventDefinitionResponse, result); } catch (error) { if (error instanceof EventDefinitionConflict) throw new ServiceError(409, "stale_event", "Event changed since it was loaded."); throw error; } } async deleteEvent(id: string) { await this.authorize("triggers:write"); if (!await this.eventDefinitions().delete(id)) throw new ServiceError(404, "not_found", "Event not found"); return { id, deleted: true as const }; } + private occurrenceSummaryBoundary(id: string, cursor?: string) { + if (cursor === undefined) return undefined; + const boundary = parseOccurrenceSummaryCursor(cursor, id); + if (!boundary) throw new ServiceError(400, "invalid_request", "Cursor does not match this occurrence history."); + return boundary; + } + async listEventOccurrenceSummaries(id: string, limit: number, cursor?: string) { + await this.authorize("triggers:read"); + id = id.toLowerCase(); + const result = await readOccurrenceSummaries(databaseFor(this.env), this.auth.tenantId, + { kind: "event", id }, limit, this.occurrenceSummaryBoundary(id, cursor)); + if (!result) throw new ServiceError(404, "not_found", "Event not found"); + return publicValue(eventOccurrenceSummaryPage, result); + } + async listSubscriptionOccurrences(id: string, limit: number, cursor?: string) { + await this.authorizeOwnerSession("triggers:read"); + const result = await readOccurrenceSummaries(databaseFor(this.env), this.auth.tenantId, + { kind: "subscription", id, userId: this.auth.userId }, limit, this.occurrenceSummaryBoundary(id, cursor)); + if (!result) throw new ServiceError(404, "not_found", "Event subscription not found"); + return publicValue(subscriptionOccurrenceSummaryPage, result); + } async listEventOccurrences(id: string, limit: number, cursor?: string) { await this.authorize("triggers:read"); const result = await this.eventDefinitions().occurrences(id, limit, cursor); if (!result) throw new ServiceError(404, "not_found", "Event not found"); return publicValue(eventOccurrencePage, result); } async mcpEventCatalog() { await this.authorize("triggers:read"); diff --git a/packages/api/src/event-contracts.ts b/packages/api/src/event-contracts.ts index 2ff72b67..548c988b 100644 --- a/packages/api/src/event-contracts.ts +++ b/packages/api/src/event-contracts.ts @@ -31,3 +31,24 @@ export const eventSubscription = z.object({ expiresAt: z.iso.datetime(), }); export const eventSubscriptionList = z.array(eventSubscription); + +export const occurrenceSummaryQuery = z.object({ + limit: z.coerce.number().int().min(1).max(50).default(10), + cursor: z.string().min(1).max(384).optional(), +}); +const summarySource = z.enum(["manual", "schedule", "github", "linear", "cloudflare", "webhook", "unknown"]); +const occurrenceSummary = z.object({ id: z.uuid(), occurredAt: z.iso.datetime(), source: summarySource }); +const subscriptionOccurrenceSummary = occurrenceSummary.extend({ + delivery: z.enum(["pending", "sending", "accepted", "failed", "cancelled"]), + acknowledgment: z.enum(["off", "pending", "awaiting_ack", "processed", "waived", "exhausted", "cancelled"]), +}); +export const eventOccurrenceSummaryPage = z.object({ items: z.array(occurrenceSummary), nextCursor: z.string().nullable() }); +export const subscriptionOccurrenceSummaryPage = z.object({ items: z.array(subscriptionOccurrenceSummary), nextCursor: z.string().nullable() }); +const summaryCursor = z.tuple([z.string(), z.iso.datetime(), z.uuid()]); +export function parseOccurrenceSummaryCursor(cursor: string, collectionId: string): [string, string] | null { + try { + const [id, occurredAt, occurrenceId] = summaryCursor.parse(JSON.parse(atob(cursor))); + if (id === collectionId) return [occurredAt, occurrenceId]; + } catch { /* Invalid or foreign cursor. */ } + return null; +} diff --git a/packages/api/src/postgres/occurrence-summary-repository.ts b/packages/api/src/postgres/occurrence-summary-repository.ts new file mode 100644 index 00000000..e9b0e1fc --- /dev/null +++ b/packages/api/src/postgres/occurrence-summary-repository.ts @@ -0,0 +1,42 @@ +import type { Database } from "./database"; + +type Collection = { kind: "event"; id: string } | { kind: "subscription"; id: string; userId: string }; +type Row = { id: string | null; occurred_at: string; source: string; delivery: string; acknowledgment: string }; + +// Project only safe columns. The ID is usable with the existing occurrence read +// protocol; payload, raw sources, credentials and callbacks never go to the table. +export async function readOccurrenceSummaries(db: Database, tenantId: string, collection: Collection, limit: number, boundary?: [string, string]) { + const isSubscription = collection.kind === "subscription"; + const parent = isSubscription + ? "SELECT tenant_id,id,definition_id FROM app.mcp_event_subscriptions WHERE tenant_id=$1 AND id=$2 AND user_id=$6" + : "SELECT tenant_id,id AS definition_id FROM app.event_definitions WHERE tenant_id=$1 AND id=$2"; + const fields = isSubscription ? ",d.status AS delivery,COALESCE(d.ack_state,'off') AS acknowledgment" : ""; + const delivery = isSubscription + ? "JOIN app.mcp_event_deliveries d ON d.tenant_id=o.tenant_id AND d.subscription_id=p.id AND d.occurrence_id=o.id" + : ""; + const { rows } = await db.pool.query( + `SELECT page.id,page.occurred_at,page.source${isSubscription ? ",page.delivery,page.acknowledgment" : ""} + FROM (${parent}) p + LEFT JOIN LATERAL ( + SELECT o.id,o.occurred_at AS sort_time, + to_char(o.occurred_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS occurred_at, + CASE split_part(o.source_identity,':',1) + WHEN 'manual' THEN 'manual' WHEN 'schedule' THEN 'schedule' WHEN 'github' THEN 'github' + WHEN 'linear' THEN 'linear' WHEN 'cloudflare' THEN 'cloudflare' WHEN 'webhook' THEN 'webhook' + ELSE 'unknown' END AS source${fields} + FROM app.event_occurrences o ${delivery} + WHERE o.tenant_id=p.tenant_id AND o.definition_id=p.definition_id + AND ($3::timestamptz IS NULL OR (o.occurred_at,o.id)<($3,$4::uuid)) + ORDER BY o.occurred_at DESC,o.id DESC LIMIT $5 + ) page ON TRUE + ORDER BY page.sort_time DESC,page.id DESC`, + [tenantId, collection.id, boundary?.[0] ?? null, boundary?.[1] ?? null, limit + 1, ...(isSubscription ? [collection.userId] : [])], + ); + if (!rows.length) return null; + const items = rows.slice(0, limit).flatMap(row => !row.id ? [] : [{ + id: row.id, occurredAt: row.occurred_at, source: row.source, + ...(isSubscription ? { delivery: row.delivery, acknowledgment: row.acknowledgment } : {}), + }]); + const last = items.at(-1); + return { items, nextCursor: rows.length > limit && last ? btoa(JSON.stringify([collection.id, last.occurredAt, last.id])) : null }; +} diff --git a/packages/api/test/occurrence-summaries.postgres.test.ts b/packages/api/test/occurrence-summaries.postgres.test.ts new file mode 100644 index 00000000..daa0920a --- /dev/null +++ b/packages/api/test/occurrence-summaries.postgres.test.ts @@ -0,0 +1,89 @@ +import { expect, it, vi } from "vitest"; +import { protectedApiFetch } from "../src/protected-api"; +import { loadingFixture } from "./helpers/loading-fixture"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {}, WorkflowEntrypoint: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const database = process.env.AUTH_TEST_DATABASE_URL; +const subscriptionId = (digit: string) => "sub_" + digit.repeat(64); +const occurrenceId = (number: number) => "d0000000-0000-4000-8000-" + String(number).padStart(12, "0"); + +it.skipIf(!database)("pages safe newest-first summaries and exposes only exact owner subscription deliveries", async () => { + const f = await loadingFixture(database!); + try { + const { definitionId } = await f.seedEventTrigger(); + const foreign = await f.seedEventTrigger(f.otherTenant); + const generation = crypto.randomUUID(); + const otherOwner = crypto.randomUUID(); + for (const [id, owner, tenant, definition] of [ + [subscriptionId("a"), f.userId, f.tenantId, definitionId], + [subscriptionId("b"), f.userId, f.tenantId, definitionId], + [subscriptionId("c"), otherOwner, f.tenantId, definitionId], + [subscriptionId("d"), f.userId, f.otherTenant, foreign.definitionId], + ]) { + await f.db.pool.query(`INSERT INTO app.mcp_event_subscriptions + (tenant_id,id,user_id,session_version,grant_id,client_id,definition_id,arguments,callback_url,encrypted_secret,secret_fingerprint,verified_at,generation,status,expires_at) + VALUES ($1,$2,$3,0,'grant','client',$4,'{"private":"arguments"}','https://private.example.test','private-secret','private-fingerprint',now(),$5,'active',now()+interval '1 day')`, + [tenant, id, owner, definition, generation]); + } + const older = "2026-01-02T03:04:05.000001Z", newer = "2026-01-02T03:04:05.000002Z"; + for (let n = 1; n <= 13; n++) { + const source = n === 12 ? "linear:private-project-id" : n === 13 ? "unrecognized-private-value" : "manual:private-trigger-id"; + await f.db.pool.query(`INSERT INTO app.event_occurrences + (tenant_id,id,definition_id,definition_revision,occurred_at,payload,producer_identity,evidence,source_identity,idempotency_key) + VALUES ($1,$2,$3,1,$4,'{"private":"payload"}','{"private":"producer"}','[]',$5,$6)`, + [f.tenantId, occurrenceId(n), definitionId, n < 12 ? older : newer, source, "fixture-" + n]); + } + for (let n = 1; n <= 12; n++) { + const [delivery, acknowledgment] = n === 12 ? ["accepted", "awaiting_ack"] : n === 11 ? ["accepted", "processed"] + : n === 10 ? ["pending", "pending"] : n === 9 ? ["failed", "exhausted"] : ["accepted", null]; + await f.db.pool.query(`INSERT INTO app.mcp_event_deliveries + (tenant_id,subscription_id,occurrence_id,generation,status,ack_state,http_status,last_outcome) + VALUES ($1,$2,$3,$4,$5,$6,202,'private-outcome')`, + [f.tenantId, subscriptionId(n === 1 ? "b" : "a"), occurrenceId(n), generation, delivery, acknowledgment]); + } + const read = (path: string, auth = f.auth) => protectedApiFetch(new Request(f.env.APP_ORIGIN + path), + f.env, auth, {} as ExecutionContext); + const get = async (path: string) => { + const response = await read(path); + expect(response.status, await response.clone().text()).toBe(200); + return await response.json() as { items: { id: string; occurredAt: string; source: string }[]; nextCursor: string | null }; + }; + const eventPath = "/api/v1/events/" + definitionId + "/occurrence-summaries"; + const subPath = "/api/v1/event-subscriptions/" + subscriptionId("a") + "/occurrences"; + const first = await get(eventPath); + expect(first.items.map(item => item.id)).toEqual(Array.from({ length: 10 }, (_, i) => occurrenceId(13 - i))); + expect(first.items[0]).toEqual({ id: occurrenceId(13), occurredAt: newer, source: "unknown" }); + expect(first.items[1]).toEqual({ id: occurrenceId(12), occurredAt: newer, source: "linear" }); + expect(first.items[2]).toEqual({ id: occurrenceId(11), occurredAt: older, source: "manual" }); + expect(first.nextCursor).toBeTruthy(); + const cursor = "?cursor=" + encodeURIComponent(first.nextCursor!); + const second = await get(eventPath + cursor); + expect(second.items.map(item => item.id)).toEqual([3, 2, 1].map(occurrenceId)); + expect(second.nextCursor).toBeNull(); + expect((await read(subPath + cursor)).status).toBe(400); + expect((await read(eventPath + "?cursor=not-a-cursor")).status).toBe(400); + expect((await read(eventPath + "?limit=51")).status).toBe(400); + expect((await read("/api/v1/events/" + foreign.definitionId + "/occurrence-summaries")).status).toBe(404); + + const deliveries = await get(subPath); + expect(deliveries.items.map(item => item.id)).toEqual(Array.from({ length: 10 }, (_, i) => occurrenceId(12 - i))); + expect(deliveries.items.slice(0, 5)).toEqual([ + { id: occurrenceId(12), occurredAt: newer, source: "linear", delivery: "accepted", acknowledgment: "awaiting_ack" }, + { id: occurrenceId(11), occurredAt: older, source: "manual", delivery: "accepted", acknowledgment: "processed" }, + { id: occurrenceId(10), occurredAt: older, source: "manual", delivery: "pending", acknowledgment: "pending" }, + { id: occurrenceId(9), occurredAt: older, source: "manual", delivery: "failed", acknowledgment: "exhausted" }, + { id: occurrenceId(8), occurredAt: older, source: "manual", delivery: "accepted", acknowledgment: "off" }, + ]); + const next = await get(subPath + "?cursor=" + encodeURIComponent(deliveries.nextCursor!)); + expect(next.items.map(item => item.id)).toEqual([occurrenceId(2)]); + expect(next.nextCursor).toBeNull(); + expect((await get("/api/v1/event-subscriptions/" + subscriptionId("b") + "/occurrences")).items.map(item => item.id)).toEqual([occurrenceId(1)]); + for (const id of [subscriptionId("c"), subscriptionId("d"), subscriptionId("e")]) { + expect((await read("/api/v1/event-subscriptions/" + id + "/occurrences")).status).toBe(404); + } + expect((await read(subPath, { ...f.auth, authMethod: "oauth" })).status).toBe(403); + expect(JSON.stringify({ first, deliveries })).not.toMatch(/private|httpStatus|callback|payload|producer|encrypted|arguments/i); + } finally { await f.cleanup(); } +}); diff --git a/packages/app/src/features/events/events.tsx b/packages/app/src/features/events/events.tsx index 02e3440a..6daac8a3 100644 --- a/packages/app/src/features/events/events.tsx +++ b/packages/app/src/features/events/events.tsx @@ -1,14 +1,14 @@ import type { ReactNode } from "react"; import { Link, useNavigate, useParams } from "@tanstack/react-router"; -import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { api, type paths } from "factorize-api-client"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; import { Button, Page, PageHeader, Table, tableCellClasses, tableHeadClasses, tableRowClasses } from "../../shared/ui"; +import { OccurrenceTable } from "./occurrence-table"; import { eventsQuery, subscriptionsQuery } from "./queries"; import { EventSubscriptions, SubscriptionsTable, SubscriptionTime } from "./subscriptions-table"; const linkClass = "rounded-lg px-3 py-2 hover:bg-stone-100 dark:hover:bg-slate-800"; const activeClass = "bg-factorize-50 text-factorize-700 dark:bg-factorize-500/10 dark:text-factorize-500"; -type OccurrencePage = paths["/api/v1/events/{eventId}/occurrences"]["get"]["responses"][200]["content"]["application/json"]; function EventsLayout({ title, description, children, subscriptions }: { title: string; description?: string; children: ReactNode; subscriptions?: boolean }) { return