From 579b4e26636d8ecd6773f128dddd2f66f4c50eab Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 24 Nov 2026 01:20:50 +0000 Subject: [PATCH] Add event triggers and permission presets --- .node-version | 2 +- AGENTS.md | 4 +- Dockerfile.validation-runner | 2 +- docs/factorize-validation-runner.md | 6 +- docs/package-migration.md | 2 +- package-lock.json | 2 +- package.json | 2 +- packages/api-client/src/schema.d.ts | 298 ++++++++++++- ...0_event_cascade_and_permission_presets.sql | 30 ++ packages/api/src/api-contract.ts | 16 +- .../src/{flow-service.ts => api-service.ts} | 98 +++- packages/api/src/consent-api.ts | 7 +- packages/api/src/event-subscription.ts | 2 +- packages/api/src/generated/builtin-skills.ts | 8 +- packages/api/src/oauth-connection-settings.ts | 12 +- packages/api/src/postgres/schema.ts | 10 +- packages/api/src/protected-api.ts | 18 +- packages/api/src/settings-contracts.ts | 13 +- packages/api/src/trigger-contracts.ts | 14 +- .../{flow-schemas.ts => trigger-schemas.ts} | 4 +- packages/api/src/worker.ts | 4 +- packages/api/test/api-contract.test.ts | 2 + packages/api/test/apps.postgres.test.ts | 2 +- packages/api/test/auth-api.test.ts | 2 +- .../event-match-repository.postgres.test.ts | 40 ++ packages/api/test/git-https.postgres.test.ts | 2 +- packages/api/test/oidc.postgres.test.ts | 2 +- .../test/permission-presets.postgres.test.ts | 22 + .../api/test/protocol-api.postgres.test.ts | 2 + .../api/test/resource-names.postgres.test.ts | 2 +- .../test/skill-content-cache.postgres.test.ts | 2 +- packages/api/test/webhook-conditions.test.ts | 2 +- packages/app/src/features/apps/index.tsx | 11 +- packages/app/src/features/auth/consent.tsx | 2 +- .../app/src/features/auth/team-navigation.tsx | 2 +- packages/app/src/features/events/events.tsx | 7 +- .../features/settings/client-permissions.tsx | 4 +- .../src/features/settings/integrations.tsx | 4 +- .../app/src/features/settings/navigation.tsx | 3 + .../app/src/features/settings/permissions.tsx | 47 ++ packages/app/src/features/settings/routes.tsx | 4 +- packages/app/test/auth.browser.test.mjs | 24 +- packages/docs/api/authentication.mdx | 4 + packages/docs/api/openapi.mdx | 2 +- packages/docs/mcp/tools.mdx | 3 + packages/docs/openapi.yaml | 417 ++++++++++++++++-- scripts/bootstrap-test.mjs | 2 +- scripts/smoke-validation-runner-image.sh | 2 +- scripts/validation.mjs | 2 +- skills/manage-triggers/SKILL.md | 2 +- 50 files changed, 1047 insertions(+), 129 deletions(-) create mode 100644 packages/api/migrations/0100_event_cascade_and_permission_presets.sql rename packages/api/src/{flow-service.ts => api-service.ts} (86%) rename packages/api/src/{flow-schemas.ts => trigger-schemas.ts} (93%) create mode 100644 packages/api/test/permission-presets.postgres.test.ts create mode 100644 packages/app/src/features/settings/permissions.tsx diff --git a/.node-version b/.node-version index 248216ad..df6ae337 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -24.12.0 +24.21.0 diff --git a/AGENTS.md b/AGENTS.md index 7b11dac7..ec3539a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ This project in Linear is "Factorize" ## Validation -Use Node 24.12.0 and npm 11.19.0 (`.node-version` and `package.json`) and run `npm ci` after a clean checkout. +Use Node 24.21.0 and npm 11.19.0 (`.node-version` and `package.json`) and run `npm ci` after a clean checkout. Run `npm test` after the final code change; it is the complete required local validation and runs the shared backend and browser lanes used by CI. `npm run check` is an alias for the same suite. Targeted workspace commands remain @@ -12,7 +12,7 @@ available for iteration, but do not replace the root suite before handoff. For a fresh exe.dev VM, use the Factorize validation runner image described in [`docs/factorize-validation-runner.md`](docs/factorize-validation-runner.md). -It provides Node 24.12.0, npm 11.19.0, PostgreSQL and the matching Playwright +It provides Node 24.21.0, npm 11.19.0, PostgreSQL and the matching Playwright Chromium build. After checkout, run `npm ci` and `npm run test:local`; this resets only the isolated local validation database, applies migrations, and runs the complete root suite with the database variables in its child diff --git a/Dockerfile.validation-runner b/Dockerfile.validation-runner index 7f7c1b5e..b646b23b 100644 --- a/Dockerfile.validation-runner +++ b/Dockerfile.validation-runner @@ -2,7 +2,7 @@ FROM ghcr.int.exe.xyz/boldsoftware/exeuntu:latest SHELL ["/bin/bash", "-euo", "pipefail", "-c"] -ARG NODE_VERSION=24.12.0 +ARG NODE_VERSION=24.21.0 ARG NPM_VERSION=11.19.0 ARG PLAYWRIGHT_VERSION=1.64.0 diff --git a/docs/factorize-validation-runner.md b/docs/factorize-validation-runner.md index 1a0a68cb..29706013 100644 --- a/docs/factorize-validation-runner.md +++ b/docs/factorize-validation-runner.md @@ -6,7 +6,7 @@ documented exe.dev `exeuntu` base. It keeps the base image's SSH, systemd, `exedev` user, and agent setup while adding prerequisites for the complete Factorize test suite. -The image pins Node 24.12.0, npm 11.19.0, and Playwright/Chromium 1.64.0. It +The image pins Node 24.21.0, npm 11.19.0, and Playwright/Chromium 1.64.0. It installs PostgreSQL 16 without starting systemd during image build, enables the PostgreSQL service for VM boot, and sets the `postgres` password used by `scripts/bootstrap-test.mjs`. PostgreSQL listens on loopback; the test @@ -54,6 +54,10 @@ publishing a new digest, followed by repeating this sequence. ## Validated image record +The existing digest below records the previous Node 24.12.0 image. The current +Dockerfile and validation scripts target Node 24.21.0; rebuild and publish a +new image digest before using it for validation or pinning it to a Dev job. + | Field | Value | | --- | --- | | Public image digest | `ghcr.io/generationsoftware/factorize-validation-runner@sha256:1333c4a7bb49c4cbcdd28ca2b57331dfcbff7cf611db1aaeaa4830517aacf6d4` | diff --git a/docs/package-migration.md b/docs/package-migration.md index 8fdc67f4..a9759a08 100644 --- a/docs/package-migration.md +++ b/docs/package-migration.md @@ -26,7 +26,7 @@ not the persistence mechanism. Skills are standalone instruction documents. ## Local development and validation -Use Node 24.12.0 and npm 11.19.0. After a clean checkout run `npm ci`. For full +Use Node 24.21.0 and npm 11.19.0. After a clean checkout run `npm ci`. For full local validation, use the image and isolated database described in [`factorize-validation-runner.md`](factorize-validation-runner.md), then run `npm run test:local`. This applies migrations and runs the complete root suite. diff --git a/package-lock.json b/package-lock.json index dc46dd48..2b5079e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "packages/*" ], "engines": { - "node": ">=24.12.0", + "node": ">=24.21.0", "npm": ">=11.19.0" } }, diff --git a/package.json b/package.json index ff3ead23..c3648ea6 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,7 @@ "check:skills": "node scripts/generate-builtin-skills.mjs --check" }, "engines": { - "node": ">=24.12.0", + "node": ">=24.21.0", "npm": ">=11.19.0" }, "allowScripts": { diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 88431a6e..2466715d 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -963,8 +963,10 @@ export interface paths { }; get?: never; /** - * Edit an OAuth connection’s scopes and integration access - * @description Requires the triggers:write scope. + * Set an OAuth connection’s effective scopes and integration access + * @description Interactive owner session required. Saving updates the connection immediately and can add scopes beyond the original OAuth request. + * + * Requires the triggers:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ @@ -976,6 +978,84 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/permission-presets": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List team permission presets + * @description Requires the team:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_permission_presets"]; + put?: never; + /** + * Create a team permission preset + * @description Requires the team:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_permission_presets"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/permission-presets/{presetId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Update a team permission preset + * @description Requires the team:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_permission_presets_presetId"]; + post?: never; + /** + * Delete a team permission preset + * @description Requires the team:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_permission_presets_presetId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/permission-presets/{presetId}/default": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Set the team default permission preset + * @description Requires the team:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_permission_presets_presetId_default"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/access/authorizations/{grantId}": { parameters: { query?: never; @@ -1457,8 +1537,10 @@ export interface paths { put: operations["put_api_v1_events_eventId"]; post?: never; /** - * Delete an Event with no Triggers - * @description Requires the triggers:write scope. + * 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. + * + * Requires the triggers:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -3584,6 +3666,7 @@ export interface operations { "application/json": { clientName: string; scopes: string[]; + selectedScopes: string[]; request: string; signature: string; expiresAt: string; @@ -4399,8 +4482,12 @@ export interface operations { }; content: { "application/json": { - availableScopes: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "apps:manage")[]; - /** @description Integration ID to approved epoch-bound scope, or false to block. */ + availableScopes: string[]; + /** @default {} */ + scopeLabels: { + [key: string]: string; + }; + /** @default {} */ integrationOverrides: { [key: string]: string | false; }; @@ -4550,9 +4637,11 @@ export interface operations { requestBody: { content: { "application/json": { - disabledScopes: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "apps:manage")[]; + /** @description Complete owner-selected effective scope set for this connection. */ + scopes?: string[]; + disabledScopes?: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "apps:manage")[]; /** @description Integration ID to approved epoch-bound scope, or false to block. */ - integrationOverrides: { + integrationOverrides?: { [key: string]: string | false; }; expectedRevision?: number; @@ -4582,6 +4671,199 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_permission_presets: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Permission presets */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + scopes: string[]; + isDefault: boolean; + revision: number; + createdAt: string; + updatedAt: 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"]; + }; + }; + post_api_v1_permission_presets: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + name: string; + scopes: string[]; + expectedRevision?: number; + }; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + scopes: string[]; + isDefault: boolean; + revision: number; + createdAt: string; + updatedAt: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_permission_presets_presetId: { + parameters: { + query?: never; + header?: never; + path: { + presetId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + name: string; + scopes: string[]; + expectedRevision: number; + }; + }; + }; + responses: { + /** @description Updated */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + scopes: string[]; + isDefault: boolean; + revision: number; + createdAt: string; + updatedAt: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + delete_api_v1_permission_presets_presetId: { + parameters: { + query?: never; + header?: never; + path: { + presetId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": Record; + }; + }; + 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"]; + }; + }; + post_api_v1_permission_presets_presetId_default: { + parameters: { + query?: never; + header?: never; + path: { + presetId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Default updated */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ok: boolean; + }; + }; + }; + 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"]; + }; + }; delete_api_v1_access_authorizations_grantId: { parameters: { query?: never; diff --git a/packages/api/migrations/0100_event_cascade_and_permission_presets.sql b/packages/api/migrations/0100_event_cascade_and_permission_presets.sql new file mode 100644 index 00000000..4133877c --- /dev/null +++ b/packages/api/migrations/0100_event_cascade_and_permission_presets.sql @@ -0,0 +1,30 @@ +-- Event deletion removes its dependent Triggers. Trigger-owned source rows, +-- schedule state, and match records already cascade from the Trigger; Event +-- schema revisions cascade to their durable occurrences. +ALTER TABLE app.triggers DROP CONSTRAINT IF EXISTS triggers_event_definition_fk; +ALTER TABLE app.triggers ADD CONSTRAINT triggers_event_definition_fk + FOREIGN KEY (tenant_id,event_definition_id) + REFERENCES app.event_definitions(tenant_id,id) ON DELETE CASCADE; + +-- Owner-managed scope overrides can expand or restrict a connected OAuth +-- client's effective scopes independently of the original OAuth grant. +ALTER TABLE app.agent_identities ADD COLUMN scope_overrides text[]; + +-- A team may define named scope sets and select one default for new OAuth +-- authorizations. Scope names are validated against active platform scopes +-- and integrations by the API before writes. +CREATE TABLE app.permission_presets ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + id uuid NOT NULL, + name text NOT NULL, + scopes text[] NOT NULL DEFAULT '{}', + is_default boolean NOT NULL DEFAULT false, + revision integer NOT NULL DEFAULT 1 CHECK (revision > 0), + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id,id) +); +CREATE UNIQUE INDEX permission_presets_name ON app.permission_presets(tenant_id,lower(name)); +CREATE UNIQUE INDEX permission_presets_default ON app.permission_presets(tenant_id) WHERE is_default; + +INSERT INTO app.schema_migrations(version) VALUES ('0100_event_cascade_and_permission_presets') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index e1b69d6c..954bc39c 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -8,17 +8,17 @@ import { apiReflection, apiPolicyList, apiPolicyInput, requestApiInput, requestA import { queryOf } from "./query-params"; import { searchResponse } from "./search-contracts"; import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api"; -import { exeConnection, integrationStatus, clientPermissionsUpdate, authorizedClient, accessToken, createdAccessToken, savedExe, savedAmp, savedTail, okResult } from "./settings-contracts"; +import { exeConnection, integrationStatus, clientPermissionsUpdate, authorizedClient, accessToken, createdAccessToken, savedExe, savedAmp, savedTail, okResult, permissionPreset, permissionPresetInput, permissionPresetList } from "./settings-contracts"; import { eventAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts"; import { triggerResponse, triggerUpdateInput } from "./trigger-contracts"; import { z } from "zod"; import { oidcConsentInput, oidcConsentPreview } from "./oidc-provider"; import { appRegistrationInput, appRegistrationUpdate, appSecret, connectedApp, registeredApp } from "./apps-contracts"; -import type { ApiService } from "./flow-service"; +import type { ApiService } from "./api-service"; import { triggerInputSchema, fireTriggerInputSchema, triggerConditionsTestSchema, scopeSchema, teamResponse, -} from "./flow-schemas"; +} from "./trigger-schemas"; import { X_OAUTH_SCOPES } from "./x-oauth"; import document from "./api-document.json"; @@ -552,9 +552,15 @@ export const API_ROUTES: RouteContract[] = [ { ownerSession: true }, ), route("PUT", "/api/v1/access/authorizations/{grantId}/permissions", "triggers:write", { - summary: "Edit an OAuth connection’s scopes and integration access", + summary: "Set an OAuth connection’s effective scopes and integration access", + description: "Interactive owner session required. Saving updates the connection immediately and can add scopes beyond the original OAuth request.", responses: {"200": {description: "Permissions saved", content: {"application/json": {schema: jsonSchema(okResult, "output")}}}}, }, (service, {params, body}) => service.updateClientPermissions(params.grantId, body), {ownerSession: true, body: clientPermissionsUpdate}), + route("GET", "/api/v1/permission-presets", "team:read", {summary:"List team permission presets",responses:{"200":{description:"Permission presets",content:{"application/json":{schema:jsonSchema(permissionPresetList,"output")}}}}}, service=>service.listPermissionPresets(), {ownerSession:true}), + route("POST", "/api/v1/permission-presets", "team:write", {summary:"Create a team permission preset",responses:{"201":{description:"Created",content:{"application/json":{schema:jsonSchema(permissionPreset,"output")}}}}}, (service,{body})=>service.createPermissionPreset(body), {ownerSession:true,body:permissionPresetInput}), + route("PUT", "/api/v1/permission-presets/{presetId}", "team:write", {summary:"Update a team permission preset",responses:{"200":{description:"Updated",content:{"application/json":{schema:jsonSchema(permissionPreset,"output")}}}}}, (service,{params,body})=>service.updatePermissionPreset(params.presetId,body), {ownerSession:true,parameters:z.object({presetId:z.uuid()}),body:permissionPresetInput.extend({expectedRevision:z.number().int().positive()})}), + route("POST", "/api/v1/permission-presets/{presetId}/default", "team:write", {summary:"Set the team default permission preset",responses:{"200":{description:"Default updated",content:{"application/json":{schema:jsonSchema(okResult,"output")}}}}}, (service,{params})=>service.setDefaultPermissionPreset(params.presetId), {ownerSession:true,parameters:z.object({presetId:z.uuid()})}), + route("DELETE", "/api/v1/permission-presets/{presetId}", "team:write", {summary:"Delete a team permission preset",responses:{"200":{description:"Deleted"}}}, (service,{params})=>service.deletePermissionPreset(params.presetId), {ownerSession:true,parameters:z.object({presetId:z.uuid()})}), route("DELETE", "/api/v1/access/authorizations/{grantId}", "triggers:write", {summary:"Revoke one isolated OAuth connection", description:"Other connections, including copies of the same client, retain their approvals.",responses:{"200":{description:"Authorization revoked",content:{"application/json":{schema:jsonSchema(z.object({revoked:z.number().int()}),"output")}}}}}, (service,{params})=>service.revokeOAuthAuthorization(params.grantId), {ownerSession:true}), route( "DELETE", @@ -690,7 +696,7 @@ export const API_ROUTES: RouteContract[] = [ 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 with no Triggers", 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 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("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", diff --git a/packages/api/src/flow-service.ts b/packages/api/src/api-service.ts similarity index 86% rename from packages/api/src/flow-service.ts rename to packages/api/src/api-service.ts index 5a2baf04..efe0b6a4 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/api-service.ts @@ -25,9 +25,10 @@ import { searchResponse } from "./search-contracts"; import { integrationStatus, exeConnection, accessToken, createdAccessToken, clientPermissionsUpdate, clientNameInput, authorizedClient } from "./settings-contracts"; import { namedOption, providerOptions, githubRepository, githubInstallation, tailIntegration } from "./editor-contracts"; import { z } from "zod"; +import { permissionPreset, permissionPresetInput, permissionPresetList } from "./settings-contracts"; import { eventContextCatalog } from "./trigger-context"; import type { Env, OAuthProps } from "./types"; -import { type TriggerInput, type FireTriggerInput, triggerConditionsTestSchema } from "./flow-schemas"; +import { type TriggerInput, type FireTriggerInput, triggerConditionsTestSchema } from "./trigger-schemas"; import { nextOccurrence, validateScheduleConfig } from "./schedule"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; @@ -47,7 +48,7 @@ import { installedEventAvailability } from "./trigger-availability"; import { evaluateWebhookConditions } from "./webhook-conditions"; import { ProviderCatalog } from "./postgres/provider-catalog"; -import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken, normalizeScopes } from "./access-tokens"; +import { ACCESS_SCOPES, AGENT_SCOPES, accessTokenDigest, issueAccessToken, normalizeScopes } from "./access-tokens"; import { SkillRepository, SkillConflict } from "./postgres/skill-repository"; import { EventMatchRepository } from "./postgres/event-match-repository"; @@ -231,7 +232,7 @@ export class ApiService { 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; } } - async deleteEvent(id: string) { await this.authorize("triggers:write"); const linked = await databaseFor(this.env).pool.query("SELECT 1 FROM app.triggers WHERE tenant_id=$1 AND event_definition_id=$2 LIMIT 1", [this.auth.tenantId, id]); if (linked.rowCount) throw new ServiceError(409, "event_has_triggers", "Remove the Event's Triggers before deleting it."); if (!await this.eventDefinitions().delete(id)) throw new ServiceError(404, "not_found", "Event not found"); return { id, deleted: true as const }; } + 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 }; } 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 mcpReadEvent(uri: string) { let parsed: URL; try { parsed = new URL(uri); } catch { throw new ServiceError(400, "invalid_resource", "Expected a Factorize Event resource URI."); } @@ -497,30 +498,78 @@ export class ApiService { await databaseFor(this.env).pool.query("UPDATE app.agent_identities SET display_name=$3 WHERE tenant_id=$1 AND id=$2", [this.auth.tenantId, identity.id, name]); return { name }; } + private async validatePermissionScopes(input: string[]) { + const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId); + const allowed = new Set([...AGENT_SCOPES, ...integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)]); + if (input.some(scope => !allowed.has(scope))) throw new ServiceError(400, "invalid_request", "One or more permission scopes are unsupported or unavailable."); + return [...new Set(input)]; + } + async listPermissionPresets() { + await this.authorizeOwnerSession("team:read"); + const rows = await databaseFor(this.env).pool.query("SELECT id,name,scopes,is_default,revision,created_at,updated_at FROM app.permission_presets WHERE tenant_id=$1 ORDER BY lower(name),id", [this.auth.tenantId]); + return publicValue(permissionPresetList, rows.rows.map(row => ({ id: row.id, name: row.name, scopes: row.scopes, isDefault: row.is_default, revision: row.revision, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }))); + } + async createPermissionPreset(input: unknown) { + await this.authorizeOwnerSession("team:write"); + const parsed = permissionPresetInput.parse(input), scopes = await this.validatePermissionScopes(parsed.scopes), id = crypto.randomUUID(); + const row = (await databaseFor(this.env).pool.query("INSERT INTO app.permission_presets(tenant_id,id,name,scopes) VALUES($1,$2,$3,$4) RETURNING id,name,scopes,is_default,revision,created_at,updated_at", [this.auth.tenantId,id,parsed.name,scopes])).rows[0]; + return publicValue(permissionPreset, { id: row.id, name: row.name, scopes: row.scopes, isDefault: row.is_default, revision: row.revision, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); + } + async updatePermissionPreset(id: string, input: unknown) { + await this.authorizeOwnerSession("team:write"); + const parsed = permissionPresetInput.extend({ expectedRevision: z.number().int().positive() }).parse(input), scopes = await this.validatePermissionScopes(parsed.scopes); + const result = await databaseFor(this.env).pool.query("UPDATE app.permission_presets SET name=$3,scopes=$4,revision=revision+1,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND revision=$5 RETURNING id,name,scopes,is_default,revision,created_at,updated_at", [this.auth.tenantId,id,parsed.name,scopes,parsed.expectedRevision]); + if (!result.rowCount) throw new ServiceError(409,"conflict","Permission preset changed or no longer exists."); + const row = result.rows[0]; + return publicValue(permissionPreset, { id: row.id, name: row.name, scopes: row.scopes, isDefault: row.is_default, revision: row.revision, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); + } + async setDefaultPermissionPreset(id: string) { + await this.authorizeOwnerSession("team:write"); + await databaseFor(this.env).transaction(async client => { + const selected = await client.query("SELECT id FROM app.permission_presets WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.auth.tenantId,id]); + if (!selected.rowCount) throw new ServiceError(404,"not_found","Permission preset not found."); + await client.query("UPDATE app.permission_presets SET is_default=false,updated_at=now() WHERE tenant_id=$1 AND is_default", [this.auth.tenantId]); + await client.query("UPDATE app.permission_presets SET is_default=true,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.auth.tenantId,id]); + }); + return { ok: true }; + } + async deletePermissionPreset(id: string) { + await this.authorizeOwnerSession("team:write"); + const result = await databaseFor(this.env).pool.query("DELETE FROM app.permission_presets WHERE tenant_id=$1 AND id=$2 RETURNING id", [this.auth.tenantId,id]); + if (!result.rowCount) throw new ServiceError(404,"not_found","Permission preset not found."); + return { id, deleted: true }; + } async updateClientPermissions(grantId: string, input: unknown) { await this.authorizeOwnerSession("triggers:write"); const edit = clientPermissionsUpdate.parse(input); const client = (await this.listAuthorizedClients()).find(client => client.grantId === grantId); if (!client) throw new ServiceError(404, "not_found", "Authorization not found."); - let disabledScopes: typeof client.availableScopes; - let integrationOverrides: Record; - disabledScopes = edit.disabledScopes; - integrationOverrides = edit.integrationOverrides; - if (disabledScopes.some(scope => !client.availableScopes.includes(scope))) throw new ServiceError(400, "invalid_request", "Scope is outside this authorization."); const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId); - const current = new Map(integrations.map(row => [row.id, row])); - if (Object.entries(integrationOverrides).some(([id, approval]) => { - const row = current.get(id); - return !row || (approval !== false && (!row.available || row.policy === "disabled" || approval !== row.requiredScope)); - })) throw new ServiceError(409, "conflict", "Integration availability changed. Reload permissions."); + let scopes = edit.scopes; + if (!scopes) { + scopes = client.scopes.filter(scope => !edit.disabledScopes?.includes(scope as any)); + for (const [id, approval] of Object.entries(edit.integrationOverrides ?? {})) { + const integration = integrations.find(row => row.id === id); + if (!integration || (approval !== false && approval !== integration.requiredScope)) throw new ServiceError(409,"conflict","Integration availability changed. Reload permissions."); + scopes = approval === false ? scopes.filter(scope => scope !== integration.requiredScope) : [...scopes,integration.requiredScope]; + } + } + if (scopes.some(scope => !client.availableScopes.includes(scope) && !client.scopes.includes(scope))) throw new ServiceError(400, "invalid_request", "Scope is outside this authorization."); + const currentScopes = new Set(integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)); + if (scopes.some(scope => scope.startsWith("integration:") && !currentScopes.has(scope) && !client.scopes.includes(scope))) throw new ServiceError(409, "conflict", "Integration availability changed. Reload permissions."); + const integrationOverrides = { ...client.integrationOverrides }; + for (const integration of integrations) { + if (scopes.includes(integration.requiredScope)) delete integrationOverrides[integration.id]; + else if (integration.available && integration.policy !== "disabled") integrationOverrides[integration.id] = false; + } const result = await databaseFor(this.env).pool.query(` - INSERT INTO app.agent_identities AS i(tenant_id,kind,subject,user_id,session_version,disabled_scopes,integration_overrides,permissions_revision) - SELECT $1,'oauth',$2,$3,$4,$5,$6,1 WHERE coalesce($7::integer,0)=0 OR EXISTS + INSERT INTO app.agent_identities AS i(tenant_id,kind,subject,user_id,session_version,disabled_scopes,scope_overrides,integration_overrides,permissions_revision) + SELECT $1,'oauth',$2,$3,$4,'{}',$5,$6,1 WHERE coalesce($7::integer,0)=0 OR EXISTS (SELECT 1 FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2) - ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET disabled_scopes=excluded.disabled_scopes, - integration_overrides=excluded.integration_overrides, permissions_revision=i.permissions_revision+1 + ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET disabled_scopes='{}',scope_overrides=excluded.scope_overrides, + integration_overrides=excluded.integration_overrides,permissions_revision=i.permissions_revision+1 WHERE i.revoked_at IS NULL AND i.user_id=excluded.user_id AND ($7 IS NULL OR i.permissions_revision=$7) - RETURNING permissions_revision`, [this.auth.tenantId, grantId, this.auth.userId, this.auth.sessionVersion, disabledScopes, JSON.stringify(integrationOverrides), edit.expectedRevision ?? client.revision]); + RETURNING permissions_revision`, [this.auth.tenantId, grantId, this.auth.userId, this.auth.sessionVersion, [...new Set(scopes)], JSON.stringify(integrationOverrides), edit.expectedRevision ?? client.revision]); if (!result.rowCount) throw new ServiceError(409, "conflict", "Connection permissions changed. Reload permissions."); return { ok: true }; } @@ -531,12 +580,19 @@ export class ApiService { do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => (grant.metadata as any)?.tenantId === this.auth.tenantId && (!grant.expiresAt || grant.expiresAt > Math.floor(Date.now() / 1000)))); cursor = page.cursor; } while (cursor); const clients = await Promise.all([...new Set(grants.map(grant => grant.clientId))].map(async clientId => [clientId, await this.env.OAUTH_PROVIDER!.lookupClient(clientId)] as const)); const byId = new Map(clients); - const settings = await databaseFor(this.env).pool.query("SELECT subject,display_name,disabled_scopes,integration_overrides,permissions_revision FROM app.agent_identities WHERE tenant_id=$1 AND user_id=$2 AND kind='oauth' AND subject=ANY($3)", [this.auth.tenantId, this.auth.userId, grants.map(g => g.id)]); + const settings = await databaseFor(this.env).pool.query("SELECT subject,display_name,disabled_scopes,scope_overrides,integration_overrides,permissions_revision FROM app.agent_identities WHERE tenant_id=$1 AND user_id=$2 AND kind='oauth' AND subject=ANY($3)", [this.auth.tenantId, this.auth.userId, grants.map(g => g.id)]); const byGrant = new Map(settings.rows.map(row => [row.subject, row])); + const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId); + const globallyAvailable = [...AGENT_SCOPES, ...integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)]; + const scopeLabels = Object.fromEntries(integrations.map(row => [row.requiredScope, `${row.name} integration access`])); return publicValue(z.array(authorizedClient), grants.map(grant => { - const row = byGrant.get(grant.id), availableScopes = normalizeScopes(grant.scope); + const row = byGrant.get(grant.id), grantedScopes = normalizeScopes(grant.scope); + const baseScopes = row?.scope_overrides ?? grantedScopes.filter(scope => !row?.disabled_scopes.includes(scope)); + const baselineScopes = integrations.filter(integration => integration.policy === "baseline" && integration.available && row?.integration_overrides?.[integration.id] !== false).map(integration => integration.requiredScope); + const scopes = [...new Set([...baseScopes,...baselineScopes])].filter(scope => !row?.disabled_scopes.includes(scope)); + const availableScopes = [...new Set([...globallyAvailable, ...scopes])]; return { grantId: grant.id, clientId: grant.clientId, clientName: row?.display_name ?? byId.get(grant.clientId)?.clientName ?? grant.clientId, appName: byId.get(grant.clientId)?.clientName ?? grant.clientId, - availableScopes: availableScopes.filter(scope => !scope.startsWith("integration:")), scopes: availableScopes.filter(scope => !row?.disabled_scopes.includes(scope)), revision: row?.permissions_revision ?? 0, + availableScopes, scopeLabels, scopes, revision: row?.permissions_revision ?? 0, integrationOverrides: row?.integration_overrides ?? {}, authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }; })); diff --git a/packages/api/src/consent-api.ts b/packages/api/src/consent-api.ts index f0596113..01f185ef 100644 --- a/packages/api/src/consent-api.ts +++ b/packages/api/src/consent-api.ts @@ -10,7 +10,7 @@ import type { Session } from "./session"; import { AGENT_SCOPES, normalizeScopes } from "./access-tokens"; export const consentPreviewInput = z.object({ authorizationQuery: z.string().min(1).max(8192) }).strict(); export const consentDecisionInput = z.object({ request: z.string().min(1).max(16384), signature: z.string().min(1).max(256), decision: z.enum(["allow", "deny"]), scopes: z.array(z.string()) }).strict(); -export const consentPreviewResponse = z.object({ clientName: z.string(), scopes: z.array(z.string()), request: z.string(), signature: z.string(), expiresAt: z.string(), integrationLabels: z.array(z.object({ scope: z.string(), name: z.string(), description: z.string().nullable() })).optional() }); +export const consentPreviewResponse = z.object({ clientName: z.string(), scopes: z.array(z.string()), selectedScopes: z.array(z.string()), request: z.string(), signature: z.string(), expiresAt: z.string(), integrationLabels: z.array(z.object({ scope: z.string(), name: z.string(), description: z.string().nullable() })).optional() }); export const consentDecisionResponse = z.object({ redirectTo: z.string() }); const supported: readonly string[] = AGENT_SCOPES; const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))); @@ -39,7 +39,10 @@ export async function consentPreview(env: Env, session: Session, input: z.infer< if (parsed.scope.some(scope => !supported.includes(scope) && !isIntegrationScope(scope))) return null; const requestedScopes = parsed.scope; const integrationLabels = await integrationConsentLabels(env, session.tenantId, requestedScopes); - return { integrationLabels, clientName: client.clientName ?? "this client", scopes: normalizeScopes(requestedScopes), request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() }; + const scopes = normalizeScopes(requestedScopes); + const defaultPreset = (await databaseFor(env).pool.query<{scopes:string[]}>("SELECT scopes FROM app.permission_presets WHERE tenant_id=$1 AND is_default=true", [session.tenantId])).rows[0]; + const selectedScopes = defaultPreset ? scopes.filter(scope => defaultPreset.scopes.includes(scope)) : scopes; + return { integrationLabels, clientName: client.clientName ?? "this client", scopes, selectedScopes, request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() }; } export async function consentDecision(env: Env, session: Session, input: z.infer) { if (!env.OAUTH_PROVIDER || !equal(input.signature, await hmac(binding(input.request, session), env.SESSION_SIGNING_SECRET))) return null; diff --git a/packages/api/src/event-subscription.ts b/packages/api/src/event-subscription.ts index 4ebe590b..6283d706 100644 --- a/packages/api/src/event-subscription.ts +++ b/packages/api/src/event-subscription.ts @@ -1,6 +1,6 @@ import { createMcpHandler, type McpServer } from "@modelcontextprotocol/server"; import { z } from "zod"; -import { ApiService } from "./flow-service"; +import { ApiService } from "./api-service"; const prefix = "factorize://events/"; function eventIdFromUri(uri: string) { diff --git a/packages/api/src/generated/builtin-skills.ts b/packages/api/src/generated/builtin-skills.ts index 0d0891f2..b71bd291 100644 --- a/packages/api/src/generated/builtin-skills.ts +++ b/packages/api/src/generated/builtin-skills.ts @@ -1,5 +1,5 @@ // Generated by scripts/generate-builtin-skills.mjs; edit skills/*/SKILL.md. -export const builtinSkillsVersion = "54982fec176ce16d59c482a7752c72f13446cca6b3820714f3bba082023ded65"; +export const builtinSkillsVersion = "41341c915eed1461684d68f4f1c2a2abedbaff78b92dc4eb09c4723536fb4788"; export const builtinSkillDocuments = [ { "name": "manage-skills", @@ -17,8 +17,8 @@ export const builtinSkillDocuments = [ "name": "manage-triggers", "description": "Configure input Triggers that publish durable Factorize Events." }, - "text": "---\nname: manage-triggers\ndescription: Configure input Triggers that publish durable Factorize Events.\n---\n# Manage Events and Triggers\n\nCall `get_api_reflection` to inspect current identity and permissions. Events and Skills are independent: an Event describes a durable payload stream, a Trigger watches one or more input sources and publishes matching occurrences, and a Skill is a standalone instruction document.\n\n## Events\n\nUse `list_events` and `get_event` to inspect Events and their payload schema revisions. Create an Event with `create_event`, including a lowercase stable `name`, optional description, and JSON Schema object in `payloadSchema`. Use `update_event` with the current `expectedRevision` to add a schema revision. Existing occurrences keep their original revision. Delete Events only after removing their Triggers.\n\nMCP subscribers read `factorize://events/{eventId}/occurrences`. Subscribe through `subscriptions/listen`; on resource update, read the occurrence resource. Occurrences are durable, so reconnecting clients can read missed records. Use `list_event_occurrences` to page through stored occurrences.\n\n## Triggers\n\nEach Trigger belongs to one Event; multiple Triggers may publish the same Event. Configure a Trigger with an existing `eventId`, or let the API create its initial Event. Trigger inputs can be manual, scheduled, or provider webhooks. Schedules use cron and an IANA timezone. Webhook inputs select a provider and provider-specific filters. Use `list_github_installations` and `list_cloudflare_tail_integrations` to discover saved provider setup.\n\nUse `list_triggers` and `get_trigger` to inspect Triggers. `create_trigger` and `update_trigger` require `triggers:write`; read before editing and preserve stable IDs for input definitions. A successful input match writes one schema-validated Event occurrence. Reuse `idempotencyKey` when retrying `fire_trigger`; duplicate source deliveries do not create duplicate occurrences. `enable_trigger` and `disable_trigger` control future input processing. `delete_trigger` removes its future automation.\n\nWebhook `conditions` are optional and can be checked with `test_trigger_webhook_conditions` against representative prepared data; this does not verify provider authentication or delivery. Use `list_trigger_webhook_activity`, `list_webhook_deliveries`, and `get_webhook_delivery` to inspect safe input-processing results.\n", - "digest": "sha256:9edc9e0235fc7866f6d822eb0d1b6fd2a646bebbd3a1a19cd9729b4d431151da", - "size": 2416 + "text": "---\nname: manage-triggers\ndescription: Configure input Triggers that publish durable Factorize Events.\n---\n# Manage Events and Triggers\n\nCall `get_api_reflection` to inspect current identity and permissions. Events and Skills are independent: an Event describes a durable payload stream, a Trigger watches one or more input sources and publishes matching occurrences, and a Skill is a standalone instruction document.\n\n## Events\n\nUse `list_events` and `get_event` to inspect Events and their payload schema revisions. Create an Event with `create_event`, including a lowercase stable `name`, optional description, and JSON Schema object in `payloadSchema`. Use `update_event` with the current `expectedRevision` to add a schema revision. Existing occurrences keep their original revision. `delete_event` permanently deletes the Event, all attached Triggers and input configurations, and all occurrence history.\n\nMCP subscribers read `factorize://events/{eventId}/occurrences`. Subscribe through `subscriptions/listen`; on resource update, read the occurrence resource. Occurrences are durable, so reconnecting clients can read missed records. Use `list_event_occurrences` to page through stored occurrences.\n\n## Triggers\n\nEach Trigger belongs to one Event; multiple Triggers may publish the same Event. Configure a Trigger with an existing `eventId`, or let the API create its initial Event. Trigger inputs can be manual, scheduled, or provider webhooks. Schedules use cron and an IANA timezone. Webhook inputs select a provider and provider-specific filters. Use `list_github_installations` and `list_cloudflare_tail_integrations` to discover saved provider setup.\n\nUse `list_triggers` and `get_trigger` to inspect Triggers. `create_trigger` and `update_trigger` require `triggers:write`; read before editing and preserve stable IDs for input definitions. A successful input match writes one schema-validated Event occurrence. Reuse `idempotencyKey` when retrying `fire_trigger`; duplicate source deliveries do not create duplicate occurrences. `enable_trigger` and `disable_trigger` control future input processing. `delete_trigger` removes its future automation.\n\nWebhook `conditions` are optional and can be checked with `test_trigger_webhook_conditions` against representative prepared data; this does not verify provider authentication or delivery. Use `list_trigger_webhook_activity`, `list_webhook_deliveries`, and `get_webhook_delivery` to inspect safe input-processing results.\n", + "digest": "sha256:8fef06466e055cc430521724a428bbe8330754cf9208f11a10df723bed736fec", + "size": 2488 } ] as const; diff --git a/packages/api/src/oauth-connection-settings.ts b/packages/api/src/oauth-connection-settings.ts index 34c7cf63..552543ba 100644 --- a/packages/api/src/oauth-connection-settings.ts +++ b/packages/api/src/oauth-connection-settings.ts @@ -1,11 +1,13 @@ import { databaseFor } from "./postgres/database"; import type { Env, OAuthProps } from "./types"; -export async function disabledConnectionScopes(env: Env, auth: OAuthProps): Promise { - if (auth.authMethod !== "oauth" || !auth.oauthGrantId) return []; - const { rows } = await databaseFor(env).pool.query<{ disabled_scopes: string[] }>( - "SELECT disabled_scopes FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2 AND user_id=$3", +export async function effectiveConnectionScopes(env: Env, auth: OAuthProps, grantScopes: string[] = auth.scopes): Promise { + if (auth.authMethod !== "oauth" || !auth.oauthGrantId) return grantScopes; + const { rows } = await databaseFor(env).pool.query<{ disabled_scopes: string[]; scope_overrides: string[] | null }>( + "SELECT disabled_scopes,scope_overrides FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2 AND user_id=$3", [auth.tenantId, auth.oauthGrantId, auth.userId], ); - return rows[0]?.disabled_scopes ?? []; + const policy = rows[0]; + const effective = policy?.scope_overrides ?? grantScopes; + return effective.filter(scope => !policy?.disabled_scopes.includes(scope)); } diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 231ee508..c0788dcc 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -69,10 +69,16 @@ export const agentIntegrations = app.table("agent_integrations", { policy:text("policy").$type<"baseline"|"requestable"|"disabled">().notNull().default("requestable"),epoch:integer("epoch").notNull().default(1),revision:integer("revision").notNull().default(1), },t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.credentialId)]); export const agentIdentities = app.table("agent_identities", { - displayName: text("display_name"), disabledScopes: text("disabled_scopes").array().notNull().default([]), + displayName: text("display_name"), disabledScopes: text("disabled_scopes").array().notNull().default([]), scopeOverrides: text("scope_overrides").array(), integrationOverrides: jsonb("integration_overrides").notNull().default({}), permissionsRevision: integer("permissions_revision").notNull().default(0), tenantId:uuid("tenant_id").notNull().references(()=>tenants.id,{onDelete:"cascade"}),id:uuid("id").notNull().defaultRandom(),kind:text("kind").$type<"oauth">().notNull(),subject:text("subject").notNull(),userId:uuid("user_id").notNull(),sessionVersion:integer("session_version").notNull(),revokedAt:timestamp("revoked_at",{withTimezone:true}),createdAt:createdAt(), },t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.subject)]); +export const permissionPresets = app.table("permission_presets", { + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), + id: uuid("id").notNull(), name: text("name").notNull(), scopes: text("scopes").array().notNull().default([]), + isDefault: boolean("is_default").notNull().default(false), revision: integer("revision").notNull().default(1), + createdAt: createdAt(), updatedAt: updatedAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("permission_presets_name").on(t.tenantId, sql`lower(${t.name})`), uniqueIndex("permission_presets_default").on(t.tenantId).where(sql`${t.isDefault}`)]); export const agentProxyResponses = app.table("agent_proxy_responses", { tenantId:uuid("tenant_id").notNull(),id:uuid("id").notNull(),identityId:uuid("identity_id").notNull(),integrationId:uuid("integration_id").notNull(),integrationEpoch:integer("integration_epoch").notNull(),objectKey:text("object_key").notNull().unique(),size:integer("size"),expiresAt:timestamp("expires_at",{withTimezone:true}).notNull(), },t=>[primaryKey({columns:[t.tenantId,t.id]}),foreignKey({columns:[t.tenantId,t.identityId],foreignColumns:[agentIdentities.tenantId,agentIdentities.id]}),foreignKey({columns:[t.tenantId,t.integrationId],foreignColumns:[agentIntegrations.tenantId,agentIntegrations.id]}),index("agent_proxy_response_expiry").on(t.expiresAt)]); @@ -93,7 +99,7 @@ export const eventDefinitionRevisions = app.table("event_definition_revisions", }, t => [primaryKey({columns:[t.tenantId,t.definitionId,t.revision]}),foreignKey({columns:[t.tenantId,t.definitionId],foreignColumns:[eventDefinitions.tenantId,eventDefinitions.id]}).onDelete("cascade")]); export const triggers = app.table("triggers", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), name: text("name").notNull(), description: text("description").notNull().default(""), slug: text("slug").notNull(), revision: integer("revision").notNull().default(1), eventDefinitionId: uuid("event_definition_id").notNull(), enabled: boolean("enabled").notNull().default(true), createdAt: createdAt(), updatedAt: updatedAt(), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.slug), foreignKey({columns:[t.tenantId,t.eventDefinitionId],foreignColumns:[eventDefinitions.tenantId,eventDefinitions.id]}).onDelete("restrict")]); +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.slug), foreignKey({columns:[t.tenantId,t.eventDefinitionId],foreignColumns:[eventDefinitions.tenantId,eventDefinitions.id]}).onDelete("cascade")]); export const skillLibraries = app.table("skill_libraries", { tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, {onDelete:"cascade"}), repo: text("repo").notNull().unique(), remote: text("remote").notNull(), source: jsonb("source").notNull(), diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 34262762..a0895a03 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -4,7 +4,7 @@ import {createPayloadInput,appendPayloadInput,finalizePayloadInput,attachmentInp import {operationRef,operationRead} from "./proxy-operations"; import {proxyToolResult} from "./proxy-result"; import {SKILLS_EXTENSION} from "./mcp-skills"; -import { disabledConnectionScopes } from "./oauth-connection-settings"; +import { effectiveConnectionScopes } from "./oauth-connection-settings"; import { clientNameInput } from "./settings-contracts"; import { SkillContentError } from "./skill-files"; import { Hono } from "hono"; @@ -16,8 +16,8 @@ import { WorkerEntrypoint } from "cloudflare:workers"; import { createMcpHandler, McpServer, ResourceTemplate, ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server"; import { createMcpHonoApp } from "@modelcontextprotocol/hono"; import { z } from "zod"; -import { ApiService, ServiceError } from "./flow-service"; -import { triggerConditionsTestSchema, triggerIdSchema, triggerInputSchema, fireTriggerInputSchema } from "./flow-schemas"; +import { ApiService, ServiceError } from "./api-service"; +import { triggerConditionsTestSchema, triggerIdSchema, triggerInputSchema, fireTriggerInputSchema } from "./trigger-schemas"; import type { Env, OAuthProps } from "./types"; import { executeAuth, validBrowserOrigin } from "./auth-api"; import { matchApiOperation } from "./api-contract"; @@ -70,8 +70,7 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP try { const url = new URL(request.url), path = url.pathname; if (auth?.oauthGrantId) { - const disabled = await disabledConnectionScopes(env, auth); - auth = { ...auth, scopes: auth.scopes.filter(scope => !disabled.includes(scope)) }; + auth = { ...auth, scopes: await effectiveConnectionScopes(env, auth, auth.scopes) }; if (path.startsWith("/api/v1/agent/") && !auth.scopes.includes("proxy:use")) throw new ServiceError(403, "insufficient_scope", "The proxy:use scope is required."); } if (path === "/mcp") { @@ -94,7 +93,9 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP const credentialActive = async () => { if (listenerAuth.oauthGrantId) { const token = await env.OAUTH_PROVIDER?.unwrapToken(request.headers.get("Authorization")?.slice(7) ?? ""); - return token?.grantId === listenerAuth.oauthGrantId && token.expiresAt > Date.now()/1000 && normalizeScopes(token.scope).includes(requiredScope) && !(await disabledConnectionScopes(env, listenerAuth)).includes(requiredScope); + if (token?.grantId !== listenerAuth.oauthGrantId || token.expiresAt <= Date.now()/1000) return false; + const tokenScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(listenerAuth.scopes).includes(scope)); + return (await effectiveConnectionScopes(env, listenerAuth, tokenScopes)).includes(requiredScope); } return listenerAuth.scopes.includes(requiredScope); // The database read rechecks owner membership and key activity. }; @@ -190,7 +191,7 @@ function createMcpServer(service: ApiService, subscriptions = true): McpServer { tool("get_event", "Read an Event and its current payload schema revision.", z.object({eventId:z.uuid()}), ({eventId}:any) => service.getEvent(eventId)); tool("create_event", "Create a durable Event that one or more Triggers can publish.", eventDefinitionInput, (input:any) => service.createEvent(input)); tool("update_event", "Create a new Event payload schema revision; existing occurrences retain their original revision.", eventDefinitionUpdate.extend({eventId:z.uuid()}), ({eventId,...input}:any) => service.updateEvent(eventId,input)); - tool("delete_event", "Delete an Event with no attached Triggers.", z.object({eventId:z.uuid()}), ({eventId}:any) => service.deleteEvent(eventId)); + tool("delete_event", "Permanently delete an Event, all its Triggers and input configurations, and its occurrence history.", z.object({eventId:z.uuid()}), ({eventId}:any) => service.deleteEvent(eventId)); tool("list_event_occurrences", "Read durable Event occurrences in reverse order.", z.object({eventId:z.uuid(),...eventOccurrenceQuery.shape}), ({eventId,limit,cursor}:any) => service.listEventOccurrences(eventId,limit,cursor)); tool("list_triggers", "List triggers and their parent Events", z.object({}), () => service.listTriggers()); tool("list_skills", "List searchable team skill metadata. Shared edits affect every trigger using the skill; bodies are omitted.", z.object({ q: z.string().optional(), limit: z.number().int().min(1).max(100).default(30), cursor: z.string().optional() }), (input: any) => service.listSkills({ q: input.q ?? "", limit: input.limit, cursor: input.cursor })); @@ -249,7 +250,8 @@ export class ProtectedApiHandler extends WorkerEntrypoint { const token = credential && this.env.OAUTH_PROVIDER ? await this.env.OAUTH_PROVIDER.unwrapToken(credential) : null; if (!token || token.userId !== auth.userId || !token.grant?.clientId) return Response.json({error:{code:"invalid_token",message:"Invalid OAuth authorization"}}, {status:401}); // Props describe original consent. The presented token may be narrowed. - auth = {...auth, authMethod: "oauth", scopes: normalizeScopes(token.scope).filter(scope => normalizeScopes(auth.scopes).includes(scope)), oauthGrantId: token.grantId, oauthClientId: token.grant.clientId, oauthExpiresAt: token.expiresAt}; + const grantScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(auth.scopes).includes(scope)); + auth = {...auth, authMethod: "oauth", scopes: grantScopes, oauthGrantId: token.grantId, oauthClientId: token.grant.clientId, oauthExpiresAt: token.expiresAt}; } return protectedApiFetch(request, this.env, auth, this.ctx); } diff --git a/packages/api/src/settings-contracts.ts b/packages/api/src/settings-contracts.ts index 024f656a..95f202b1 100644 --- a/packages/api/src/settings-contracts.ts +++ b/packages/api/src/settings-contracts.ts @@ -7,15 +7,20 @@ export const ampConnection = z.object({ connectionId: z.string(), project: z.str export const integrationStatus = z.object({ linear: z.object({ organizationName: z.string().nullable(), viewerEmail: z.string().nullable() }).nullable(), clickup: z.object({ teamName: z.string().nullable() }).nullable(), exe: exeConnection.nullable(), exeConnections: z.array(exeConnection), ampConnections: z.array(ampConnection), cloudflareTail: z.object({ count: z.number().int(), installations: z.array(tailIntegration) }) }); export const clientNameInput = z.object({ name: z.string().trim().min(1).max(120) }).strict(); export const clientPermissionsInput = z.object({ - disabledScopes: z.array(z.enum(AGENT_SCOPES)).max(AGENT_SCOPES.length), - integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).describe("Integration ID to approved epoch-bound scope, or false to block."), + scopes: z.array(z.string()).max(100).optional().describe("Complete owner-selected effective scope set for this connection."), + // Accept the previous restriction-only payload during client upgrades. + disabledScopes: z.array(z.enum(AGENT_SCOPES)).max(AGENT_SCOPES.length).optional(), + integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).optional().describe("Integration ID to approved epoch-bound scope, or false to block."), expectedRevision: z.number().int().nonnegative().optional(), -}).strict(); +}).strict().refine(value => value.scopes !== undefined || value.disabledScopes !== undefined || value.integrationOverrides !== undefined, "Supply a scope selection."); export const clientPermissionsUpdate = clientPermissionsInput; -export const authorizedClient = z.object({ availableScopes: z.array(z.enum(AGENT_SCOPES)), integrationOverrides: clientPermissionsInput.shape.integrationOverrides, revision: z.number().int(), grantId: z.string(), clientId: z.string(), clientName: z.string(), appName: z.string().optional(), scopes: z.array(z.string()), authorizationDate: timestamp, expiresAt: timestamp.nullable(), lastUsedAt: timestamp.nullable() }); +export const authorizedClient = z.object({ availableScopes: z.array(z.string()), scopeLabels: z.record(z.string(),z.string()).default({}), integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).default({}), revision: z.number().int(), grantId: z.string(), clientId: z.string(), clientName: z.string(), appName: z.string().optional(), scopes: z.array(z.string()), authorizationDate: timestamp, expiresAt: timestamp.nullable(), lastUsedAt: timestamp.nullable() }); export const accessToken = z.object({ id: z.string(), name: z.string(), scopes: z.array(z.enum(ACCESS_SCOPES)), created_at: timestamp, expires_at: timestamp, last_used_at: timestamp.nullable().optional(), revoked_at: timestamp.nullable().optional() }); export const createdAccessToken = accessToken.extend({ token: z.string() }); export const okResult = z.object({ ok: z.boolean() }); +export const permissionPresetInput = z.object({ name: z.string().trim().min(1).max(100), scopes: z.array(z.string()).max(100), expectedRevision: z.number().int().positive().optional() }).strict(); +export const permissionPreset = z.object({ id: z.uuid(), name: z.string(), scopes: z.array(z.string()), isDefault: z.boolean(), revision: z.number().int().positive(), createdAt: timestamp, updatedAt: timestamp }); +export const permissionPresetList = z.array(permissionPreset); export const savedExe = okResult.extend({ connectionId: z.string() }); export const savedAmp = okResult.extend({ connectionId: z.string() }); export const savedTail = z.object({ integrationId: z.string(), name: z.string(), status: z.literal("connected"), secretConfigured: z.literal(true), generatedSecret: z.string().optional() }); diff --git a/packages/api/src/trigger-contracts.ts b/packages/api/src/trigger-contracts.ts index 559ac71c..cc227d64 100644 --- a/packages/api/src/trigger-contracts.ts +++ b/packages/api/src/trigger-contracts.ts @@ -1,18 +1,18 @@ import { z } from "zod"; -import { triggerInputSchema, eventSchema, webhookEventConfigSchema } from "./flow-schemas"; +import { triggerInputSchema, triggerSourceSchema, webhookEventConfigSchema } from "./trigger-schemas"; -const eventIdentity = { id: z.guid(), triggerId: z.guid(), slug: z.string(), createdAt: z.string(), updatedAt: z.string() }; +const triggerSourceIdentity = { id: z.guid(), triggerId: z.guid(), slug: z.string(), createdAt: z.string(), updatedAt: z.string() }; const webhookResponse = z.discriminatedUnion("provider", [ webhookEventConfigSchema.options[0].extend({ secretConfigured: z.boolean().optional() }).strip(), webhookEventConfigSchema.options[1].extend({ secretConfigured: z.boolean().optional() }).strip(), webhookEventConfigSchema.options[2].extend({ secretConfigured: z.boolean().optional() }).strip(), webhookEventConfigSchema.options[3].extend({ destination: z.string().optional(), secretConfigured: z.boolean().optional() }).strip(), ]); -export const eventResponse = z.discriminatedUnion("kind", [ - eventSchema.options[0].extend(eventIdentity), - eventSchema.options[1].extend(eventIdentity), - eventSchema.options[2].extend({ ...eventIdentity, config: webhookResponse }), +export const triggerSourceResponse = z.discriminatedUnion("kind", [ + triggerSourceSchema.options[0].extend(triggerSourceIdentity), + triggerSourceSchema.options[1].extend(triggerSourceIdentity), + triggerSourceSchema.options[2].extend({ ...triggerSourceIdentity, config: webhookResponse }), ]); -export const triggerResponse = z.object({ id: z.guid(), name: z.string(), description: z.string(), enabled: z.boolean(), eventId: z.guid(), events: z.array(eventResponse), createdAt: z.string(), updatedAt: z.string() }); +export const triggerResponse = z.object({ id: z.guid(), name: z.string(), description: z.string(), enabled: z.boolean(), eventId: z.guid(), events: z.array(triggerSourceResponse), createdAt: z.string(), updatedAt: z.string() }); // Omission preserves last-writer-wins behavior for existing REST/MCP clients. export const triggerUpdateInput = triggerInputSchema.extend({ expectedUpdatedAt: z.iso.datetime().optional() }); diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/trigger-schemas.ts similarity index 93% rename from packages/api/src/flow-schemas.ts rename to packages/api/src/trigger-schemas.ts index 5c4ae96c..0fa37953 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/trigger-schemas.ts @@ -13,12 +13,12 @@ export const webhookEventConfigSchema = z.discriminatedUnion("provider", [ webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), integrationId: z.string().min(1) }).strict(), ]); const eventTemplate = z.string().max(50_000).refine(value => { try { Mustache.parse(value); return true; } catch { return false; } }, "Enter a valid Mustache template.").optional(); -export const eventSchema = z.discriminatedUnion("kind", [ +export const triggerSourceSchema = z.discriminatedUnion("kind", [ z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).optional(), kind: z.literal("manual"), template: eventTemplate, enabled: z.boolean().default(true), config: z.object({}).strict().default({}) }).strict(), z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).optional(), kind: z.literal("schedule"), template: eventTemplate, enabled: z.boolean().default(true), config: z.object({ cron: z.string().trim().min(1), timezone: z.string().trim().min(1) }).strict() }).strict(), z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).optional(), kind: z.literal("webhook"), template: eventTemplate, enabled: z.boolean().default(true), config: webhookEventConfigSchema }).strict(), ]); -export const triggerInputSchema = z.object({ name: resourceName, eventId: z.guid(), events: z.array(eventSchema).min(1).max(50).default([{ kind: "manual", slug: "event-1", enabled: true, config: {} }]) }).strict(); +export const triggerInputSchema = z.object({ name: resourceName, eventId: z.guid(), events: z.array(triggerSourceSchema).min(1).max(50).default([{ kind: "manual", slug: "event-1", enabled: true, config: {} }]) }).strict(); export const triggerIdSchema = z.object({ triggerId: z.string().min(1) }); export const fireTriggerInputSchema = z.object({ data: z.record(z.string(), z.unknown()).default({}), idempotencyKey: z.string().trim().min(1).max(200).optional() }).strict(); export const triggerConditionsTestSchema = z.object({ conditions: conditionsSchema.optional(), webhook: preparedWebhookSchema }).strict(); diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index ace80f96..a302012e 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -11,6 +11,7 @@ import { consentDecision } from "./consent-api"; import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceToken, deviceVerification } from "./device-oauth"; import type { Env, OAuthProps } from "./types"; import { AGENT_SCOPES, ACCESS_SCOPES, authenticateAccessToken, normalizeScopes } from "./access-tokens"; +import { effectiveConnectionScopes } from "./oauth-connection-settings"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; import { oidcApiAuth, oidcRequest } from "./oidc-provider"; @@ -110,7 +111,8 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) const props = token?.grant.props; if (!token || token.audience !== env.APP_ORIGIN+"/mcp" || !props || props.userId !== token.userId || token.expiresAt <= Date.now()/1000) return Response.json({error:{code:"invalid_token"}},{status:401}); - const effective = normalizeScopes(token.scope).filter(scope => normalizeScopes(props.scopes).includes(scope)); + const tokenScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(props.scopes).includes(scope)); + const effective = await effectiveConnectionScopes(env, { ...props, authMethod: "oauth", oauthGrantId: token.grantId }, tokenScopes); if (!effective.includes("proxy:use")) return Response.json({error:{code:"insufficient_scope"}},{status:403, headers:{"WWW-Authenticate":'Bearer error="insufficient_scope", scope="proxy:use"'}}); return protectedApiFetch(request,apiEnv,{...props,authMethod:"oauth",scopes:effective,oauthGrantId:token.grantId,oauthClientId:token.grant.clientId,oauthExpiresAt:token.expiresAt},ctx); } diff --git a/packages/api/test/api-contract.test.ts b/packages/api/test/api-contract.test.ts index a251b1c8..1c0d0817 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -8,6 +8,8 @@ describe("Events and Triggers API contract", () => { "GET /api/v1/events", "POST /api/v1/events", "GET /api/v1/events/{eventId}", "PUT /api/v1/events/{eventId}", "DELETE /api/v1/events/{eventId}", "GET /api/v1/events/{eventId}/occurrences", "GET /api/v1/triggers", + "GET /api/v1/permission-presets", "POST /api/v1/permission-presets", + "PUT /api/v1/access/authorizations/{grantId}/permissions", "POST /api/v1/triggers", "POST /api/v1/triggers/{triggerId}/fire", ]) expect(routes).toContain(operation); expect(matchApiOperation("GET", "/api/v1/runs")).toBeUndefined(); diff --git a/packages/api/test/apps.postgres.test.ts b/packages/api/test/apps.postgres.test.ts index 6bade7cc..0983465e 100644 --- a/packages/api/test/apps.postgres.test.ts +++ b/packages/api/test/apps.postgres.test.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { loadingFixture } from "./helpers/loading-fixture"; -import { ApiService } from "../src/flow-service"; +import { ApiService } from "../src/api-service"; import { accessTokenDigest } from "../src/access-tokens"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); diff --git a/packages/api/test/auth-api.test.ts b/packages/api/test/auth-api.test.ts index aa7b2f09..5033b96d 100644 --- a/packages/api/test/auth-api.test.ts +++ b/packages/api/test/auth-api.test.ts @@ -8,7 +8,7 @@ import { safeReturnTo } from "../src/auth-api"; import { signSession } from "../src/session"; import { AuthRepository } from "../src/postgres/auth-repository"; import { IdentityRepository } from "../src/postgres/identity-repository"; -import { ApiService } from "../src/flow-service"; +import { ApiService } from "../src/api-service"; import type { Env, OAuthProps } from "../src/types"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); diff --git a/packages/api/test/event-match-repository.postgres.test.ts b/packages/api/test/event-match-repository.postgres.test.ts index e1ecd1e0..b8300aac 100644 --- a/packages/api/test/event-match-repository.postgres.test.ts +++ b/packages/api/test/event-match-repository.postgres.test.ts @@ -1,12 +1,52 @@ import { describe, expect, it, vi } from "vitest"; import { EventMatchRepository, validAgainstSchema } from "../src/postgres/event-match-repository"; import { loadingFixture } from "./helpers/loading-fixture"; +import { ApiService } from "../src/api-service"; +import { effectiveConnectionScopes } from "../src/oauth-connection-settings"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, WorkflowEntrypoint: class {}, DurableObject: class {} })); vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); const url = process.env.AUTH_TEST_DATABASE_URL; describe.skipIf(!url)("durable Event occurrences", () => { + it("lets owners add and remove standard and integration scopes for a connected client immediately", async () => { + const f = await loadingFixture(url!); + try { + const grantId = "scope-grant"; + const now = Math.floor(Date.now()/1000); + f.env.OAUTH_PROVIDER = { listUserGrants: async () => ({items:[{id:grantId,clientId:"test-client",metadata:{tenantId:f.tenantId},scope:["triggers:read"],createdAt:now,expiresAt:null}]}), lookupClient: async () => ({clientId:"test-client",clientName:"Test client"}) } as any; + const integrationId = crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy,epoch) VALUES($1,$2,'bearer','test-secret','Test integration',true,'requestable',1)",[f.tenantId,integrationId]); + const integrationScope = `integration:${integrationId}:1`; + const service = new ApiService(f.env,f.auth); + await service.updateClientPermissions(grantId,{scopes:["triggers:read","triggers:write","proxy:use",integrationScope],expectedRevision:0}); + const auth = {...f.auth,authMethod:"oauth" as const,oauthGrantId:grantId}; + expect(await effectiveConnectionScopes(f.env,auth,["triggers:read"])).toEqual(["triggers:read","triggers:write","proxy:use",integrationScope]); + await service.updateClientPermissions(grantId,{scopes:["triggers:read"],expectedRevision:1}); + expect(await effectiveConnectionScopes(f.env,auth,["triggers:read","triggers:write","proxy:use",integrationScope])).toEqual(["triggers:read"]); + } finally { await f.cleanup(); } + }); + it("deletes an Event with its Triggers, input sources, match state, and occurrence history", async () => { + const f = await loadingFixture(url!); + try { + const triggerId = f.triggerIds[0]; + const definitionId = (await f.db.pool.query("SELECT event_definition_id FROM app.triggers WHERE tenant_id=$1 AND id=$2", [f.tenantId,triggerId])).rows[0].event_definition_id as string; + const schedule = (await f.db.pool.query("SELECT id FROM app.events WHERE tenant_id=$1 AND trigger_id=$2 AND kind='schedule'", [f.tenantId,triggerId])).rows[0]; + await f.db.pool.query("INSERT INTO app.schedule_state(tenant_id,event_id,trigger_id,next_run_at) VALUES($1,$2,$3,now())", [f.tenantId,schedule.id,triggerId]); + await new EventMatchRepository(f.db).match({tenantId:f.tenantId,triggerId,triggerRevision:1,sourceIdentity:"fixture:delete",deduplicationKey:"delete",evidence:{value:1},decision:"matched"}); + const otherEvent = (await f.db.pool.query("SELECT id FROM app.event_definitions WHERE tenant_id=$1",[f.otherTenant])).rows[0].id; + const service = new ApiService(f.env,f.auth); + await expect(service.deleteEvent(definitionId)).resolves.toEqual({id:definitionId,deleted:true}); + expect((await f.db.pool.query("SELECT count(*)::int AS count FROM app.triggers WHERE tenant_id=$1 AND id=$2",[f.tenantId,triggerId])).rows[0].count).toBe(0); + expect((await f.db.pool.query("SELECT count(*)::int AS count FROM app.events WHERE tenant_id=$1 AND trigger_id=$2",[f.tenantId,triggerId])).rows[0].count).toBe(0); + expect((await f.db.pool.query("SELECT count(*)::int AS count FROM app.schedule_state WHERE tenant_id=$1 AND trigger_id=$2",[f.tenantId,triggerId])).rows[0].count).toBe(0); + expect((await f.db.pool.query("SELECT count(*)::int AS count FROM app.trigger_matches WHERE tenant_id=$1 AND trigger_id=$2",[f.tenantId,triggerId])).rows[0].count).toBe(0); + expect((await f.db.pool.query("SELECT count(*)::int AS count FROM app.event_occurrences WHERE tenant_id=$1 AND definition_id=$2",[f.tenantId,definitionId])).rows[0].count).toBe(0); + expect((await f.db.pool.query("SELECT count(*)::int AS count FROM app.event_definition_revisions WHERE tenant_id=$1 AND definition_id=$2",[f.tenantId,definitionId])).rows[0].count).toBe(0); + expect((await f.db.pool.query("SELECT count(*)::int AS count FROM app.event_definitions WHERE tenant_id=$1 AND id=$2",[f.tenantId,definitionId])).rows[0].count).toBe(0); + expect((await f.db.pool.query("SELECT count(*)::int AS count FROM app.event_definitions WHERE tenant_id=$1 AND id=$2",[f.otherTenant,otherEvent])).rows[0].count).toBe(1); + } finally { await f.cleanup(); } + }); it("validates payloads, supports multiple Triggers per Event, deduplicates deliveries, and scopes reads by tenant", async () => { const f = await loadingFixture(url!); try { diff --git a/packages/api/test/git-https.postgres.test.ts b/packages/api/test/git-https.postgres.test.ts index 9b8eb8f3..af0511c2 100644 --- a/packages/api/test/git-https.postgres.test.ts +++ b/packages/api/test/git-https.postgres.test.ts @@ -8,7 +8,7 @@ import { join } from "node:path"; import { loadingFixture } from "./helpers/loading-fixture"; import { gitHttpsFetch, issueGitCredential, skillCloneInfo } from "../src/git-https"; import { SkillLibrary } from "../src/skill-library"; -import { ApiService } from "../src/flow-service"; +import { ApiService } from "../src/api-service"; import { protectedApiFetch } from "../src/protected-api"; import { installationToken } from "../src/github"; import { GitHubRepository } from "../src/postgres/github-repository"; diff --git a/packages/api/test/oidc.postgres.test.ts b/packages/api/test/oidc.postgres.test.ts index 29af9553..3a302a55 100644 --- a/packages/api/test/oidc.postgres.test.ts +++ b/packages/api/test/oidc.postgres.test.ts @@ -3,7 +3,7 @@ import { Buffer } from "node:buffer"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { loadingFixture } from "./helpers/loading-fixture"; import { accessTokenDigest } from "../src/access-tokens"; -import { ApiService } from "../src/flow-service"; +import { ApiService } from "../src/api-service"; import { signSession } from "../src/session"; import worker from "../src/worker"; diff --git a/packages/api/test/permission-presets.postgres.test.ts b/packages/api/test/permission-presets.postgres.test.ts new file mode 100644 index 00000000..48a00def --- /dev/null +++ b/packages/api/test/permission-presets.postgres.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { ApiService } from "../src/api-service"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, WorkflowEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const url = process.env.AUTH_TEST_DATABASE_URL; +describe.skipIf(!url)("team permission presets", () => { + it("creates, edits, lists, and sets a default scope preset", async () => { + const f = await loadingFixture(url!); + try { + const service = new ApiService(f.env,f.auth); + const created = await service.createPermissionPreset({name:"Read only",scopes:["triggers:read","proxy:use"]}); + expect(created).toMatchObject({name:"Read only",scopes:["triggers:read","proxy:use"],isDefault:false,revision:1}); + await service.setDefaultPermissionPreset(created.id); + const updated = await service.updatePermissionPreset(created.id,{name:"Agent read",scopes:["triggers:read"],expectedRevision:1}); + expect(updated).toMatchObject({name:"Agent read",scopes:["triggers:read"],isDefault:true,revision:2}); + expect(await service.listPermissionPresets()).toEqual([updated]); + } finally { await f.cleanup(); } + }); +}); diff --git a/packages/api/test/protocol-api.postgres.test.ts b/packages/api/test/protocol-api.postgres.test.ts index d44558fd..12e37031 100644 --- a/packages/api/test/protocol-api.postgres.test.ts +++ b/packages/api/test/protocol-api.postgres.test.ts @@ -12,10 +12,12 @@ describe.skipIf(!url)("cookie protocol APIs against PostgreSQL", { timeout: 30_0 const f = await loadingFixture(url!); try { const parsed = { responseType: "code", clientId: "client", redirectUri: "https://external.test/callback", scope: ["team:read", "triggers:read", "integrations:read"], state: "state", codeChallenge: "challenge", codeChallengeMethod: "S256", resource: f.env.APP_ORIGIN + "/mcp", issuer: f.env.APP_ORIGIN }; + await f.db.pool.query("INSERT INTO app.permission_presets(tenant_id,id,name,scopes,is_default) VALUES($1,$2,'Read only',ARRAY['triggers:read'],true)",[f.tenantId,crypto.randomUUID()]); const oauth = { parseAuthRequest: async () => parsed, lookupClient: async () => ({ clientId: "client", clientName: "CLI", redirectUris: [parsed.redirectUri] }), completeAuthorization: vi.fn(async (_input: unknown) => ({ redirectTo: parsed.redirectUri + "?code=issued" })) }; f.env.OAUTH_PROVIDER = oauth as any; const request = (path: string, body: unknown, cookie = f.cookie) => protectedApiFetch(new Request(f.env.APP_ORIGIN + path, { method: "POST", headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify(body) }), f.env, null, {} as ExecutionContext); const previewResponse = await request("/api/v1/oauth/consent/preview", { authorizationQuery: "client_id=client" }); expect(previewResponse.status).toBe(200); const preview = await previewResponse.json() as any; + expect(preview.selectedScopes).toEqual(["triggers:read"]); expect(preview.scopes).toEqual(parsed.scope); const input = { request: preview.request, signature: preview.signature, scopes: ["team:read", "triggers:read", "integrations:read"], decision: "allow" }; expect((await request("/api/v1/oauth/consent/decision", input)).status).toBe(200); expect(oauth.completeAuthorization).toHaveBeenCalledTimes(1); await f.db.pool.query("UPDATE app.members SET session_version=session_version+1 WHERE tenant_id=$1 AND user_id=$2", [f.tenantId, f.userId]); diff --git a/packages/api/test/resource-names.postgres.test.ts b/packages/api/test/resource-names.postgres.test.ts index db152061..946e7e7b 100644 --- a/packages/api/test/resource-names.postgres.test.ts +++ b/packages/api/test/resource-names.postgres.test.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { resourceName } from "../src/resource-names"; -import { triggerInputSchema } from "../src/flow-schemas"; +import { triggerInputSchema } from "../src/trigger-schemas"; import { skillInput } from "../src/skills"; import { loadingFixture } from "./helpers/loading-fixture"; diff --git a/packages/api/test/skill-content-cache.postgres.test.ts b/packages/api/test/skill-content-cache.postgres.test.ts index 284e24dc..251d1c9c 100644 --- a/packages/api/test/skill-content-cache.postgres.test.ts +++ b/packages/api/test/skill-content-cache.postgres.test.ts @@ -4,7 +4,7 @@ import { SkillContent } from "../src/skill-content"; import { PostgresSkillContentCache } from "../src/postgres/skill-content-cache"; import { withSkillGit } from "../src/skill-git"; import { markdown,type Directory } from "../src/skill-files"; -import { ApiService } from "../src/flow-service"; +import { ApiService } from "../src/api-service"; import { decrypt } from "../src/crypto"; vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class extends Error{},getOAuthApi:vi.fn()})); diff --git a/packages/api/test/webhook-conditions.test.ts b/packages/api/test/webhook-conditions.test.ts index 40efdcbe..1fd0c411 100644 --- a/packages/api/test/webhook-conditions.test.ts +++ b/packages/api/test/webhook-conditions.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { readFileSync } from "node:fs"; import { CONDITION_LIMITS, evaluateWebhookConditions, validateConditions } from "../src/webhook-conditions"; -import { webhookEventConfigSchema } from "../src/flow-schemas"; +import { webhookEventConfigSchema } from "../src/trigger-schemas"; const build = JSON.parse(readFileSync(new URL("../migrations/build-manager-conditions.json", import.meta.url), "utf8")); export const leaf = (path: string, operator: string, value: unknown) => ({ fact: "webhook", path, operator, value }); const decision = async (conditions: unknown, webhook: Record) => (await evaluateWebhookConditions(conditions, webhook)).decision; diff --git a/packages/app/src/features/apps/index.tsx b/packages/app/src/features/apps/index.tsx index 6aea0665..8acd5c68 100644 --- a/packages/app/src/features/apps/index.tsx +++ b/packages/app/src/features/apps/index.tsx @@ -2,7 +2,8 @@ import { useState, type FormEvent } from "react"; import { Link, useLocation } from "@tanstack/react-router"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api, type paths } from "factorize-api-client"; -import { Button, Input, Label, Page } from "../../shared/ui"; +import { Button, Input, Label } from "../../shared/ui"; +import { SettingsLayout } from "../settings/navigation"; import { Dialog } from "../../shared/dialog"; import { messageOf } from "../auth/session"; import { tabClasses } from "../auth/team-navigation"; @@ -35,7 +36,7 @@ export function ConnectedAppsPage() { }, onSuccess: () => cache.invalidateQueries({ queryKey: connectedKey }), }); - return

Apps

+ return {connected.isPending &&

Loading connected apps…

} {connected.error &&

{connected.error.message}

} {revoke.error &&

{revoke.error.message}

} @@ -48,7 +49,7 @@ export function ConnectedAppsPage() { }}>Revoke connection )} -
; + ; } function RegistrationEditor({ app, close }: { app: AppRegistration | null; close: () => void }) { @@ -104,7 +105,7 @@ export function RegisteredAppsPage() { }, onSuccess: () => cache.invalidateQueries({ queryKey: registeredKey }), }); - return

Apps

+ return {registered.isPending &&

Loading registered apps…

} {registered.error &&

{registered.error.message}

} @@ -128,5 +129,5 @@ export function RegisteredAppsPage() { } -
; + ; } diff --git a/packages/app/src/features/auth/consent.tsx b/packages/app/src/features/auth/consent.tsx index 118447cf..29885371 100644 --- a/packages/app/src/features/auth/consent.tsx +++ b/packages/app/src/features/auth/consent.tsx @@ -7,7 +7,7 @@ export function ConsentScreen() { const authorizationQuery = location.search.slice(1), [selected, setSelected] = useState(null); const preview = useQuery({ queryKey: ["consent", authorizationQuery], queryFn: async ({ signal }) => { const { data, error } = await api.POST("/api/v1/oauth/consent/preview", { signal, body: { authorizationQuery } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 0, retry: false }); const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { if (!preview.data) throw new Error("Load the authorization request first."); const { data, error } = await api.POST("/api/v1/oauth/consent/decision", { body: { request: preview.data.request, signature: preview.data.signature, decision: value, scopes: selected ?? preview.data.scopes } }); if (!data || error) throw new Error(messageOf(error)); location.assign(data.redirectTo); } }); - const scopes = selected ?? preview.data?.scopes ?? []; + const scopes = selected ?? preview.data?.selectedScopes ?? preview.data?.scopes ?? []; return

Authorize {preview.data?.clientName ?? "a client"}

{preview.isPending &&

Validating authorization request…

}{preview.error &&

{preview.error.message}

} {preview.data && <>

This client requests workspace access. Permissions are independent; write does not imply read. Trigger writes may cause future schedule/webhook/lifecycle execution. Request expires {preview.data.expiresAt}.

Permissions{preview.data.scopes.map(scope => )}
}{decision.error &&

{decision.error.message}

}
; diff --git a/packages/app/src/features/auth/team-navigation.tsx b/packages/app/src/features/auth/team-navigation.tsx index 85e614e8..55c52fb8 100644 --- a/packages/app/src/features/auth/team-navigation.tsx +++ b/packages/app/src/features/auth/team-navigation.tsx @@ -2,5 +2,5 @@ import { Link } from "@tanstack/react-router"; import { NavIcon } from "../../shared/nav-icon"; export const tabClasses=(active:boolean)=>`inline-flex min-h-12 shrink-0 items-center gap-2 border-b-2 px-3 text-base font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-factorize-500 ${active?"border-factorize-500 text-factorize-700 dark:text-factorize-500":"border-transparent text-slate-600 hover:border-stone-300 dark:text-slate-300"}`; export function TeamNavigation({pathname}:{pathname:string}){ - return ; + return ; } diff --git a/packages/app/src/features/events/events.tsx b/packages/app/src/features/events/events.tsx index af11d6c7..24ec9b81 100644 --- a/packages/app/src/features/events/events.tsx +++ b/packages/app/src/features/events/events.tsx @@ -23,6 +23,10 @@ export function EventsPage() { if (!result.data || result.error) throw new Error(result.error?.error?.message ?? "Could not create Event"); return result.data; }, onSuccess: async event => { setName(""); setDescription(""); setSelected(event.id); await client.invalidateQueries({ queryKey: ["events"] }); } }); + const remove = useMutation({ mutationFn: async (eventId: string) => { + const result = await api.DELETE("/api/v1/events/{eventId}", { params: { path: { eventId } } }); + if (result.error) throw new Error(result.error.error?.message ?? "Could not delete Event"); + }, onSuccess: async (_result, eventId) => { if (selected === eventId) setSelected(undefined); await client.invalidateQueries({ queryKey: ["events"] }); } }); return

Event stream

Events

Durable occurrences published by Triggers. Subscribe to an Event’s occurrence resource over MCP.

{ event.preventDefault(); create.mutate(); }}> @@ -30,7 +34,8 @@ export function EventsPage() { {create.error &&

{create.error.message}

}
{events.error &&

{events.error.message}

} -

Defined Events

    {(events.data ?? []).map(item =>
  • )}
{events.data?.length === 0 &&

No Events yet.

}
+ {remove.error &&

{remove.error.message}

} +

Defined Events

    {(events.data ?? []).map(item =>
  • )}
{events.data?.length === 0 &&

No Events yet.

}

Occurrences

{!selected ?

Select an Event to inspect its durable occurrences.

: occurrences.error ?

{occurrences.error.message}

:
    {(occurrences.data?.items ?? []).map(item =>
  1. {JSON.stringify(item.payload, null, 2)}
  2. )}
}
; } diff --git a/packages/app/src/features/settings/client-permissions.tsx b/packages/app/src/features/settings/client-permissions.tsx index 1e65aca7..3200a761 100644 --- a/packages/app/src/features/settings/client-permissions.tsx +++ b/packages/app/src/features/settings/client-permissions.tsx @@ -10,8 +10,8 @@ export function ClientPermissions({ client, close }: { client: AuthorizedClient; const cache = useQueryClient(); const [allowed, setAllowed] = useState(() => client.availableScopes.filter(scope => client.scopes.includes(scope))); const save = useMutation({ retry: false, mutationFn: async () => { - const { error } = await api.PUT("/api/v1/access/authorizations/{grantId}/permissions", { params: { path: { grantId: client.grantId } }, body: { disabledScopes: client.availableScopes.filter(scope => !allowed.includes(scope)), integrationOverrides: client.integrationOverrides, expectedRevision: client.revision } }); + const { error } = await api.PUT("/api/v1/access/authorizations/{grantId}/permissions", { params: { path: { grantId: client.grantId } }, body: { scopes: allowed, expectedRevision: client.revision } }); if (error) throw new Error(messageOf(error)); }, onSuccess: close, onSettled: () => cache.invalidateQueries({ queryKey: clientsQuery.queryKey }) }); - return
Agent API scopes{client.availableScopes.map(scope => )}
{save.error &&

{save.error.message}

}
; + return

Changes take effect as soon as you save.

Agent API scopes{client.availableScopes.map(scope => )}
{save.error &&

{save.error.message}

}
; } diff --git a/packages/app/src/features/settings/integrations.tsx b/packages/app/src/features/settings/integrations.tsx index 8e4e3dc1..56d69e3b 100644 --- a/packages/app/src/features/settings/integrations.tsx +++ b/packages/app/src/features/settings/integrations.tsx @@ -4,7 +4,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { integrationsQuery } from "./queries"; import { installationsQuery } from "./provider-queries"; -import { Page } from "../../shared/ui"; +import { SettingsLayout } from "./navigation"; import { IntegrationForm } from "./integration-form"; import { messageOf } from "../auth/session"; import { useBearerIntegrations } from "./bearer-integrations"; @@ -18,7 +18,7 @@ type Kind = "exe" | "amp" | "cloudflareTail" | "github"; const linkClass = "inline-flex min-h-10 items-center rounded-lg border border-stone-200 px-3 py-2 text-sm font-semibold hover:bg-stone-100 dark:border-slate-700 dark:hover:bg-slate-800"; export function Integrations() { useDisableCredentialAutofill(); - return ; + return ; } function IntegrationsContent() { const cache = useQueryClient(), status = useQuery(integrationsQuery), github = useQuery(installationsQuery); diff --git a/packages/app/src/features/settings/navigation.tsx b/packages/app/src/features/settings/navigation.tsx index f90bfd31..1a9620c2 100644 --- a/packages/app/src/features/settings/navigation.tsx +++ b/packages/app/src/features/settings/navigation.tsx @@ -9,6 +9,9 @@ export function SettingsNavigation() { const cls = "inline-flex items-center gap-2 rounded-lg px-3 py-2 hover:bg-stone-100 dark:hover:bg-slate-800"; const active = { className: "bg-factorize-50 text-factorize-700 dark:bg-factorize-500/10 dark:text-factorize-500" }; return + Permissions + Apps + Integrations Profile API keys Change password diff --git a/packages/app/src/features/settings/permissions.tsx b/packages/app/src/features/settings/permissions.tsx new file mode 100644 index 00000000..af623806 --- /dev/null +++ b/packages/app/src/features/settings/permissions.tsx @@ -0,0 +1,47 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; +import { Button, Input, Label } from "../../shared/ui"; +import { SettingsLayout } from "./navigation"; +import { messageOf } from "../auth/session"; + +const key = ["settings", "permission-presets"]; +const standardScopes = ["team:read","team:write","triggers:read","triggers:write","integrations:read","integrations:write","skills:read","skills:write","proxy:use","apps:manage"]; +type Preset = {id:string;name:string;scopes:string[];isDefault:boolean;revision:number}; +export function Permissions() { + const cache = useQueryClient(); + const presets = useQuery({queryKey:key,queryFn:async({signal})=>{const {data,error}=await api.GET("/api/v1/permission-presets",{signal});if(!data||error)throw new Error(messageOf(error));return data as Preset[];}}); + const integrations = useQuery({queryKey:["settings","api-policies"],queryFn:async({signal})=>{const {data,error}=await api.GET("/api/v1/integration-api-policies",{signal});if(!data||error)throw new Error(messageOf(error));return data.integrations;}}); + const [editing,setEditing]=useState(null),[name,setName]=useState(""),[scopes,setScopes]=useState([]),[error,setError]=useState(""),[formOpen,setFormOpen]=useState(false); + const refresh=()=>cache.invalidateQueries({queryKey:key}); + const save=useMutation({retry:false,mutationFn:async()=>{ + const body={name:name.trim(),scopes}; + const result=editing?await api.PUT("/api/v1/permission-presets/{presetId}",{params:{path:{presetId:editing.id}},body:{...body,expectedRevision:editing.revision}}):await api.POST("/api/v1/permission-presets",{body}); + if(result.error)throw new Error(messageOf(result.error)); + },onSuccess:async()=>{setEditing(null);setName("");setScopes([]);setError("");setFormOpen(false);await refresh();},onError:e=>setError(e.message)}); + const action=useMutation({retry:false,mutationFn:async({preset,kind}:{preset:Preset;kind:"default"|"delete"})=>{ + const result=kind==="default"?await api.POST("/api/v1/permission-presets/{presetId}/default",{params:{path:{presetId:preset.id}}}):await api.DELETE("/api/v1/permission-presets/{presetId}",{params:{path:{presetId:preset.id}}}); + if(result.error)throw new Error(messageOf(result.error)); + },onSuccess:refresh,onError:e=>setError(e.message)}); + const toggle=(scope:string)=>setScopes(current=>current.includes(scope)?current.filter(value=>value!==scope):[...current,scope]); + const begin=(preset?:Preset)=>{setEditing(preset??null);setName(preset?.name??"");setScopes(preset?.scopes??[]);setError("");setFormOpen(true);}; + const scopeOptions=[...standardScopes,...(integrations.data??[]).filter(row=>row.available&&row.policy!=="disabled").map(row=>row.requiredScope)]; + const labels=new Map((integrations.data??[]).map(row=>[row.requiredScope,`${row.name} integration access`])); + return +

Create scope presets for new client connections. The default preset preselects scopes during authorization. Existing client permissions remain individually editable.

+ {(presets.error||integrations.error||error)&&

{error||(presets.error??integrations.error)?.message}

} + {presets.isPending&&

Loading permission presets…

} + {!!presets.data?.length&&
    {presets.data.map(preset=>
  • +
    {preset.name}{preset.isDefault&&Default}

    {preset.scopes.map(scope=>labels.get(scope)??scope).join(", ")||"No scopes"}

    +
    +
  • )}
} + {!presets.isPending&&!presets.data?.length&&

No permission presets yet.

} + {formOpen?
{event.preventDefault();save.mutate();}}> +

{editing?`Edit ${editing.name}`:"New permission preset"}

+ +
Scopes{scopeOptions.map(scope=>)}
+ {save.isPending&&

Saving preset…

} +
+
:} +
; +} diff --git a/packages/app/src/features/settings/routes.tsx b/packages/app/src/features/settings/routes.tsx index 0e737eac..3f2dde94 100644 --- a/packages/app/src/features/settings/routes.tsx +++ b/packages/app/src/features/settings/routes.tsx @@ -7,11 +7,13 @@ export function settingsRoutes(root: AnyRootRoute) { return [ createRoute({getParentRoute:()=>root,path:"/uploads/proxy/$handle",beforeLoad:guard,component:lazyRouteComponent(()=>import("./proxy-upload"),"ProxyUpload")}), createRoute({ getParentRoute: () => root, path: "/settings/profile", beforeLoad: guard, component: lazyRouteComponent(() => import("./profile"), "Profile") }), + createRoute({ getParentRoute: () => root, path: "/settings/permissions", beforeLoad: guard, component: lazyRouteComponent(() => import("./permissions"), "Permissions") }), + createRoute({ getParentRoute: () => root, path: "/settings/apps", beforeLoad: ({ location }) => { throw redirect({ to: "/apps", search: location.search, hash: location.hash, replace: true }); } }), createRoute({ getParentRoute: () => root, path: "/settings/integrations", beforeLoad: ({ location }) => { throw redirect({ to: "/integrations", search: location.search, hash: location.hash, replace: true }); } }), createRoute({ getParentRoute: () => root, path: "/integrations", beforeLoad: guard, component: lazyRouteComponent(() => import("./integrations"), "Integrations") }), createRoute({ getParentRoute: () => root, path: "/clients", beforeLoad: guard, component: lazyRouteComponent(() => import("./authorized-clients"), "ClientsPage") }), createRoute({ getParentRoute: () => root, path: "/clients/$grantId", beforeLoad: guard, component: lazyRouteComponent(() => import("./authorized-clients"), "ClientPage") }), - createRoute({ getParentRoute: () => root, path: "/settings", beforeLoad: async context => { await guard(context); throw redirect({to:"/integrations",replace:true}); } }), + createRoute({ getParentRoute: () => root, path: "/settings", beforeLoad: async context => { await guard(context); throw redirect({to:"/settings/permissions",replace:true}); } }), createRoute({ getParentRoute: () => root, path: "/settings/api-keys", beforeLoad: guard, component: lazyRouteComponent(() => import("./api-keys"), "ApiKeys") }), createRoute({ getParentRoute: () => root, path: "/settings/api-keys/new", beforeLoad: guard, component: lazyRouteComponent(() => import("./api-key-create"), "ApiKeyCreate") }), createRoute({ getParentRoute: () => root, path: "/settings/authorized-clients", beforeLoad: () => { throw redirect({ to: "/clients", replace: true }); } }), diff --git a/packages/app/test/auth.browser.test.mjs b/packages/app/test/auth.browser.test.mjs index 9e88c40b..b2b6ea11 100644 --- a/packages/app/test/auth.browser.test.mjs +++ b/packages/app/test/auth.browser.test.mjs @@ -130,7 +130,7 @@ test("authenticated password route shows settings navigation with the active pas } })); await page.goto(origin + "/settings/password"); const settings = page.getByRole("navigation", { name: "Settings" }); - assert.equal(await settings.getByRole("link", { name: "Integrations", exact: true }).count(), 0); + assert.equal(await settings.getByRole("link", { name: "Integrations", exact: true }).count(), 1); assert.equal(await settings.getByRole("link", { name: "Skills library", exact: true }).count(), 0); const dashboard = page.getByRole("navigation", { name: "Dashboard navigation" }); assert.equal(await dashboard.count(), 1); @@ -143,6 +143,28 @@ test("authenticated password route shows settings navigation with the active pas await context.close(); }); +test("Settings navigation opens permission presets and Apps from the sidebar", async () => { + const context = await browser.newContext({ viewport: { width: 1280, height: 900 } }); + const page = await context.newPage(); + await page.route("**/api/v1/session", route => route.fulfill({ json: { + authenticated: true, user: { id: "owner-a", email: "owner@example.test" }, + team: { id: "workspace-a", name: "Workspace", role: "owner" }, capabilities: [], + } })); + await page.route("**/api/v1/permission-presets", route => route.fulfill({ json: [] })); + await page.route("**/api/v1/integration-api-policies", route => route.fulfill({ json: { integrations: [] } })); + await page.route("**/api/v1/app-connections", route => route.fulfill({ json: [] })); + await page.goto(origin + "/settings"); + await page.getByRole("heading", { name: "Permissions", exact: true }).waitFor(); + assert.equal(new URL(page.url()).pathname, "/settings/permissions"); + const settings = page.getByRole("navigation", { name: "Settings" }); + await settings.getByRole("link", { name: "Apps", exact: true }).click(); + await page.getByText("No connected apps.").waitFor(); + assert.equal(new URL(page.url()).pathname, "/apps"); + await settings.getByRole("link", { name: "Permissions", exact: true }).click(); + await page.getByRole("heading", { name: "Permissions", exact: true }).waitFor(); + await context.close(); +}); + test("authenticated password change is isolated from global auth navigation and reports invalidation", async () => { const context = await browser.newContext(); const page = await context.newPage(); diff --git a/packages/docs/api/authentication.mdx b/packages/docs/api/authentication.mdx index f187d057..b0bd72d6 100644 --- a/packages/docs/api/authentication.mdx +++ b/packages/docs/api/authentication.mdx @@ -26,6 +26,10 @@ Scopes are independent; write does not imply read. Integration-specific scopes are granted separately. Owner-only operations require an interactive browser session. +Owners can edit the effective scopes of an existing MCP connection in Settings; +saved scope additions and removals apply immediately. Team permission presets +can preselect scopes during new client authorization. + ## OAuth clients Authorization-code clients must use PKCE S256. Implicit and plain PKCE are diff --git a/packages/docs/api/openapi.mdx b/packages/docs/api/openapi.mdx index db06b5e4..03135c0a 100644 --- a/packages/docs/api/openapi.mdx +++ b/packages/docs/api/openapi.mdx @@ -11,6 +11,6 @@ The definition is generated from the executable route catalog in `packages/api/s npm run generate:openapi ``` -Commit `packages/docs/openapi.yaml` with the change. CI regenerates it and rejects a diff; parsed contract tests also require exact method/path equality with the executable catalog. Shared schemas and general API metadata live beside the catalog in `flow-schemas.ts`, `trace-replay-schemas.ts`, and `api-document.json`. +Commit `packages/docs/openapi.yaml` with the change. CI regenerates it and rejects a diff; parsed contract tests also require exact method/path equality with the executable catalog. Shared schemas and general API metadata live beside the catalog in `trigger-schemas.ts`, `trace-replay-schemas.ts`, and `api-document.json`. Run `npm run validate --workspace=factorize-docs` to verify the generated artifact, parsed operation contract, and Mintlify configuration before publishing. diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index ab1df1b1..442f9bf5 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -69,6 +69,9 @@ subscription support. After a resource-updated notification, read the resource to retrieve durable data. `list_event_occurrences` lets a reconnecting client recover stored records. +`delete_event` permanently removes the Event, all attached Triggers and input +configurations, and all stored occurrences. + ## Triggers A Trigger belongs to one Event and watches a schedule, signed webhook/provider diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 2be15486..bcfbf73b 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -2475,6 +2475,10 @@ paths: type: array items: type: string + selectedScopes: + type: array + items: + type: string request: type: string signature: @@ -2502,6 +2506,7 @@ paths: required: - clientName - scopes + - selectedScopes - request - signature - expiresAt @@ -3975,18 +3980,15 @@ paths: type: array items: type: string - enum: - - team:read - - team:write - - triggers:read - - triggers:write - - integrations:read - - integrations:write - - skills:read - - skills:write - - proxy:use - - apps:manage + scopeLabels: + default: {} + type: object + propertyNames: + type: string + additionalProperties: + type: string integrationOverrides: + default: {} type: object propertyNames: type: string @@ -3997,7 +3999,6 @@ paths: - type: string - type: boolean const: false - description: Integration ID to approved epoch-bound scope, or false to block. revision: type: integer minimum: -9007199254740991 @@ -4026,6 +4027,7 @@ paths: - "null" required: - availableScopes + - scopeLabels - integrationOverrides - revision - grantId @@ -4300,7 +4302,13 @@ paths: minLength: 1 /api/v1/access/authorizations/{grantId}/permissions: put: - summary: Edit an OAuth connection’s scopes and integration access + summary: Set an OAuth connection’s effective scopes and integration access + description: |- + Interactive owner session required. Saving updates the connection immediately and can add scopes beyond the original OAuth request. + + Requires the triggers:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. responses: "200": description: Permissions saved @@ -4332,10 +4340,6 @@ paths: $ref: "#/components/responses/Error500" "503": $ref: "#/components/responses/Error503" - description: |- - Requires the triggers:write scope. - - An interactive owner session is required; bearer tokens cannot call this operation. operationId: put_api_v1_access_authorizations_grantId_permissions tags: - access @@ -4357,6 +4361,12 @@ paths: schema: type: object properties: + scopes: + description: Complete owner-selected effective scope set for this connection. + maxItems: 100 + type: array + items: + type: string disabledScopes: maxItems: 10 type: array @@ -4374,6 +4384,7 @@ paths: - proxy:use - apps:manage integrationOverrides: + description: Integration ID to approved epoch-bound scope, or false to block. type: object propertyNames: type: string @@ -4384,15 +4395,369 @@ paths: - type: string - type: boolean const: false - description: Integration ID to approved epoch-bound scope, or false to block. expectedRevision: type: integer minimum: 0 maximum: 9007199254740991 + additionalProperties: false + /api/v1/permission-presets: + get: + summary: List team permission presets + responses: + "200": + description: Permission presets + content: + application/json: + schema: + type: array + items: + type: object + properties: + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + name: + type: string + scopes: + type: array + items: + type: string + isDefault: + type: boolean + revision: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + createdAt: + type: string + updatedAt: + type: string + required: + - id + - name + - scopes + - isDefault + - revision + - createdAt + - updatedAt + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the team:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: get_api_v1_permission_presets + tags: + - permission-presets + security: + - cookieAuth: [] + x-required-scope: team:read + x-owner-session-required: true + post: + summary: Create a team permission preset + responses: + "201": + description: Created + content: + application/json: + schema: + type: object + properties: + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + name: + type: string + scopes: + type: array + items: + type: string + isDefault: + type: boolean + revision: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + createdAt: + type: string + updatedAt: + type: string + required: + - id + - name + - scopes + - isDefault + - revision + - createdAt + - updatedAt + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the team:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: post_api_v1_permission_presets + tags: + - permission-presets + security: + - cookieAuth: [] + x-required-scope: team:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 100 + scopes: + maxItems: 100 + type: array + items: + type: string + expectedRevision: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 required: - - disabledScopes - - integrationOverrides + - name + - scopes additionalProperties: false + /api/v1/permission-presets/{presetId}: + put: + summary: Update a team permission preset + responses: + "200": + description: Updated + content: + application/json: + schema: + type: object + properties: + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + name: + type: string + scopes: + type: array + items: + type: string + isDefault: + type: boolean + revision: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + createdAt: + type: string + updatedAt: + type: string + required: + - id + - name + - scopes + - isDefault + - revision + - createdAt + - updatedAt + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the team:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: put_api_v1_permission_presets_presetId + tags: + - permission-presets + security: + - cookieAuth: [] + x-required-scope: team:write + x-owner-session-required: true + parameters: + - name: presetId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 100 + scopes: + maxItems: 100 + type: array + items: + type: string + expectedRevision: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + required: + - name + - scopes + - expectedRevision + additionalProperties: false + delete: + summary: Delete a team permission preset + responses: + "200": + description: Deleted + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the team:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: delete_api_v1_permission_presets_presetId + tags: + - permission-presets + security: + - cookieAuth: [] + x-required-scope: team:write + x-owner-session-required: true + parameters: + - name: presetId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + /api/v1/permission-presets/{presetId}/default: + post: + summary: Set the team default permission preset + responses: + "200": + description: Default updated + content: + application/json: + schema: + type: object + properties: + ok: + type: boolean + required: + - ok + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the team:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: post_api_v1_permission_presets_presetId_default + tags: + - permission-presets + security: + - cookieAuth: [] + x-required-scope: team:write + x-owner-session-required: true + parameters: + - name: presetId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ /api/v1/access/authorizations/{grantId}: delete: summary: Revoke one isolated OAuth connection @@ -6466,7 +6831,13 @@ paths: - expectedRevision additionalProperties: false delete: - summary: Delete an Event with no Triggers + 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. + + Requires the triggers:write scope. + + Accepts a scoped bearer token or interactive owner session. responses: "200": description: Deleted @@ -6490,10 +6861,6 @@ paths: $ref: "#/components/responses/Error500" "503": $ref: "#/components/responses/Error503" - description: |- - Requires the triggers:write scope. - - Accepts a scoped bearer token or interactive owner session. operationId: delete_api_v1_events_eventId tags: - events diff --git a/scripts/bootstrap-test.mjs b/scripts/bootstrap-test.mjs index 965fd427..11c0bc68 100644 --- a/scripts/bootstrap-test.mjs +++ b/scripts/bootstrap-test.mjs @@ -4,7 +4,7 @@ import process from "node:process"; const exec = promisify(execFile); const runTests = process.argv.includes("--test"); -const expectedNode = "v24.12.0"; +const expectedNode = "v24.21.0"; const expectedNpm = "11.19.0"; const databaseUrl = process.env.VALIDATION_DATABASE_URL ?? "postgresql://postgres:local-validation-only@localhost:5432/factorize_validation"; const adminUrl = process.env.VALIDATION_DATABASE_ADMIN_URL ?? "postgresql://postgres:local-validation-only@localhost:5432/postgres"; diff --git a/scripts/smoke-validation-runner-image.sh b/scripts/smoke-validation-runner-image.sh index 940e86e4..85cbdc7f 100644 --- a/scripts/smoke-validation-runner-image.sh +++ b/scripts/smoke-validation-runner-image.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -expected_node=24.12.0 +expected_node=24.21.0 expected_npm=11.19.0 expected_playwright=1.64.0 diff --git a/scripts/validation.mjs b/scripts/validation.mjs index 64ffd061..fc381d99 100644 --- a/scripts/validation.mjs +++ b/scripts/validation.mjs @@ -3,7 +3,7 @@ import process from "node:process"; import { runProcess } from "./portable-proxy-test-helpers.mjs"; const lane = process.argv[2] ?? "all"; -const expectedNode = "24.12.0"; +const expectedNode = "24.21.0"; const suiteTimeoutMs = 1_000_000; const lanes = { backend: [ diff --git a/skills/manage-triggers/SKILL.md b/skills/manage-triggers/SKILL.md index 3df093bd..f350ee86 100644 --- a/skills/manage-triggers/SKILL.md +++ b/skills/manage-triggers/SKILL.md @@ -8,7 +8,7 @@ Call `get_api_reflection` to inspect current identity and permissions. Events an ## Events -Use `list_events` and `get_event` to inspect Events and their payload schema revisions. Create an Event with `create_event`, including a lowercase stable `name`, optional description, and JSON Schema object in `payloadSchema`. Use `update_event` with the current `expectedRevision` to add a schema revision. Existing occurrences keep their original revision. Delete Events only after removing their Triggers. +Use `list_events` and `get_event` to inspect Events and their payload schema revisions. Create an Event with `create_event`, including a lowercase stable `name`, optional description, and JSON Schema object in `payloadSchema`. Use `update_event` with the current `expectedRevision` to add a schema revision. Existing occurrences keep their original revision. `delete_event` permanently deletes the Event, all attached Triggers and input configurations, and all occurrence history. MCP subscribers read `factorize://events/{eventId}/occurrences`. Subscribe through `subscriptions/listen`; on resource update, read the occurrence resource. Occurrences are durable, so reconnecting clients can read missed records. Use `list_event_occurrences` to page through stored occurrences.