Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 131 additions & 2 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1732,6 +1732,52 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/event-subscriptions": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* List the signed-in owner's Event subscriptions in the current workspace
* @description Shows registration lifecycle, not current delivery capability. Does not expose webhook configuration.
*
* Requires the triggers:read scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
get: operations["get_api_v1_event_subscriptions"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/event-subscriptions/{subscriptionId}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Get a signed-in owner's Event subscription in the current workspace
* @description 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"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/events": {
parameters: {
query?: never;
Expand Down Expand Up @@ -1783,8 +1829,8 @@ export interface paths {
put: operations["put_api_v1_events_eventId"];
post?: never;
/**
* Delete an Event and its Triggers and occurrences
* @description Permanently deletes the Event, all attached Triggers, their input configurations, and the Event's occurrence history.
* Delete an Event, its Triggers, subscriptions, and occurrences
* @description Permanently deletes the Event, all attached Triggers, their input configurations, subscriptions, and the Event's occurrence history.
*
* Requires the triggers:write scope.
*
Expand Down Expand Up @@ -6287,6 +6333,89 @@ export interface operations {
503: components["responses"]["Error503"];
};
};
get_api_v1_event_subscriptions: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Event subscriptions */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
id: string;
/** Format: uuid */
eventId: string;
eventName: string;
grantId: string;
/** @enum {string} */
status: "active" | "expired" | "stopped";
/** @enum {string} */
acknowledgmentMode: "required" | "off";
/** Format: date-time */
expiresAt: string;
}[];
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
get_api_v1_event_subscriptions_subscriptionId: {
parameters: {
query?: never;
header?: never;
path: {
subscriptionId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Event subscription */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
id: string;
/** Format: uuid */
eventId: string;
eventName: string;
grantId: string;
/** @enum {string} */
status: "active" | "expired" | "stopped";
/** @enum {string} */
acknowledgmentMode: "required" | "off";
/** Format: date-time */
expiresAt: string;
};
};
};
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: {
parameters: {
query?: never;
Expand Down
14 changes: 12 additions & 2 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { X_OAUTH_SCOPES } from "./x-oauth";
import document from "./api-document.json";
import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, googleAvailability, googleStartResult, googlePendingResult, googleUsernameResult, totpStatusResponse, totpSetupResponse, totpEnabledResponse, type AuthAction } from "./auth-api";
import { flyConnectionInput, flyConnectionMetadata } from "./fly-account-client";
import { eventDefinitionInput, eventDefinitionUpdate, eventDefinitionResponse, eventDefinitionList, eventOccurrenceQuery, eventOccurrencePage } from "./event-contracts";
import { eventSubscription, eventSubscriptionId, eventSubscriptionList, eventDefinitionInput, eventDefinitionUpdate, eventDefinitionResponse, eventDefinitionList, eventOccurrenceQuery, eventOccurrencePage } from "./event-contracts";
import { vmGrantInput, vmGrantList, vmGrantRef, vmGrantResult, vmRevokeResult } from "./vm-grant-contracts";

type JsonSchema = Record<string, any>;
Expand Down Expand Up @@ -689,11 +689,21 @@ export const API_ROUTES: RouteContract[] = [
summary: "Get the current team",
responses: { "200": { description: "Team", content: { "application/json": { schema: jsonSchema(teamResponse, "output") } } } },
}, service => service.getTeam()),
route("GET", "/api/v1/event-subscriptions", "triggers:read", {
summary: "List the signed-in owner's Event subscriptions in the current workspace",
description: "Shows registration lifecycle, not current delivery capability. Does not expose webhook configuration.",
responses: { "200": { description: "Event subscriptions", content: { "application/json": { schema: jsonSchema(eventSubscriptionList, "output") } } } },
}, service => service.listDashboardEventSubscriptions(), { ownerSession: true }),
route("GET", "/api/v1/event-subscriptions/{subscriptionId}", "triggers:read", {
summary: "Get a signed-in owner's Event subscription in the current workspace",
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/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() }) }),
route("PUT", "/api/v1/events/{eventId}", "triggers:write", { summary: "Update an Event payload schema", responses: { "200": { description: "Updated Event", content: { "application/json": { schema: jsonSchema(eventDefinitionResponse, "output") } } } } }, (service, { params, body }) => service.updateEvent(params.eventId, body), { parameters: z.object({ eventId: z.uuid() }), body: eventDefinitionUpdate }),
route("DELETE", "/api/v1/events/{eventId}", "triggers:write", { summary: "Delete an Event and its Triggers and occurrences", description:"Permanently deletes the Event, all attached Triggers, their input configurations, and the Event's occurrence history.", responses: { "200": { description: "Deleted" } } }, (service, { params }) => service.deleteEvent(params.eventId), { parameters: z.object({ eventId: z.uuid() }) }),
route("DELETE", "/api/v1/events/{eventId}", "triggers:write", { summary: "Delete an Event, its Triggers, subscriptions, and occurrences", description:"Permanently deletes the Event, all attached Triggers, their input configurations, subscriptions, and the Event's occurrence history.", responses: { "200": { description: "Deleted" } } }, (service, { params }) => service.deleteEvent(params.eventId), { parameters: z.object({ eventId: z.uuid() }) }),
route("GET", "/api/v1/events/{eventId}/occurrences", "triggers:read", { summary: "List durable Event occurrences", responses: { "200": { description: "Occurrences", content: { "application/json": { schema: jsonSchema(eventOccurrencePage, "output") } } } } }, (service, { params, query }) => service.listEventOccurrences(params.eventId, query.limit, query.cursor), { parameters: z.object({ eventId: z.uuid() }), query: eventOccurrenceQuery }),
route(
"GET",
Expand Down
13 changes: 12 additions & 1 deletion packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ import { ACCESS_SCOPES, AGENT_SCOPES, accessTokenDigest, issueAccessToken, norma

import { EventMatchRepository, wakeMcpDeliveries } from "./postgres/event-match-repository";
import { EventDefinitionRepository, EventDefinitionConflict } from "./postgres/event-definition-repository";
import { parseOccurrenceCursor, eventDefinitionInput, eventDefinitionUpdate, eventDefinitionResponse, eventDefinitionList, eventOccurrencePage } from "./event-contracts";
import { readEventSubscriptions } from "./postgres/event-subscription-repository";
import { eventSubscription, eventSubscriptionList, parseOccurrenceCursor, eventDefinitionInput, eventDefinitionUpdate, eventDefinitionResponse, eventDefinitionList, eventOccurrencePage } from "./event-contracts";
import { createFlyAccountClient, FlyAccountError, flyConnectionInput } from "./fly-account-client";
import { FlyConnectionRepository } from "./postgres/fly-connection-repository";

Expand Down Expand Up @@ -210,6 +211,16 @@ export class ApiService {
async eventContextMetadata() { await this.authorize("triggers:read"); return eventContextCatalog; }
private eventDefinitions() { return new EventDefinitionRepository(databaseFor(this.env), this.auth.tenantId); }
async listEvents() { await this.authorize("triggers:read"); return publicValue(eventDefinitionList, await this.eventDefinitions().list()); }
async listDashboardEventSubscriptions() {
await this.authorizeOwnerSession("triggers:read");
return publicValue(eventSubscriptionList, await readEventSubscriptions(databaseFor(this.env), this.auth.tenantId, this.auth.userId));
}
async getDashboardEventSubscription(id: string) {
await this.authorizeOwnerSession("triggers:read");
const [result] = await readEventSubscriptions(databaseFor(this.env), this.auth.tenantId, this.auth.userId, id);
if (!result) throw new ServiceError(404, "not_found", "Event subscription not found");
return publicValue(eventSubscription, result);
}
async getEvent(id: string) { await this.authorize("triggers:read"); const event = await this.eventDefinitions().get(id); if (!event) throw new ServiceError(404, "not_found", "Event not found"); return publicValue(eventDefinitionResponse, event); }
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; } }
Expand Down
12 changes: 12 additions & 0 deletions packages/api/src/event-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,15 @@ export function parseOccurrenceCursor(cursor: string, definitionId: string, sinc
} catch { /* The caller converts malformed cursors to a validation error. */ }
return null;
}

export const eventSubscriptionId = z.string().regex(/^sub_[a-f0-9]{64}$/);
export const eventSubscription = z.object({
id: eventSubscriptionId,
eventId: z.uuid(),
eventName: z.string(),
grantId: z.string(),
status: z.enum(["active", "expired", "stopped"]),
acknowledgmentMode: z.enum(["required", "off"]),
expiresAt: z.iso.datetime(),
});
export const eventSubscriptionList = z.array(eventSubscription);
33 changes: 33 additions & 0 deletions packages/api/src/postgres/event-subscription-repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { Database } from "./database";

type SubscriptionRow = {
id: string;
definition_id: string;
name: string;
grant_id: string;
status: "active" | "expired" | "stopped";
acknowledgment_mode: "required" | "off";
expires_at: Date;
};

// Dashboard metadata is visible to the same owner and workspace as the OAuth
// connection it belongs to. Never select webhook credentials, URL or arguments.
export async function readEventSubscriptions(db: Database, tenantId: string, userId: string, id?: string) {
const { rows } = await db.pool.query<SubscriptionRow>(
`SELECT s.id,s.definition_id,e.name,s.grant_id,
CASE WHEN s.status='stopped' THEN 'stopped'
WHEN s.expires_at<=statement_timestamp() THEN 'expired'
ELSE 'active' END AS status,
CASE WHEN s.ack_epoch IS NULL THEN 'off' ELSE 'required' END AS acknowledgment_mode,
s.expires_at
FROM app.mcp_event_subscriptions s
JOIN app.event_definitions e ON e.tenant_id=s.tenant_id AND e.id=s.definition_id
WHERE s.tenant_id=$1 AND s.user_id=$2 ${id ? "AND s.id=$3" : ""}
ORDER BY e.name,s.id`,
id ? [tenantId, userId, id] : [tenantId, userId],
);
return rows.map(row => ({
id: row.id, eventId: row.definition_id, eventName: row.name, grantId: row.grant_id,
status: row.status, acknowledgmentMode: row.acknowledgment_mode, expiresAt: row.expires_at.toISOString(),
}));
}
46 changes: 46 additions & 0 deletions packages/api/test/mcp-events.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,52 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl
const makeRecoveryDue = (occurrenceId: string) => f.db.pool.query(
"UPDATE app.mcp_event_deliveries SET ack_due_at=now()-interval '1 second' WHERE occurrence_id=$1", [occurrenceId]);

it("lists only the signed-in owner's workspace subscriptions and redacts their transport configuration", async () => {
const active = (await subscribe()).message.result.id as string;
const expired = (await subscribe(otherReceiver)).message.result.id as string;
await configure(active, true);
await f.db.pool.query("UPDATE app.mcp_event_subscriptions SET expires_at=now()-interval '1 hour' WHERE tenant_id=$1 AND id=$2", [f.tenantId, expired]);

const secondUser = crypto.randomUUID();
const member = await new IdentityRepository(f.db, f.tenantId).upsertOwner(secondUser, "other@example.test");
const otherOwner = await new IdentityRepository(f.db, f.otherTenant).upsertOwner(f.userId, "owner@example.test");
const otherDefinition = await f.seedEventTrigger(f.otherTenant);
const hiddenInWorkspace = "sub_" + "1".repeat(64), hiddenInOtherWorkspace = "sub_" + "2".repeat(64);
for (const [tenantId, userId, definitionId, id] of [
[f.tenantId, secondUser, source.definitionId, hiddenInWorkspace],
[f.otherTenant, f.userId, otherDefinition.definitionId, hiddenInOtherWorkspace],
]) {
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)
SELECT $1,$2,$3,session_version,grant_id,client_id,$4,arguments,callback_url,encrypted_secret,
secret_fingerprint,verified_at,generation,status,expires_at
FROM app.mcp_event_subscriptions WHERE tenant_id=$5 AND id=$6`, [tenantId, id, userId, definitionId, f.tenantId, active]);
}
const cookieFor = async (tenantId: string, userId: string, sessionVersion: number) => "factorize_session=" + await signSession({
...f.auth, tenantId, userId, sessionVersion, email: "owner@example.test", exp: Math.floor(Date.now() / 1000) + 60,
}, f.env.SESSION_SIGNING_SECRET);
const list = "/api/v1/event-subscriptions";
const response = await f.request(list);
expect(response.status).toBe(200);
const rows = await response.json() as Record<string, unknown>[];
const expected = { eventId: source.definitionId, eventName: "fixture-event", grantId: "grant-1", expiresAt: expect.any(String) };
expect(rows).toHaveLength(2);
expect(rows).toEqual(expect.arrayContaining([
{ ...expected, id: active, status: "active", acknowledgmentMode: "required" },
{ ...expected, id: expired, status: "expired", acknowledgmentMode: "off" },
]));
expect(await (await f.request(list + "/" + active)).json()).toEqual(rows.find(row => row.id === active));
expect((await f.request(list, "")).status).toBe(401);
expect((await f.request(list, await cookieFor(f.tenantId, secondUser, member.sessionVersion))).status).toBe(401);
expect((await f.request(list + "/" + active, await cookieFor(f.otherTenant, f.userId, otherOwner.sessionVersion))).status).toBe(404);
expect((await f.request(list + "/" + hiddenInWorkspace)).status).toBe(404);
expect((await f.request(list + "/" + hiddenInOtherWorkspace)).status).toBe(404);
expect((await f.request(list + "/malformed")).status).toBe(400);
expect((await unsubscribe()).message.result).toBeDefined();
expect(await (await f.request(list + "/" + active)).json()).toMatchObject({ status: "stopped" });
});

it("acknowledges exact durable work and recovers only the unresolved original occurrence", async () => {
const id = (await subscribe()).message.result.id;
expect((await processing("get_event_processing_acknowledgments", id)).structuredContent.enabled).toBe(false);
Expand Down
Loading
Loading