diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 7eed5ed2..52527949 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -297,7 +297,7 @@ export interface paths { }; /** * Get template autocomplete metadata - * @description Requires the flows:read scope. + * @description Requires the jobs:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -319,7 +319,7 @@ export interface paths { }; /** * List exe connections - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -341,7 +341,7 @@ export interface paths { }; /** * List GitHub installations - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -363,7 +363,7 @@ export interface paths { }; /** * List execution targets - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -371,7 +371,7 @@ export interface paths { put?: never; /** * Create execution target - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -392,7 +392,7 @@ export interface paths { get?: never; /** * Update execution target - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -400,7 +400,7 @@ export interface paths { post?: never; /** * Delete execution target - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -421,7 +421,7 @@ export interface paths { put?: never; /** * Diagnose an execution target - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -441,7 +441,7 @@ export interface paths { }; /** * List available trigger kinds - * @description Requires the flows:read scope. + * @description Requires the jobs:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -465,7 +465,7 @@ export interface paths { put?: never; /** * Preview schedule - * @description Requires the flows:read scope. + * @description Requires the jobs:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -485,7 +485,7 @@ export interface paths { }; /** * List Tail integrations - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -493,7 +493,7 @@ export interface paths { put?: never; /** * Create a Tail integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -513,7 +513,7 @@ export interface paths { }; /** * List installed integrations - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -536,7 +536,7 @@ export interface paths { get?: never; /** * Create an exe.dev integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -559,7 +559,7 @@ export interface paths { put?: never; /** * Test exe.dev credentials - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -580,7 +580,7 @@ export interface paths { get?: never; /** * Create an Amp integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -603,7 +603,7 @@ export interface paths { put?: never; /** * Test Amp credentials - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -623,7 +623,7 @@ export interface paths { }; /** * List Linear projects - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -645,7 +645,7 @@ export interface paths { }; /** * List Linear trigger options - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -667,7 +667,7 @@ export interface paths { }; /** * List ClickUp lists - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -689,7 +689,7 @@ export interface paths { }; /** * List ClickUp trigger options - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -711,7 +711,7 @@ export interface paths { }; /** * List GitHub installations for provider setup - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -733,7 +733,7 @@ export interface paths { }; /** * List authorized OAuth clients - * @description Requires the flows:read scope. + * @description Requires the jobs:read scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ @@ -755,7 +755,7 @@ export interface paths { }; /** * List access tokens - * @description Requires the flows:read scope. + * @description Requires the jobs:read scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ @@ -763,7 +763,7 @@ export interface paths { put?: never; /** * Create an access token - * @description Requires the flows:write scope. + * @description Requires the jobs:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ @@ -786,7 +786,7 @@ export interface paths { post?: never; /** * Revoke an access token - * @description Requires the flows:write scope. + * @description Requires the jobs:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ @@ -808,7 +808,7 @@ export interface paths { post?: never; /** * Revoke an authorized OAuth client - * @description Requires the flows:write scope. + * @description Requires the jobs:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ @@ -830,7 +830,7 @@ export interface paths { post?: never; /** * Remove an exe.dev integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -852,7 +852,7 @@ export interface paths { post?: never; /** * Remove an Amp integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -872,7 +872,7 @@ export interface paths { get?: never; /** * Update a Tail integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -880,7 +880,7 @@ export interface paths { post?: never; /** * Remove a Tail integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -901,7 +901,7 @@ export interface paths { put?: never; /** * Test a Tail integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -921,7 +921,7 @@ export interface paths { }; /** * List installation repositories - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -943,7 +943,7 @@ export interface paths { }; /** * List GitHub issue trigger options - * @description Requires the flows:read scope. + * @description Requires the integrations:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -968,7 +968,7 @@ export interface paths { post?: never; /** * Disconnect a GitHub installation - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -989,7 +989,7 @@ export interface paths { put?: never; /** * Probe exe.dev permissions and a disposable VM's agent/model integration - * @description Requires the flows:write scope. + * @description Requires the integrations:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1011,7 +1011,7 @@ export interface paths { * List bounded job summaries * @description Additive list representation, ordered by immutable UUID descending. Cursor is the last ID; filters must remain the same between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array. * - * Requires the flows:read scope. + * Requires the jobs:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1033,7 +1033,7 @@ export interface paths { }; /** * Search bounded lifecycle job options - * @description Requires the flows:read scope. + * @description Requires the jobs:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1055,7 +1055,7 @@ export interface paths { }; /** * List projects - * @description Requires the flows:read scope. + * @description Requires the projects:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1063,7 +1063,7 @@ export interface paths { put?: never; /** * Create project - * @description Requires the flows:write scope. + * @description Requires the projects:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1083,14 +1083,14 @@ export interface paths { }; /** * Get project - * @description Requires the flows:read scope. + * @description Requires the projects:read scope. * * Accepts a scoped bearer token or interactive owner session. */ get: operations["get_api_v1_projects_projectId"]; /** * Update project - * @description Requires the flows:write scope. + * @description Requires the projects:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1098,7 +1098,7 @@ export interface paths { post?: never; /** * Delete empty project - * @description Requires the flows:write scope. + * @description Requires the projects:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1119,7 +1119,7 @@ export interface paths { put?: never; /** * Move a job to a project - * @description Requires the flows:write scope. + * @description Requires the projects:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1139,7 +1139,7 @@ export interface paths { }; /** * List jobs - * @description Requires the flows:read scope. + * @description Requires the jobs:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1147,7 +1147,7 @@ export interface paths { put?: never; /** * Create job - * @description Requires the flows:write scope. + * @description Requires the jobs:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1171,7 +1171,7 @@ export interface paths { * Test webhook conditions * @description Evaluates supplied prepared webhook context only; does not authenticate the example, route events, verify GitHub state, or invoke jobs. * - * Requires the flows:write scope. + * Requires the jobs:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1193,7 +1193,7 @@ export interface paths { put?: never; /** * Invoke job - * @description Requires the runs:write scope. + * @description Requires the runs:invoke scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1237,7 +1237,7 @@ export interface paths { put?: never; /** * Enable job - * @description Requires the flows:write scope. + * @description Requires the jobs:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1259,7 +1259,7 @@ export interface paths { put?: never; /** * Disable job - * @description Requires the flows:write scope. + * @description Requires the jobs:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1279,7 +1279,7 @@ export interface paths { }; /** * Get job - * @description Requires the flows:read scope. + * @description Requires the jobs:read scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1288,7 +1288,7 @@ export interface paths { * Replace job * @description Supply expectedUpdatedAt from GET for atomic optimistic concurrency. Stale edits return 409 stale_job. Omission preserves legacy REST/MCP last-writer-wins updates. Trigger identity is preserved. * - * Requires the flows:write scope. + * Requires the jobs:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1296,7 +1296,7 @@ export interface paths { post?: never; /** * Delete job - * @description Requires the flows:write scope. + * @description Requires the jobs:write scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1341,7 +1341,7 @@ export interface paths { * Search jobs and runs by approximate metadata matches * @description Search uses PostgreSQL pg_trgm approximate matching over job names/slugs and run names, issue titles, and issue identifiers. Identifier matching is whole-field trigram matching; names and titles use word-level trigram matching. Exact identifiers and metadata names rank first, followed by the strongest individual field score. Results are unique, tenant-scoped, deterministically ordered, and limited to 100. Blank or punctuation-only queries return no results. One- and two-character queries may return no results because trigram matching is approximate; this is not ordered-character or substring matching. * - * Requires the runs:read scope. + * Requires the jobs:read and runs:read scopes. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1501,9 +1501,9 @@ export interface paths { put?: never; /** * Replay a retained trace artifact or restore a native-session projection - * @description Requires runs:write and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run. + * @description Requires runs:cancel and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run. * - * Requires the runs:write scope. + * Requires the runs:cancel scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ @@ -1547,7 +1547,7 @@ export interface paths { put?: never; /** * Stop run - * @description Requires the runs:write scope. + * @description Requires the runs:cancel scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -1569,7 +1569,7 @@ export interface paths { put?: never; /** * Kill run and immediately release its concurrency slot - * @description Requires the runs:write scope. + * @description Requires the runs:cancel scope. * * Accepts a scoped bearer token or interactive owner session. */ @@ -2205,7 +2205,7 @@ export interface operations { /** @constant */ role: "owner"; }; - capabilities: ("flows:read" | "flows:write" | "runs:read" | "runs:write")[]; + capabilities: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write")[]; /** Format: date-time */ expiresAt: string; }; @@ -2717,7 +2717,7 @@ export interface operations { signature: string; /** @enum {string} */ decision: "allow" | "deny"; - scopes: ("flows:read" | "flows:write" | "runs:read" | "runs:write")[]; + scopes: string[]; }; }; }; @@ -3731,7 +3731,7 @@ export interface operations { "application/json": { id: string; name: string; - scopes: ("flows:read" | "flows:write" | "runs:read" | "runs:write")[]; + scopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write")[]; created_at: string; expires_at: string; last_used_at?: string | null; @@ -3760,7 +3760,7 @@ export interface operations { content: { "application/json": { name: string; - scopes: ("flows:read" | "flows:write" | "runs:read" | "runs:write")[]; + scopes: (("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write") | ("flows:read" | "flows:write" | "runs:write"))[]; expiryDays: 7 | 30 | 90; }; }; @@ -3775,7 +3775,7 @@ export interface operations { "application/json": { id: string; name: string; - scopes: ("flows:read" | "flows:write" | "runs:read" | "runs:write")[]; + scopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write")[]; created_at: string; expires_at: string; last_used_at?: string | null; @@ -5967,7 +5967,7 @@ export interface operations { 400: components["responses"]["Error400"]; /** @description Invalid owner session */ 401: components["responses"]["Error401"]; - /** @description Missing runs:write scope or interactive owner session */ + /** @description Missing runs:cancel scope or interactive owner session */ 403: components["responses"]["Error403"]; /** @description Run not found within the tenant */ 404: components["responses"]["Error404"]; diff --git a/packages/api/src/access-tokens.ts b/packages/api/src/access-tokens.ts index 94f5117c..f9c04afa 100644 --- a/packages/api/src/access-tokens.ts +++ b/packages/api/src/access-tokens.ts @@ -2,8 +2,21 @@ import type { Env, OAuthProps } from "./types"; import { databaseFor } from "./postgres/database"; import { AccessTokenRepository } from "./postgres/access-token-repository"; -export const ACCESS_SCOPES = ["flows:read", "flows:write", "runs:read", "runs:write"] as const; +export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"] as const; export type AccessScope = typeof ACCESS_SCOPES[number]; +export type LegacyScope = "flows:read" | "flows:write" | "runs:write"; + +/** Legacy grants are accepted only at authentication time. New issuance never emits them. */ +export function normalizeScopes(scopes: readonly string[]): string[] { + const result = new Set(); + for (const scope of scopes) { + if (scope === "flows:read") ["projects:read", "jobs:read", "integrations:read"].forEach(value => result.add(value)); + else if (scope === "flows:write") ["projects:write", "jobs:write", "integrations:write"].forEach(value => result.add(value)); + else if (scope === "runs:write") ["runs:read", "runs:invoke", "runs:cancel"].forEach(value => result.add(value)); + else if (ACCESS_SCOPES.includes(scope as AccessScope)) result.add(scope); + } + return [...result]; +} const encoder = new TextEncoder(); const base64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); @@ -33,5 +46,5 @@ export async function authenticateAccessToken(request: Request, env: Env): Promi const token = authorization.slice(7), tenantId = accessTokenTenant(token); if (!tenantId) return null; const auth = await new AccessTokenRepository(databaseFor(env), tenantId).authenticate(await accessTokenDigest(token)); - return auth ? { ...auth, authMethod: "access_token" } : null; + return auth ? { ...auth, scopes: normalizeScopes(auth.scopes), authMethod: "access_token" } : null; } diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 3723ac78..d14044ae 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -23,7 +23,7 @@ type JsonSchema = Record; export interface RouteContract { method: string; path: string; - scope: z.infer; + scope: string | string[]; ownerSession: boolean; authOperation?: AuthAction; body?: z.ZodType; @@ -104,14 +104,16 @@ const scheduleBody = z .strict(); const accessTokenBody = z.object({ name: z.string().trim().min(1).max(100), - scopes: z.array(scopeSchema).min(1), + // Legacy names remain accepted at this boundary for migration; the service + // immediately stores their canonical resource-scope expansion. + scopes: z.array(z.union([scopeSchema, z.enum(["flows:read", "flows:write", "runs:write"])] )).min(1), expiryDays: z.union([z.literal(7), z.literal(30), z.literal(90)]), }); function route( method: string, path: string, - scope: RouteContract["scope"], + scope: string, documentation: RouteContract["documentation"], execute: RouteContract["execute"], options: Partial< @@ -132,10 +134,11 @@ function route( const status = Number( Object.keys(documentation.responses).find((code) => code.startsWith("2")), ); + const requiredScope = scopeForRoute(path, scope); return { method, path, - scope, + scope: requiredScope, parameters, status, ownerSession: false, @@ -145,6 +148,25 @@ function route( }; } +// Keep the catalog readable while making the authorization boundary explicit. +// Legacy route labels are translated by resource and effect; they are never +// accepted as newly issued scopes. +function scopeForRoute(path: string, legacy: string): string | string[] { + if (legacy === "runs:read" && path === "/api/v1/search") return "jobs:read+runs:read"; + if (legacy === "flows:read") { + if (path.startsWith("/api/v1/projects") || path.includes("/jobs/") && path.endsWith("/project")) return "projects:read"; + if (path.includes("/integrations") || path.includes("/providers") || path.includes("execution-target") || path.includes("exe-connections") || path.includes("github-installations")) return "integrations:read"; + return "jobs:read"; + } + if (legacy === "flows:write") { + if (path.startsWith("/api/v1/projects") || path.includes("/jobs/") && path.endsWith("/project")) return "projects:write"; + if (path.includes("/integrations") || path.includes("/providers") || path.includes("execution-target") || path.includes("exe-connections") || path.includes("github-installations")) return "integrations:write"; + return "jobs:write"; + } + if (legacy === "runs:write") return path.includes("invocation") ? "runs:invoke" : "runs:cancel"; + return legacy; +} + /** The executable API catalog: change an operation here, then run generate:openapi. * Service methods retain tenant/identity authorization for both REST and MCP. */ @@ -912,7 +934,7 @@ export const API_ROUTES: RouteContract[] = [ summary: "Replay a retained trace artifact or restore a native-session projection", description: - "Requires runs:write and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run.", + "Requires runs:cancel and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run.", responses: { "200": { description: "Durable replay result", @@ -925,7 +947,7 @@ export const API_ROUTES: RouteContract[] = [ "400": { description: "Invalid request" }, "401": { description: "Invalid owner session" }, "403": { - description: "Missing runs:write scope or interactive owner session", + description: "Missing runs:cancel scope or interactive owner session", }, "404": { description: "Run not found within the tenant" }, "409": { @@ -1120,7 +1142,7 @@ export function generateOpenApi() { ...route.documentation, description: [ route.documentation.description, - route.authOperation ? undefined : `Requires the ${route.scope} scope.`, + route.authOperation ? undefined : `Requires the ${Array.isArray(route.scope) ? route.scope.join(" and ") : route.scope.replaceAll("+", " and ")} scope${Array.isArray(route.scope) || route.scope.includes("+") ? "s" : ""}.`, route.authOperation ? undefined : route.ownerSession ? "An interactive owner session is required; bearer tokens cannot call this operation." : "Accepts a scoped bearer token or interactive owner session.", diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index 5940fc11..c2ed82c3 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -9,7 +9,7 @@ import { databaseFor } from "./postgres/database"; import { readSession, requestCookie, signSession, type Session } from "./session"; import type { Env } from "./types"; -export const SESSION_SCOPES = ["flows:read", "flows:write", "runs:read", "runs:write"] as const; +export const SESSION_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"] as const; const email = z.string().trim().toLowerCase().email().max(320); const password = z.string().min(12).max(200).meta({ writeOnly: true }); const connection = z.uuid().optional(); diff --git a/packages/api/src/consent-api.ts b/packages/api/src/consent-api.ts index 75662477..6d7eacac 100644 --- a/packages/api/src/consent-api.ts +++ b/packages/api/src/consent-api.ts @@ -5,11 +5,12 @@ import type { AuthRequest } from "@cloudflare/workers-oauth-provider"; import { hmac } from "./crypto"; import type { Env, OAuthProps } from "./types"; import type { Session } from "./session"; +import { ACCESS_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.enum(["flows:read", "flows:write", "runs:read", "runs:write"])) }).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() }); export const consentDecisionResponse = z.object({ redirectTo: z.string() }); -const supported = ["flows:read", "flows:write", "runs:read", "runs:write"]; +const supported = [...ACCESS_SCOPES, "flows:read", "flows:write", "runs:write"]; const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))); const decode = (value: string) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)))); const binding = (payload: string, session: Session) => `${payload}.${session.tenantId}.${session.userId}.${session.sessionVersion}`; @@ -33,7 +34,8 @@ export async function consentPreview(env: Env, session: Session, input: z.infer< const nonce = crypto.randomUUID(); await databaseFor(env).pool.query("INSERT INTO app.oauth_consent_previews(id,expires_at) VALUES ($1,$2)", [nonce, new Date(expiresAt * 1000)]); const request = encode({ parsed, expiresAt, nonce, connection: connectionId }); - return { clientName: client.clientName ?? "this client", scopes: parsed.scope.filter(scope => supported.includes(scope)), request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() }; + const requestedScopes = parsed.scope.filter(scope => supported.includes(scope)); + return { clientName: client.clientName ?? "this client", scopes: requestedScopes.some(scope => scope.startsWith("flows:") || scope === "runs:write") ? requestedScopes : normalizeScopes(requestedScopes), 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; @@ -44,7 +46,11 @@ export async function consentDecision(env: Env, session: Session, input: z.infer // Revalidate client registration and redirect URI before grant issuance. const client = await env.OAUTH_PROVIDER.lookupClient(parsed.clientId); if (!client || !client.redirectUris.includes(parsed.redirectUri)) return null; - if (input.scopes.some(scope => !parsed.scope.includes(scope) || !supported.includes(scope))) return null; + const allowed = new Set(normalizeScopes(parsed.scope.filter(scope => supported.includes(scope)))); + const legacyRequest = parsed.scope.some(scope => scope === "flows:read" || scope === "flows:write" || scope === "runs:write"); + const selected = normalizeScopes(input.scopes); + const issuedScopes = legacyRequest ? input.scopes : selected; + if (input.scopes.some(scope => !allowed.has(scope) && !allowed.has(normalizeScopes([scope])[0] ?? "") ) || selected.some(scope => !ACCESS_SCOPES.includes(scope as typeof ACCESS_SCOPES[number]))) return null; return databaseFor(env).transaction(async transaction => { const preview = await transaction.query("UPDATE app.oauth_consent_previews SET used_at=now() WHERE id=$1 AND used_at IS NULL AND expires_at>clock_timestamp() RETURNING id", [envelope.nonce]); if (!preview.rows.length) return null; @@ -53,8 +59,8 @@ export async function consentDecision(env: Env, session: Session, input: z.infer if (!consumed.rows.length) return null; } if (input.decision === "deny") { const redirect = new URL(parsed.redirectUri); redirect.searchParams.set("error", "access_denied"); redirect.searchParams.set("state", parsed.state); if (parsed.issuer) redirect.searchParams.set("iss", parsed.issuer); return { redirectTo: redirect.toString() }; } - const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: input.scopes, authMethod: "oauth" }; - const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: input.scopes, props }); + const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: issuedScopes, authMethod: "oauth" }; + const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: issuedScopes, props }); return { redirectTo }; }); } diff --git a/packages/api/src/device-oauth.ts b/packages/api/src/device-oauth.ts index 2e29b932..bdfc880a 100644 --- a/packages/api/src/device-oauth.ts +++ b/packages/api/src/device-oauth.ts @@ -6,6 +6,7 @@ import { and, eq, gt } from "drizzle-orm"; import type { DatabaseClient } from "./postgres/database"; import { databaseFor } from "./postgres/database"; import { oauthDeviceAuthorizations } from "./postgres/schema"; +import { normalizeScopes } from "./access-tokens"; export const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"; const DEVICE_TTL = 600; @@ -128,7 +129,7 @@ export async function deviceAuthorization(request: Request, env: Env, oauth: OAu if (!compactUserCode) return oauthError("server_error", "Could not allocate a user code.", 500); const now = Math.floor(Date.now() / 1000); const record: DeviceRecord = { - clientId, clientName: client.clientName ?? "this client", tokenEndpointAuthMethod: client.tokenEndpointAuthMethod ?? "none", scope: requested, resource, + clientId, clientName: client.clientName ?? "this client", tokenEndpointAuthMethod: client.tokenEndpointAuthMethod ?? "none", scope: requested.some(scope => scope === "flows:read" || scope === "flows:write" || scope === "runs:write") ? requested : normalizeScopes(requested), resource, redirectUri: client.redirectUris[0], codeChallenge: await challenge(codeVerifier), createdAt: now, expiresAt: now + DEVICE_TTL, interval: DEFAULT_INTERVAL, status: "pending", }; diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 47890e2e..27a39132 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import { conditionsSchema, preparedWebhookSchema } from "./webhook-conditions"; -export const scopeSchema = z.enum(["flows:read", "flows:write", "runs:read", "runs:write"]); +export const scopeSchema = z.enum(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"]); export const runStateSchema = z.enum(["queued", "reserved", "starting", "running", "done", "blocked", "failed", "ignored", "succeeded", "stopping", "stopped"]); export const matchRuleSchema = z.object({ type: z.enum(["owner", "creator", "status", "label", "assignee"]), diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 075fb11c..7b27f623 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -27,7 +27,7 @@ import { evaluateWebhookConditions } from "./webhook-conditions"; import { jobConditionsTestSchema } from "./flow-schemas"; import { ProviderCatalog } from "./postgres/provider-catalog"; import { ArtifactRepository } from "./postgres/artifact-repository"; -import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens"; +import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken, normalizeScopes } from "./access-tokens"; import { TraceProjectionRepository } from "./postgres/trace-projection-repository"; import { replayTrace, traceReplaySchema, traceReplayRunIdSchema, TraceReplayError } from "./trace-replay"; @@ -48,7 +48,7 @@ export function publicValue(schema: T, value: unknown): z.o return result.data; } -type Scope = "flows:read" | "flows:write" | "runs:read" | "runs:write"; +type Scope = "projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write"; export class ApiService { authorizationDuration = 0; @@ -117,7 +117,7 @@ export class ApiService { } private async authorize(scope: Scope): Promise { - if (!this.auth.scopes.includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); + if (!normalizeScopes(this.auth.scopes).includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); const started = performance.now(); try { const database = databaseFor(this.env); @@ -129,12 +129,12 @@ export class ApiService { private async authorizeOwnerSession(scope: Scope): Promise { await this.authorize(scope); if (this.auth.authMethod !== "session") throw new ServiceError(403, "session_required", "An interactive owner session is required."); } - async listExeConnections() { await this.authorize("flows:read"); return publicValue(z.array(exeConnection), (await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).status()).exeConnections); } - async listGitHubInstallations() { await this.authorize("flows:read"); return publicValue(z.array(githubInstallation), JSON.parse(JSON.stringify(await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).installations()))); } - async listTailIntegrations() { await this.authorize("flows:read"); return publicValue(z.array(tailIntegration), await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails()); } + async listExeConnections() { await this.authorize("integrations:read"); return publicValue(z.array(exeConnection), (await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).status()).exeConnections); } + async listGitHubInstallations() { await this.authorize("integrations:read"); return publicValue(z.array(githubInstallation), JSON.parse(JSON.stringify(await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).installations()))); } + async listTailIntegrations() { await this.authorize("integrations:read"); return publicValue(z.array(tailIntegration), await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails()); } async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return publicValue(runPageResponse, JSON.parse(JSON.stringify(await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query)))); } - async search(query: string) { await this.authorize("runs:read"); return publicValue(searchResponse, await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query)); } - async triggerContextMetadata() { await this.authorize("flows:read"); return triggerContextCatalog; } + async search(query: string) { await this.authorize("jobs:read"); await this.authorize("runs:read"); return publicValue(searchResponse, await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query)); } + async triggerContextMetadata() { await this.authorize("jobs:read"); return triggerContextCatalog; } async getRunStatus(runId: string) { await this.authorize("runs:read"); const status = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).status(runId); if (!status) throw new ServiceError(404, "not_found", "Run not found"); return status; } async getRevisionTrace(runId: string, after: number, limit: number, revision?: string) { await this.authorize("runs:read"); const page = await new TraceRepository(databaseFor(this.env), this.auth.tenantId).revisionPage(runId, after, limit, revision); if (!page) throw new ServiceError(404, "not_found", "Run not found"); return page; } async getRun(runId: string) { @@ -185,43 +185,43 @@ export class ApiService { harnessLog: run.harness_log, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; } async replayRunTrace(runId: string, body: unknown) { - await this.authorizeOwnerSession("runs:write"); + await this.authorizeOwnerSession("runs:cancel"); const input = traceReplaySchema.parse(body); traceReplayRunIdSchema.parse(runId); try { return await replayTrace(this.env, this.auth.tenantId, this.auth.userId, runId, input); } catch (error) { if (error instanceof TraceReplayError) throw new ServiceError(error.status, error.code, error.message); throw error; } } - async stopRun(runId: string) { await this.authorize("runs:write"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; } + async stopRun(runId: string) { await this.authorize("runs:cancel"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; } killRun(runId: string) { return this.stopRun(runId); } - async listJobSummaries(input: JobPageQuery, selector = false) { await this.authorize("flows:read"); return new JobSummaryRepository(databaseFor(this.env), this.auth.tenantId).page(input, selector); } - async listJobs() { await this.authorize("flows:read"); const jobs = await this.jobs().list(), stats = await this.jobStatistics(jobs.map(job => job.id)); return Promise.all(jobs.map(job => this.presentJob(job, stats.get(job.id) ?? { running_count: "0", last_run_state: null }))); } - async getJob(jobId: string) { await this.authorize("flows:read"); const job = await this.jobs().getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); return this.presentJob(job); } - async listProjects() { await this.authorize("flows:read"); return this.projects().list(); } - async getProject(projectId: string) { await this.authorize("flows:read"); const project = await this.projects().get(projectId); if (!project) throw new ServiceError(404, "not_found", "Project not found"); return project; } - async createProject(input: { name: string; description?: string }) { await this.authorize("flows:write"); try { return await this.projects().create(input.name, input.description); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A project with this name already exists"); throw error; } } - async updateProject(projectId: string, input: { name: string; description?: string }) { await this.authorize("flows:write"); const result = await this.projects().update(projectId, input.name, input.description); if (!result) throw new ServiceError(404, "not_found", "Project not found"); return result; } - async deleteProject(projectId: string) { await this.authorize("flows:write"); const result = await this.projects().remove(projectId); if (result === "missing") throw new ServiceError(404, "not_found", "Project not found"); if (result === "nonempty") throw new ServiceError(409, "conflict", "Move or delete the project's jobs before deleting it"); return { id: projectId, deleted: true }; } + async listJobSummaries(input: JobPageQuery, selector = false) { await this.authorize("jobs:read"); return new JobSummaryRepository(databaseFor(this.env), this.auth.tenantId).page(input, selector); } + async listJobs() { await this.authorize("jobs:read"); const jobs = await this.jobs().list(), stats = await this.jobStatistics(jobs.map(job => job.id)); return Promise.all(jobs.map(job => this.presentJob(job, stats.get(job.id) ?? { running_count: "0", last_run_state: null }))); } + async getJob(jobId: string) { await this.authorize("jobs:read"); const job = await this.jobs().getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); return this.presentJob(job); } + async listProjects() { await this.authorize("projects:read"); return this.projects().list(); } + async getProject(projectId: string) { await this.authorize("projects:read"); const project = await this.projects().get(projectId); if (!project) throw new ServiceError(404, "not_found", "Project not found"); return project; } + async createProject(input: { name: string; description?: string }) { await this.authorize("projects:write"); try { return await this.projects().create(input.name, input.description); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A project with this name already exists"); throw error; } } + async updateProject(projectId: string, input: { name: string; description?: string }) { await this.authorize("projects:write"); const result = await this.projects().update(projectId, input.name, input.description); if (!result) throw new ServiceError(404, "not_found", "Project not found"); return result; } + async deleteProject(projectId: string) { await this.authorize("projects:write"); const result = await this.projects().remove(projectId); if (result === "missing") throw new ServiceError(404, "not_found", "Project not found"); if (result === "nonempty") throw new ServiceError(409, "conflict", "Move or delete the project's jobs before deleting it"); return { id: projectId, deleted: true }; } async listJobEvents(jobId: string, limit = 50) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).jobEvents(jobId, limit); } async listWebhookDeliveries(query: URLSearchParams) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).deliveries(query); } async getWebhookDelivery(deliveryId: string) { await this.authorize("runs:read"); const value = await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).delivery(deliveryId); if (!value) throw new ServiceError(404,"not_found","Webhook delivery not found"); return value; } - async testJobConditions(input: unknown) { await this.authorize("flows:write"); const parsed = jobConditionsTestSchema.parse(input); return evaluateWebhookConditions(parsed.conditions, parsed.webhook); } + async testJobConditions(input: unknown) { await this.authorize("jobs:write"); const parsed = jobConditionsTestSchema.parse(input); return evaluateWebhookConditions(parsed.conditions, parsed.webhook); } async createJob(input: JobInput) { - await this.authorize("flows:write"); const timestamp = new Date().toISOString(), id = crypto.randomUUID(); + await this.authorize("jobs:write"); const timestamp = new Date().toISOString(), id = crypto.randomUUID(); const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id })); const projectId = input.projectId ?? await this.projects().defaultProjectId(); const job: Job = { id, projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, createdAt: timestamp, updatedAt: timestamp }; try { return this.presentJob(await this.jobs().create(job)); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "Job slug is already in use"); throw error; } } async updateJob(jobId: string, input: JobInput & { expectedUpdatedAt?: string }) { - await this.authorize("flows:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found"); + await this.authorize("jobs:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found"); const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId })); const updated = await repository.update({ ...current, projectId: input.projectId ?? current.projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; }); await this.wakeScheduler(); return this.presentJob(updated); } - async moveJob(jobId: string, projectId: string, expectedUpdatedAt?: string) { await this.authorize("flows:write"); try { return this.presentJob(await this.jobs().move(jobId, projectId, expectedUpdatedAt)); } catch (error) { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload it before moving it."); if (error instanceof Error && error.message === "Project not found") throw new ServiceError(404, "not_found", "Project not found"); if (error instanceof Error && error.message === "Job not found") throw new ServiceError(404, "not_found", "Job not found"); throw error; } } + async moveJob(jobId: string, projectId: string, expectedUpdatedAt?: string) { await this.authorize("projects:write"); try { return this.presentJob(await this.jobs().move(jobId, projectId, expectedUpdatedAt)); } catch (error) { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload it before moving it."); if (error instanceof Error && error.message === "Project not found") throw new ServiceError(404, "not_found", "Project not found"); if (error instanceof Error && error.message === "Job not found") throw new ServiceError(404, "not_found", "Job not found"); throw error; } } async deleteJob(jobId: string) { - await this.authorize("flows:write"); + await this.authorize("jobs:write"); const database = databaseFor(this.env), repository = this.jobs(); if (!await repository.getJob(jobId)) throw new ServiceError(404, "not_found", "Job not found"); const objectKeys = await new ArtifactRepository(database, this.auth.tenantId).keysForJob(jobId); @@ -236,9 +236,9 @@ export class ApiService { private async wakeScheduler() { if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); } - async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("flows:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; } + async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("jobs:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; } async invokeJob(jobId: string, input: ManualInvocationInput) { - await this.authorize("runs:write"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); + await this.authorize("runs:cancel"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled"); const service = new InvocationService(repository, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey: input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`, context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); @@ -246,19 +246,19 @@ export class ApiService { return { invocationId: result.invocation.id, runId: result.run.id, state: result.run.state, duplicate: result.duplicate }; } async listExecutionTargets() { - await this.authorize("flows:read"); const records = await this.targetRecords().list(); const targets: any[] = []; + await this.authorize("jobs:read"); const records = await this.targetRecords().list(); const targets: any[] = []; for (const target of records) { const value = await this.connections().get(`${target.integrationKind}:${target.integrationId}`); if (!value) continue; targets.push({ id: target.id, kind: target.integrationKind === "amp" ? "amp" : "exe-vm", name: target.name, integrationId: target.integrationId, tags: target.tags, workspace: target.integrationKind === "amp" ? value.project : "ephemeral", cwd: target.integrationKind === "amp" ? "Cloud orb" : "/home/exedev/workspace", agentKind: target.agentKind, models: value.models ?? [], modelsRefreshedAt: value.modelsRefreshedAt ?? null, efforts: target.agentKind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : [], capabilities: target.integrationKind === "amp" ? ["stop"] : ["recovery", "stop"] }); } return publicValue(z.array(executionTargetResponse), targets); } - async listExecutionTargetResources() { await this.authorize("flows:read"); return publicValue(z.array((await import("./editor-contracts")).executionTargetResource), await this.targetRecords().list()); } - async createExecutionTarget(input: { name: string; integrationKind: "exe" | "amp"; integrationId: string; tags?: string[]; agentKind: string }) { await this.authorize("flows:write"); const value = await this.connections().get(`${input.integrationKind}:${input.integrationId}`); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); if (input.integrationKind === "exe" && !["codex", "claude", "pi"].includes(input.agentKind)) throw new ServiceError(400, "invalid_request", "Unsupported agent kind"); try { return await this.targetRecords().create({ ...input, tags: input.tags ?? [] }); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A target with this name already exists"); throw error; } } - async updateExecutionTarget(id: string, input: { name: string; integrationKind: "exe" | "amp"; integrationId: string; tags?: string[]; agentKind: string }) { await this.authorize("flows:write"); const value = await this.connections().get(`${input.integrationKind}:${input.integrationId}`); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); if (input.integrationKind === "exe" && !["codex", "claude", "pi"].includes(input.agentKind)) throw new ServiceError(400, "invalid_request", "Unsupported agent kind"); try { const result = await this.targetRecords().update(id, { ...input, tags: input.tags ?? [] }); if (!result) throw new ServiceError(404, "not_found", "Execution target not found"); return result; } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A target with this name already exists"); throw error; } } - async deleteExecutionTarget(id: string) { await this.authorize("flows:write"); const result = await this.targetRecords().remove(id); if (result === "missing") throw new ServiceError(404, "not_found", "Execution target not found"); if (result === "referenced") throw new ServiceError(409, "conflict", "This target is used by a job"); if (result === "active") throw new ServiceError(409, "conflict", "This target is used by an active or queued run"); return { id, deleted: true }; } - async diagnoseExeIntegration(connectionId: string) { await this.authorize("flows:write"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExe(connectionId); if (!value) throw new ServiceError(404,"not_found","Integration not found"); return value; } - async diagnoseExecutionTarget(id: string) { await this.authorize("flows:write"); const target = await this.targetRecords().get(id); if (!target) throw new ServiceError(404, "not_found", "Execution target not found"); if (target.integrationKind !== "exe") throw new ServiceError(400, "invalid_request", "Diagnostics are only available for exe.dev targets"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExeTarget(id, target.integrationId, target.tags, target.agentKind as "codex" | "claude" | "pi"); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); return value; } - async listJobTriggerAvailability() { await this.authorize("flows:read"); const [kinds, installations] = await Promise.all([this.connections().kinds(), new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()]), states=installations.map((x:any)=>x.state); return installedTriggerAvailability(kinds.includes("linear"),kinds.includes("clickup"),states,kinds.filter(x=>x.startsWith("cloudflare-tail:")).length); } + async listExecutionTargetResources() { await this.authorize("integrations:read"); return publicValue(z.array((await import("./editor-contracts")).executionTargetResource), await this.targetRecords().list()); } + async createExecutionTarget(input: { name: string; integrationKind: "exe" | "amp"; integrationId: string; tags?: string[]; agentKind: string }) { await this.authorize("integrations:write"); const value = await this.connections().get(`${input.integrationKind}:${input.integrationId}`); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); if (input.integrationKind === "exe" && !["codex", "claude", "pi"].includes(input.agentKind)) throw new ServiceError(400, "invalid_request", "Unsupported agent kind"); try { return await this.targetRecords().create({ ...input, tags: input.tags ?? [] }); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A target with this name already exists"); throw error; } } + async updateExecutionTarget(id: string, input: { name: string; integrationKind: "exe" | "amp"; integrationId: string; tags?: string[]; agentKind: string }) { await this.authorize("integrations:write"); const value = await this.connections().get(`${input.integrationKind}:${input.integrationId}`); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); if (input.integrationKind === "exe" && !["codex", "claude", "pi"].includes(input.agentKind)) throw new ServiceError(400, "invalid_request", "Unsupported agent kind"); try { const result = await this.targetRecords().update(id, { ...input, tags: input.tags ?? [] }); if (!result) throw new ServiceError(404, "not_found", "Execution target not found"); return result; } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A target with this name already exists"); throw error; } } + async deleteExecutionTarget(id: string) { await this.authorize("integrations:write"); const result = await this.targetRecords().remove(id); if (result === "missing") throw new ServiceError(404, "not_found", "Execution target not found"); if (result === "referenced") throw new ServiceError(409, "conflict", "This target is used by a job"); if (result === "active") throw new ServiceError(409, "conflict", "This target is used by an active or queued run"); return { id, deleted: true }; } + async diagnoseExeIntegration(connectionId: string) { await this.authorize("integrations:write"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExe(connectionId); if (!value) throw new ServiceError(404,"not_found","Integration not found"); return value; } + async diagnoseExecutionTarget(id: string) { await this.authorize("integrations:write"); const target = await this.targetRecords().get(id); if (!target) throw new ServiceError(404, "not_found", "Execution target not found"); if (target.integrationKind !== "exe") throw new ServiceError(400, "invalid_request", "Diagnostics are only available for exe.dev targets"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExeTarget(id, target.integrationId, target.tags, target.agentKind as "codex" | "claude" | "pi"); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); return value; } + async listJobTriggerAvailability() { await this.authorize("jobs:read"); const [kinds, installations] = await Promise.all([this.connections().kinds(), new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()]), states=installations.map((x:any)=>x.state); return installedTriggerAvailability(kinds.includes("linear"),kinds.includes("clickup"),states,kinds.filter(x=>x.startsWith("cloudflare-tail:")).length); } async previewSchedule(input: unknown) { - await this.authorize("flows:read"); + await this.authorize("jobs:read"); try { const config = validateScheduleConfig(input); return { nextRunAt: nextOccurrence(config, new Date()).toISOString() }; @@ -270,34 +270,34 @@ export class ApiService { private integrations() { return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private providers() { return new ProviderCatalog(databaseFor(this.env), this.env, this.auth.tenantId); } - async integrationStatus() { await this.authorize("flows:read"); return publicValue(integrationStatus, await this.integrations().status()); } - async saveExeIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().saveExe(input); } - async testExeIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().testExe(input); } - async removeIntegration(kind: "exe" | "amp", id: string) { await this.authorize("flows:write"); const result = await this.integrations().remove(kind, id); if (result.conflict) throw new ServiceError(409, "conflict", "This integration is used by a job."); if (!result.deleted) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } - async saveAmpIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().saveAmp(input); } - async testAmpIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().testAmp(input); } - async saveTailIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().saveTail(input); } - async testTailIntegration(id: string) { await this.authorize("flows:write"); const result = await this.integrations().testTail(id); if (!result) throw new ServiceError(404, "not_found", "Integration not found"); return result; } - async removeTailIntegration(id: string) { await this.authorize("flows:write"); if (!await this.connections().delete(`cloudflare-tail:${id}`)) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } - async linearProjects() { await this.authorize("flows:read"); return publicValue(z.array(namedOption), await this.providers().linearProjects()); } - async linearOptions() { await this.authorize("flows:read"); return publicValue(providerOptions, await this.providers().linearOptions()); } - async clickUpLists() { await this.authorize("flows:read"); return publicValue(z.array(namedOption), await this.providers().clickUpLists()); } - async clickUpOptions(listId: string) { await this.authorize("flows:read"); return publicValue(providerOptions, await this.providers().clickUpOptions(listId)); } - async githubRepositories(installationId: number) { await this.authorize("flows:read"); return publicValue(z.array(githubRepository), await this.providers().githubRepositories(installationId)); } - async githubIssueOptions(installationId: number, repositoryId: number) { await this.authorize("flows:read"); return publicValue(providerOptions, await this.providers().githubIssueOptions(installationId, repositoryId)); } - async removeGitHubInstallation(id: number) { await this.authorize("flows:write"); if (!await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).delete(id)) throw new ServiceError(404, "not_found", "Installation not found"); return { id, deleted: true }; } + async integrationStatus() { await this.authorize("integrations:read"); return publicValue(integrationStatus, await this.integrations().status()); } + async saveExeIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveExe(input); } + async testExeIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().testExe(input); } + async removeIntegration(kind: "exe" | "amp", id: string) { await this.authorize("integrations:write"); const result = await this.integrations().remove(kind, id); if (result.conflict) throw new ServiceError(409, "conflict", "This integration is used by a job."); if (!result.deleted) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } + async saveAmpIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveAmp(input); } + async testAmpIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().testAmp(input); } + async saveTailIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveTail(input); } + async testTailIntegration(id: string) { await this.authorize("integrations:write"); const result = await this.integrations().testTail(id); if (!result) throw new ServiceError(404, "not_found", "Integration not found"); return result; } + async removeTailIntegration(id: string) { await this.authorize("integrations:write"); if (!await this.connections().delete(`cloudflare-tail:${id}`)) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } + async linearProjects() { await this.authorize("integrations:read"); return publicValue(z.array(namedOption), await this.providers().linearProjects()); } + async linearOptions() { await this.authorize("integrations:read"); return publicValue(providerOptions, await this.providers().linearOptions()); } + async clickUpLists() { await this.authorize("integrations:read"); return publicValue(z.array(namedOption), await this.providers().clickUpLists()); } + async clickUpOptions(listId: string) { await this.authorize("integrations:read"); return publicValue(providerOptions, await this.providers().clickUpOptions(listId)); } + async githubRepositories(installationId: number) { await this.authorize("integrations:read"); return publicValue(z.array(githubRepository), await this.providers().githubRepositories(installationId)); } + async githubIssueOptions(installationId: number, repositoryId: number) { await this.authorize("integrations:read"); return publicValue(providerOptions, await this.providers().githubIssueOptions(installationId, repositoryId)); } + async removeGitHubInstallation(id: number) { await this.authorize("integrations:write"); if (!await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).delete(id)) throw new ServiceError(404, "not_found", "Installation not found"); return { id, deleted: true }; } async listAuthorizedClients() { - await this.authorizeOwnerSession("flows:read"); + await this.authorizeOwnerSession("jobs:read"); if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable"); const grants: any[] = []; let cursor: string | undefined; do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => !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); - return publicValue(z.array(authorizedClient), grants.map(grant => ({ grantId: grant.id, clientId: grant.clientId, clientName: byId.get(grant.clientId)?.clientName ?? grant.clientId, scopes: grant.scope, authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }))); + return publicValue(z.array(authorizedClient), grants.map(grant => ({ grantId: grant.id, clientId: grant.clientId, clientName: byId.get(grant.clientId)?.clientName ?? grant.clientId, scopes: normalizeScopes(grant.scope), authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }))); } - async revokeAuthorizedClient(clientId: string) { await this.authorizeOwnerSession("flows:write"); if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable"); const grants: any[] = []; let cursor: string | undefined; do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => grant.clientId === clientId)); cursor = page.cursor; } while (cursor); await Promise.all(grants.map(grant => this.env.OAUTH_PROVIDER!.revokeGrant(grant.id, this.auth.userId))); return { revoked: grants.length }; } - async listAccessTokens() { await this.authorizeOwnerSession("flows:read"); return publicValue(z.array(accessToken), JSON.parse(JSON.stringify(await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).list()))); } - async createAccessToken(input: any) { await this.authorizeOwnerSession("flows:write"); const name = typeof input?.name === "string" ? input.name.trim() : "", requested: string[] = Array.isArray(input?.scopes) ? [...new Set(input.scopes.filter((scope: unknown): scope is string => typeof scope === "string"))] : [], expiryDays = Number(input?.expiryDays); if (!name || name.length > 100 || !requested.length || requested.some(scope => !ACCESS_SCOPES.includes(scope as any)) || ![7, 30, 90].includes(expiryDays)) throw new ServiceError(400, "invalid_request", "A name, supported scopes, and expiryDays of 7, 30, or 90 are required."); const token = issueAccessToken(this.auth.tenantId), expiresAt = new Date(Date.now() + expiryDays * 86_400_000).toISOString(); const metadata = await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).create({ name, scopes: requested, expiresAt, digest: await accessTokenDigest(token), userId: this.auth.userId, sessionVersion: this.auth.sessionVersion }); if (!metadata) throw new ServiceError(401, "invalid_token", "The owner session is no longer active."); return publicValue(createdAccessToken, JSON.parse(JSON.stringify({ ...metadata, token }))); } - async revokeAccessToken(id: string) { await this.authorizeOwnerSession("flows:write"); if (!await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).revoke(id)) throw new ServiceError(404, "not_found", "Access token not found"); return { revoked: true }; } + async revokeAuthorizedClient(clientId: string) { await this.authorizeOwnerSession("jobs:write"); if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable"); const grants: any[] = []; let cursor: string | undefined; do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => grant.clientId === clientId)); cursor = page.cursor; } while (cursor); await Promise.all(grants.map(grant => this.env.OAUTH_PROVIDER!.revokeGrant(grant.id, this.auth.userId))); return { revoked: grants.length }; } + async listAccessTokens() { await this.authorizeOwnerSession("jobs:read"); return publicValue(z.array(accessToken), (await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).list()).map(token => ({ ...token, created_at: new Date(token.created_at).toISOString(), expires_at: new Date(token.expires_at).toISOString(), last_used_at: token.last_used_at ? new Date(token.last_used_at).toISOString() : null, revoked_at: token.revoked_at ? new Date(token.revoked_at).toISOString() : null, scopes: normalizeScopes(token.scopes) }))); } + async createAccessToken(input: any) { await this.authorizeOwnerSession("jobs:write"); const name = typeof input?.name === "string" ? input.name.trim() : "", requested: string[] = Array.isArray(input?.scopes) ? [...new Set(input.scopes.filter((scope: unknown): scope is string => typeof scope === "string"))] : [], legacy = new Set(["flows:read", "flows:write", "runs:write"]), scopes = normalizeScopes(requested), expiryDays = Number(input?.expiryDays); if (!name || name.length > 100 || !requested.length || requested.some(scope => !ACCESS_SCOPES.includes(scope as any) && !legacy.has(scope)) || !scopes.length || ![7, 30, 90].includes(expiryDays)) throw new ServiceError(400, "invalid_request", "A name, supported scopes, and expiryDays of 7, 30, or 90 are required."); const token = issueAccessToken(this.auth.tenantId), expiresAt = new Date(Date.now() + expiryDays * 86_400_000).toISOString(); const metadata = await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).create({ name, scopes, expiresAt, digest: await accessTokenDigest(token), userId: this.auth.userId, sessionVersion: this.auth.sessionVersion }); if (!metadata) throw new ServiceError(401, "invalid_token", "The owner session is no longer active."); return publicValue(createdAccessToken, JSON.parse(JSON.stringify({ ...metadata, token }))); } + async revokeAccessToken(id: string) { await this.authorizeOwnerSession("jobs:write"); if (!await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).revoke(id)) throw new ServiceError(404, "not_found", "Access token not found"); return { revoked: true }; } } diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 616d6cae..db546ea2 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -10,6 +10,7 @@ import { jobConditionsTestSchema, jobIdSchema, jobInputSchema, listRunsSchema, m import type { Env, OAuthProps } from "./types"; import { executeAuth, validBrowserOrigin } from "./auth-api"; import { matchApiOperation } from "./api-contract"; +import { normalizeScopes } from "./access-tokens"; function errorResponse(error: unknown): Response { if (error instanceof URIError) return Response.json({ error: { code: "invalid_request", message: "Invalid path encoding" } }, { status: 400 }); @@ -38,6 +39,7 @@ function structured(value: unknown) { } export async function protectedApiFetch(request: Request, env: Env, auth: OAuthProps | null, ctx: ExecutionContext): Promise { + auth = auth ? { ...auth, scopes: normalizeScopes(auth.scopes) } : null; const started = performance.now(); let service: ApiService | undefined; const timed = (response: Response) => { @@ -57,7 +59,8 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP const { route, params } = matched; if (!["GET", "HEAD", "OPTIONS"].includes(request.method) && (route.authOperation || auth?.authMethod === "session") && !validBrowserOrigin(request, env)) throw new ServiceError(403, "invalid_origin", "Invalid request origin."); if (!route.authOperation && !auth) throw new ServiceError(401, "invalid_token", "Unauthorized"); - if (!route.authOperation && !auth!.scopes.includes(route.scope)) throw new ServiceError(403, "insufficient_scope", `The ${route.scope} scope is required.`); + const requiredScopes = Array.isArray(route.scope) ? route.scope : route.scope.split("+"); + if (!route.authOperation && !requiredScopes.every(scope => auth!.scopes.includes(scope))) throw new ServiceError(403, "insufficient_scope", `The ${requiredScopes.join(" and ")} scope is required.`); if (!route.authOperation && route.ownerSession && auth!.authMethod !== "session") throw new ServiceError(403, "session_required", "An interactive owner session is required."); let body: unknown; if (route.body) { diff --git a/packages/api/src/settings-contracts.ts b/packages/api/src/settings-contracts.ts index 9d1426ac..480f4e40 100644 --- a/packages/api/src/settings-contracts.ts +++ b/packages/api/src/settings-contracts.ts @@ -5,7 +5,7 @@ export const exeConnection = z.object({ connectionId: z.string(), agentKind: z.e export const ampConnection = z.object({ connectionId: z.string(), project: z.string(), apiBaseUrl: z.string().optional() }); 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 authorizedClient = z.object({ grantId: z.string(), clientId: z.string(), clientName: z.string(), 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(["flows:read", "flows:write", "runs:read", "runs:write"])), created_at: timestamp, expires_at: timestamp, last_used_at: timestamp.nullable().optional(), revoked_at: timestamp.nullable().optional() }); +export const accessToken = z.object({ id: z.string(), name: z.string(), scopes: z.array(z.enum(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"])), 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 savedExe = okResult.extend({ connectionId: z.string(), models: z.array(z.string()) }); diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index 34532765..5fcb05ab 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -14,7 +14,10 @@ import { traceChunkUpload } from "./trace-chunk-upload"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; -const scopes = ["flows:read", "flows:write", "runs:read", "runs:write"]; +const scopes = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"]; +// Keep accepting grants issued by the pre-resource-scope protocol. New +// consent screens and metadata advertise only the canonical scopes above. +const oauthScopes = [...scopes, "flows:read", "flows:write", "runs:write"]; async function currentOwner(request: Request, env: Env) { const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET); if (!session) return null; @@ -72,7 +75,7 @@ const defaultHandler: ExportedHandler = { function providerOptions(env: Env): OAuthProviderOptions { return { apiRoute: ["/api/v1", "/mcp"], apiHandler: ProtectedApiHandler, defaultHandler, authorizeEndpoint: "/authorize", tokenEndpoint: "/oauth/token", clientRegistrationEndpoint: "/oauth/register", - scopesSupported: scopes, allowImplicitFlow: false, allowPlainPKCE: false, + scopesSupported: oauthScopes, allowImplicitFlow: false, allowPlainPKCE: false, accessTokenTTL: 3600, refreshTokenTTL: 2_592_000, clientIdMetadataDocumentEnabled: true, resourceMetadata: { resource: `${env.APP_ORIGIN}/mcp`, authorization_servers: [env.APP_ORIGIN], scopes_supported: scopes, bearer_methods_supported: ["header"], resource_name: "Factorize jobs" }, @@ -103,7 +106,7 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) if (!auth) return Response.json({ error: { code: "invalid_token", message: "The access token is invalid, expired, or revoked." } }, { status: 401, headers: { "WWW-Authenticate": "Bearer error=\"invalid_token\"" } }); return protectedApiFetch(request, apiEnv, auth, ctx); } - if (url.pathname === "/oauth/device_authorization") return deviceAuthorization(request, env, getOAuthApi(providerOptions(env), env), scopes); + if (url.pathname === "/oauth/device_authorization") return deviceAuthorization(request, env, getOAuthApi(providerOptions(env), env), oauthScopes); if (url.pathname === "/oauth/register") return deviceClientRegistration(request, env, oauth, ctx); if (url.pathname === "/oauth/token" && request.method === "POST") { const clone = request.clone(); diff --git a/packages/api/test/scope-redesign.test.ts b/packages/api/test/scope-redesign.test.ts new file mode 100644 index 00000000..bfc7aefe --- /dev/null +++ b/packages/api/test/scope-redesign.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; +import { ACCESS_SCOPES, normalizeScopes } from "../src/access-tokens"; +import { API_ROUTES } from "../src/api-contract"; + +describe("GEN-2418 permission boundaries", () => { + it("exposes exactly nine independently issuable scopes and maps legacy grants without issuing them", () => { + expect(ACCESS_SCOPES).toEqual(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"]); + expect(normalizeScopes(["flows:read", "runs:write"])).toEqual(["projects:read", "jobs:read", "integrations:read", "runs:read", "runs:invoke", "runs:cancel"]); + expect(ACCESS_SCOPES).not.toContain("flows:read" as never); + }); + + it("keeps project creation separate from job and integration writes", () => { + const scope = (method: string, path: string) => API_ROUTES.find(route => route.method === method && route.path === path)?.scope; + expect(scope("POST", "/api/v1/projects")).toBe("projects:write"); + expect(scope("POST", "/api/v1/jobs")).toBe("jobs:write"); + expect(scope("PUT", "/api/v1/integrations/exe")).toBe("integrations:write"); + expect(scope("POST", "/api/v1/jobs/{jobId}/invocations")).toBe("runs:invoke"); + expect(scope("POST", "/api/v1/runs/{runId}/kill")).toBe("runs:cancel"); + expect(scope("GET", "/api/v1/search")).toBe("jobs:read+runs:read"); + }); +}); diff --git a/packages/app/src/features/auth/consent.tsx b/packages/app/src/features/auth/consent.tsx index 74164a99..5b0e945d 100644 --- a/packages/app/src/features/auth/consent.tsx +++ b/packages/app/src/features/auth/consent.tsx @@ -6,9 +6,9 @@ import { messageOf } from "./session"; 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) as ("flows:read" | "flows:write" | "runs:read" | "runs:write")[] } }); if (!data || error) throw new Error(messageOf(error)); location.assign(data.redirectTo); } }); + 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 ?? []; return

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

{preview.isPending &&

Validating authorization request…

}{preview.error &&

{preview.error.message}

} - {preview.data && <>

This client requests access to your workspace. Request expires {preview.data.expiresAt}.

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

{decision.error.message}

} + {preview.data && <>

This client requests workspace access. Permissions are independent; write does not imply read. Job writes may cause future schedule/webhook/lifecycle execution, and deleting a job may remove run history and artifacts. Request expires {preview.data.expiresAt}.

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

{decision.error.message}

}
; } diff --git a/packages/app/src/features/settings/api-keys.tsx b/packages/app/src/features/settings/api-keys.tsx index 6d0b11b0..5c959eff 100644 --- a/packages/app/src/features/settings/api-keys.tsx +++ b/packages/app/src/features/settings/api-keys.tsx @@ -5,15 +5,16 @@ import { api } from "factorize-api-client"; import { tokensQuery } from "./queries"; import { SettingsLayout } from "./navigation"; import { messageOf } from "../auth/session"; -const allScopes = ["flows:read", "flows:write", "runs:read", "runs:write"] as const; +const allScopes = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"] as const; +const scopeDescriptions: Record = { "projects:read": "View projects", "projects:write": "Create, rename, and delete projects", "jobs:read": "View jobs and job configuration", "jobs:write": "Create, edit, enable, disable, and delete jobs", "runs:read": "View runs, traces, context, and diagnostics", "runs:invoke": "Start jobs", "runs:cancel": "Stop or cancel runs", "integrations:read": "View integrations and provider resources", "integrations:write": "Create, configure, test, and remove integrations" }; export function ApiKeys() { const cache = useQueryClient(), tokens = useQuery(tokensQuery), [secret, setSecret] = useState(""); - const [name, setName] = useState(""), [scopes, setScopes] = useState<(typeof allScopes[number])[]>(["flows:read", "runs:read"]), [expiryDays, setExpiryDays] = useState<7 | 30 | 90>(30); + const [name, setName] = useState(""), [scopes, setScopes] = useState<(typeof allScopes[number])[]>(["jobs:read", "runs:read"]), [expiryDays, setExpiryDays] = useState<7 | 30 | 90>(30); const create = useMutation({ retry: false, mutationFn: async () => { const { data, error } = await api.POST("/api/v1/access-tokens", { body: { name, scopes, expiryDays } }); if (!data || error) throw new Error(messageOf(error)); const { token, ...metadata } = data; setSecret(token); return metadata; }, onSuccess: () => { setName(""); void cache.invalidateQueries({ queryKey: tokensQuery.queryKey }); } }); const revoke = useMutation({ retry: false, mutationFn: async (tokenId: string) => { const { error } = await api.DELETE("/api/v1/access-tokens/{tokenId}", { params: { path: { tokenId } } }); if (error) throw new Error(messageOf(error)); }, onSuccess: () => cache.invalidateQueries({ queryKey: tokensQuery.queryKey }) }); return {secret &&

Copy this key now. It will only be displayed once.

{secret}
} -
{ e.preventDefault(); create.mutate(); }}>
Scopes{allScopes.map(scope => )}
+
{ e.preventDefault(); create.mutate(); }}>

Permissions are independent: write does not imply read. Job writes can affect future schedule, webhook, and lifecycle executions; deleting a job may remove its run history and artifacts.

Permissions{allScopes.map(scope => )}
{tokens.isPending &&

Loading keys…

}{[tokens.error, create.error, revoke.error].filter(Boolean).map((error, i) =>

{error?.message}

)}{tokens.data?.length === 0 &&

No API keys.

}
    {tokens.data?.map(token =>
  • {token.name}

    {token.scopes.join(", ")} · Expires {token.expires_at} · Last used {token.last_used_at ?? "Never"}

    {token.revoked_at ?

    Revoked

    : }
  • )}
; diff --git a/packages/docs/api/authentication.mdx b/packages/docs/api/authentication.mdx index 8809eb02..f4305685 100644 --- a/packages/docs/api/authentication.mdx +++ b/packages/docs/api/authentication.mdx @@ -23,10 +23,19 @@ An expired or completed request cannot be extended by resending email or recover | Scope | Allows | | --- | --- | -| `flows:read` | Jobs, targets, connections, integrations, trigger availability | -| `flows:write` | Create/update/delete/enable/disable jobs; test conditions | -| `runs:read` | List/get runs and webhook activity | -| `runs:write` | Invoke and stop runs | +| `projects:read` | View projects | +| `projects:write` | Create, update, and delete projects | +| `jobs:read` | View jobs and job configuration | +| `jobs:write` | Create, update, enable, disable, and delete jobs | +| `runs:read` | Inspect runs, context, traces, and diagnostics | +| `runs:invoke` | Invoke jobs | +| `runs:cancel` | Stop or cancel runs, including `kill` | +| `integrations:read` | View integration metadata and provider resources | +| `integrations:write` | Create, configure, test, and remove integrations | + +Scopes are independent: write does not imply read. Job configuration can cause future execution through schedules, webhooks, and lifecycle triggers; deleting a job can remove its execution history and artifacts. Key and OAuth grant administration and trace replay always require an interactive owner session. + +Legacy `flows:read`, `flows:write`, and `runs:write` grants remain usable during migration and are normalized at authentication (`flows:read` → all three read domains, `flows:write` → all three write domains, and `runs:write` → `runs:invoke` plus `runs:cancel`). New API keys, OAuth consent, and discovery expose only the nine scopes. Existing clients should reauthorize before legacy support is removed; no new legacy grant is issued. Authorization-code clients must use PKCE S256. Implicit and plain PKCE are disabled. Access tokens last 1 hour; refresh tokens can last 30 days. RFC 7009 revocation is advertised by discovery. diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 9402de43..4e8d8bc2 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -61,7 +61,7 @@ Start Claude Code, enter `/mcp`, choose Factorize and authenticate when prompted The client opens Factorize authorization in your browser. Sign in with your verified Factorize email/password and approve the requested scopes. For the full workflow, grant `flows:read`, `flows:write`, `runs:read`, and `runs:write`. Read-only access cannot create or invoke jobs. Return to your client after consent. -If you need to create an account or verify your email, finish those steps and restart client authorization; do not assume the signup screen will automatically resume the original request. No Linear or execution token belongs in the MCP client. +Consent lists nine independent permissions: `projects:read`, `projects:write`, `jobs:read`, `jobs:write`, `runs:read`, `runs:invoke`, `runs:cancel`, `integrations:read`, and `integrations:write`. Write does not imply read. If you need to create an account or verify your email, finish those steps and restart client authorization; do not assume the signup screen will automatically resume the original request. No Linear or execution token belongs in the MCP client. Ask **“List my Factorize jobs.”** The agent should call `list_jobs({})`. An empty `items` list is a successful connection to a workspace with no jobs. Next ask it to list execution targets and follow the [first-job walkthrough](https://docs.factorize.sh/quickstart). @@ -399,41 +399,43 @@ Connect to `https://app.factorize.sh/mcp` using [client authorization](https://d ## Inventory +The required scope inventory below is authoritative. Legacy `flows:*` and `runs:write` grants are accepted only during migration and are mapped to the nine scopes at authentication. + | Tool | Required scope | Input contract | | --- | --- | --- | -| `list_exe_connections` | flows:read | `{}` | -| `list_github_installations` | flows:read | `{}` | -| `list_execution_targets` | flows:read | `{}` | -| `list_execution_target_resources` | flows:read | `{}`; returns non-secret target records for management | -| `create_execution_target` | flows:write | Required `name`, `integrationKind`, `integrationId`, `agentKind`; optional `tags` | -| `update_execution_target` | flows:write | Required `targetId`, `name`, `integrationKind`, `integrationId`, `agentKind`; optional `tags` | -| `delete_execution_target` | flows:write | Required string `targetId`; rejects referenced or active targets | -| `diagnose_execution_target` | flows:write | Required string `targetId`; probes the target's exact tags and agent | -| `list_cloudflare_tail_integrations` | flows:read | `{}` | -| `list_jobs` | flows:read | `{}` | -| `list_projects` | flows:read | `{}` | -| `get_project` | flows:read | Required string `projectId` | -| `create_project` | flows:write | Required `name`; optional `description` | -| `update_project` | flows:write | Required `projectId` and `name`; optional `description` | -| `delete_project` | flows:write | Required string `projectId` | -| `move_job` | flows:write | Required `jobId` and destination `projectId`; optional `expectedUpdatedAt` | -| `get_job` | flows:read | Required string `jobId` | -| `create_job` | flows:write | Required `name`, `slug`, `promptTemplate`, `executionTargetId`; job fields below | -| `update_job` | flows:write | Same required job fields plus `jobId`; optional `expectedUpdatedAt` | -| `delete_job` | flows:write | Required string `jobId` | -| `enable_job` | flows:write | Required string `jobId` | -| `disable_job` | flows:write | Required string `jobId` | +| `list_exe_connections` | integrations:read | `{}` | +| `list_github_installations` | integrations:read | `{}` | +| `list_execution_targets` | integrations:read | `{}` | +| `list_execution_target_resources` | integrations:read | `{}`; returns non-secret target records for management | +| `create_execution_target` | integrations:write | Required `name`, `integrationKind`, `integrationId`, `agentKind`; optional `tags` | +| `update_execution_target` | integrations:write | Required `targetId`, `name`, `integrationKind`, `integrationId`, `agentKind`; optional `tags` | +| `delete_execution_target` | integrations:write | Required string `targetId`; rejects referenced or active targets | +| `diagnose_execution_target` | integrations:write | Required string `targetId`; probes the target's exact tags and agent | +| `diagnose_exe_integration` | integrations:write | Required string `connectionId`; credential-safe diagnostic | +| `list_cloudflare_tail_integrations` | integrations:read | `{}` | +| `list_jobs` | jobs:read | `{}` | +| `get_job` | jobs:read | Required string `jobId` | +| `create_job` | jobs:write | Required `name`, `slug`, `promptTemplate`, `executionTargetId`; job fields below | +| `update_job` | jobs:write | Same required job fields plus `jobId`; optional `expectedUpdatedAt` | +| `delete_job` | jobs:write | Required string `jobId`; deletion removes execution history/artifacts | +| `enable_job` | jobs:write | Required string `jobId` | +| `disable_job` | jobs:write | Required string `jobId` | +| `list_projects` | projects:read | `{}` | +| `get_project` | projects:read | Required string `projectId` | +| `create_project` | projects:write | Required `name`; optional `description` | +| `update_project` | projects:write | Required `projectId` and `name`; optional `description` | +| `delete_project` | projects:write | Required string `projectId` | +| `move_job` | projects:write | Required `jobId` and destination `projectId`; optional `expectedUpdatedAt` | | `list_runs` | runs:read | Optional `jobId`, `state`, `contextQuery`, `limit`, `cursor` | | `get_run` | runs:read | Required string `runId` | | `get_run_diagnostics` | runs:read | Required string `runId` | -| `invoke_job` | runs:write | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | -| `stop_run` | runs:write | Required string `runId` | -| `kill_run` | runs:write | Required string `runId`; currently the same stop operation | +| `invoke_job` | runs:invoke | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `stop_run` | runs:cancel | Required string `runId` | +| `kill_run` | runs:cancel | Required string `runId`; currently the same stop operation | | `list_job_webhook_activity` | runs:read | Required `jobId`; optional integer `limit` (1–100, default 50) | | `list_webhook_deliveries` | runs:read | Optional strings `provider`, `deliveryId`, `event`, `action`, `outcome`, `jobId`, `q`, `from`, `to`, `cursor`; integer `limit` (1–100, default 50) | | `get_webhook_delivery` | runs:read | Required string `deliveryId` | -| `test_job_webhook_conditions` | flows:write | Required prepared JSON object `webhook`; optional `conditions` tree | -| `diagnose_exe_integration` | flows:write | Required string `connectionId` | +| `test_job_webhook_conditions` | jobs:write | Required prepared JSON object `webhook`; optional `conditions` tree | The inventory is validated against every registered implementation tool. All required IDs are non-empty strings except numeric GitHub installation/repository IDs in trigger configuration. @@ -611,10 +613,19 @@ An expired or completed request cannot be extended by resending email or recover | Scope | Allows | | --- | --- | -| `flows:read` | Jobs, targets, connections, integrations, trigger availability | -| `flows:write` | Create/update/delete/enable/disable jobs; test conditions | -| `runs:read` | List/get runs and webhook activity | -| `runs:write` | Invoke and stop runs | +| `projects:read` | View projects | +| `projects:write` | Create, update, and delete projects | +| `jobs:read` | View jobs and job configuration | +| `jobs:write` | Create, update, enable, disable, and delete jobs | +| `runs:read` | Inspect runs, context, traces, and diagnostics | +| `runs:invoke` | Invoke jobs | +| `runs:cancel` | Stop or cancel runs, including `kill` | +| `integrations:read` | View integration metadata and provider resources | +| `integrations:write` | Create, configure, test, and remove integrations | + +Scopes are independent: write does not imply read. Job configuration can cause future execution through schedules, webhooks, and lifecycle triggers; deleting a job can remove its execution history and artifacts. Key and OAuth grant administration and trace replay always require an interactive owner session. + +Legacy `flows:read`, `flows:write`, and `runs:write` grants remain usable during migration and are normalized at authentication (`flows:read` → all three read domains, `flows:write` → all three write domains, and `runs:write` → `runs:invoke` plus `runs:cancel`). New API keys, OAuth consent, and discovery expose only the nine scopes. Existing clients should reauthorize before legacy support is removed; no new legacy grant is issued. Authorization-code clients must use PKCE S256. Implicit and plain PKCE are disabled. Access tokens last 1 hour; refresh tokens can last 30 days. RFC 7009 revocation is advertised by discovery. diff --git a/packages/docs/mcp/overview.mdx b/packages/docs/mcp/overview.mdx index 52fae945..f5987028 100644 --- a/packages/docs/mcp/overview.mdx +++ b/packages/docs/mcp/overview.mdx @@ -36,7 +36,7 @@ Start Claude Code, enter `/mcp`, choose Factorize and authenticate when prompted The client opens Factorize authorization in your browser. Sign in with your verified Factorize email/password and approve the requested scopes. For the full workflow, grant `flows:read`, `flows:write`, `runs:read`, and `runs:write`. Read-only access cannot create or invoke jobs. Return to your client after consent. -If you need to create an account or verify your email, finish those steps and restart client authorization; do not assume the signup screen will automatically resume the original request. No Linear or execution token belongs in the MCP client. +Consent lists nine independent permissions: `projects:read`, `projects:write`, `jobs:read`, `jobs:write`, `runs:read`, `runs:invoke`, `runs:cancel`, `integrations:read`, and `integrations:write`. Write does not imply read. If you need to create an account or verify your email, finish those steps and restart client authorization; do not assume the signup screen will automatically resume the original request. No Linear or execution token belongs in the MCP client. Ask **“List my Factorize jobs.”** The agent should call `list_jobs({})`. An empty `items` list is a successful connection to a workspace with no jobs. Next ask it to list execution targets and follow the [first-job walkthrough](/quickstart). diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index 9aaa4864..19852e8b 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -7,41 +7,43 @@ Connect to `https://app.factorize.sh/mcp` using [client authorization](/mcp/over ## Inventory +The required scope inventory below is authoritative. Legacy `flows:*` and `runs:write` grants are accepted only during migration and are mapped to the nine scopes at authentication. + | Tool | Required scope | Input contract | | --- | --- | --- | -| `list_exe_connections` | flows:read | `{}` | -| `list_github_installations` | flows:read | `{}` | -| `list_execution_targets` | flows:read | `{}` | -| `list_execution_target_resources` | flows:read | `{}`; returns non-secret target records for management | -| `create_execution_target` | flows:write | Required `name`, `integrationKind`, `integrationId`, `agentKind`; optional `tags` | -| `update_execution_target` | flows:write | Required `targetId`, `name`, `integrationKind`, `integrationId`, `agentKind`; optional `tags` | -| `delete_execution_target` | flows:write | Required string `targetId`; rejects referenced or active targets | -| `diagnose_execution_target` | flows:write | Required string `targetId`; probes the target's exact tags and agent | -| `list_cloudflare_tail_integrations` | flows:read | `{}` | -| `list_jobs` | flows:read | `{}` | -| `list_projects` | flows:read | `{}` | -| `get_project` | flows:read | Required string `projectId` | -| `create_project` | flows:write | Required `name`; optional `description` | -| `update_project` | flows:write | Required `projectId` and `name`; optional `description` | -| `delete_project` | flows:write | Required string `projectId` | -| `move_job` | flows:write | Required `jobId` and destination `projectId`; optional `expectedUpdatedAt` | -| `get_job` | flows:read | Required string `jobId` | -| `create_job` | flows:write | Required `name`, `slug`, `promptTemplate`, `executionTargetId`; job fields below | -| `update_job` | flows:write | Same required job fields plus `jobId`; optional `expectedUpdatedAt` | -| `delete_job` | flows:write | Required string `jobId` | -| `enable_job` | flows:write | Required string `jobId` | -| `disable_job` | flows:write | Required string `jobId` | +| `list_exe_connections` | integrations:read | `{}` | +| `list_github_installations` | integrations:read | `{}` | +| `list_execution_targets` | integrations:read | `{}` | +| `list_execution_target_resources` | integrations:read | `{}`; returns non-secret target records for management | +| `create_execution_target` | integrations:write | Required `name`, `integrationKind`, `integrationId`, `agentKind`; optional `tags` | +| `update_execution_target` | integrations:write | Required `targetId`, `name`, `integrationKind`, `integrationId`, `agentKind`; optional `tags` | +| `delete_execution_target` | integrations:write | Required string `targetId`; rejects referenced or active targets | +| `diagnose_execution_target` | integrations:write | Required string `targetId`; probes the target's exact tags and agent | +| `diagnose_exe_integration` | integrations:write | Required string `connectionId`; credential-safe diagnostic | +| `list_cloudflare_tail_integrations` | integrations:read | `{}` | +| `list_jobs` | jobs:read | `{}` | +| `get_job` | jobs:read | Required string `jobId` | +| `create_job` | jobs:write | Required `name`, `slug`, `promptTemplate`, `executionTargetId`; job fields below | +| `update_job` | jobs:write | Same required job fields plus `jobId`; optional `expectedUpdatedAt` | +| `delete_job` | jobs:write | Required string `jobId`; deletion removes execution history/artifacts | +| `enable_job` | jobs:write | Required string `jobId` | +| `disable_job` | jobs:write | Required string `jobId` | +| `list_projects` | projects:read | `{}` | +| `get_project` | projects:read | Required string `projectId` | +| `create_project` | projects:write | Required `name`; optional `description` | +| `update_project` | projects:write | Required `projectId` and `name`; optional `description` | +| `delete_project` | projects:write | Required string `projectId` | +| `move_job` | projects:write | Required `jobId` and destination `projectId`; optional `expectedUpdatedAt` | | `list_runs` | runs:read | Optional `jobId`, `state`, `contextQuery`, `limit`, `cursor` | | `get_run` | runs:read | Required string `runId` | | `get_run_diagnostics` | runs:read | Required string `runId` | -| `invoke_job` | runs:write | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | -| `stop_run` | runs:write | Required string `runId` | -| `kill_run` | runs:write | Required string `runId`; currently the same stop operation | +| `invoke_job` | runs:invoke | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `stop_run` | runs:cancel | Required string `runId` | +| `kill_run` | runs:cancel | Required string `runId`; currently the same stop operation | | `list_job_webhook_activity` | runs:read | Required `jobId`; optional integer `limit` (1–100, default 50) | | `list_webhook_deliveries` | runs:read | Optional strings `provider`, `deliveryId`, `event`, `action`, `outcome`, `jobId`, `q`, `from`, `to`, `cursor`; integer `limit` (1–100, default 50) | | `get_webhook_delivery` | runs:read | Required string `deliveryId` | -| `test_job_webhook_conditions` | flows:write | Required prepared JSON object `webhook`; optional `conditions` tree | -| `diagnose_exe_integration` | flows:write | Required string `connectionId` | +| `test_job_webhook_conditions` | jobs:write | Required prepared JSON object `webhook`; optional `conditions` tree | The inventory is validated against every registered implementation tool. All required IDs are non-empty strings except numeric GitHub installation/repository IDs in trigger configuration. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index d08f6ec3..8debd47a 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1402,10 +1402,15 @@ paths: items: type: string enum: - - flows:read - - flows:write + - projects:read + - projects:write + - jobs:read + - jobs:write - runs:read - - runs:write + - runs:invoke + - runs:cancel + - integrations:read + - integrations:write expiresAt: type: string format: date-time @@ -2313,11 +2318,6 @@ paths: type: array items: type: string - enum: - - flows:read - - flows:write - - runs:read - - runs:write required: - request - signature @@ -2377,7 +2377,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the jobs:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_trigger_contexts @@ -2386,7 +2386,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: false /api/v1/exe-connections: get: @@ -2446,7 +2446,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_exe_connections @@ -2455,7 +2455,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false /api/v1/github-installations: get: @@ -2509,7 +2509,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_github_installations @@ -2518,7 +2518,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false /api/v1/execution-targets: get: @@ -2596,7 +2596,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_execution_targets @@ -2605,7 +2605,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false post: summary: Create execution target @@ -2682,7 +2682,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_execution_targets @@ -2691,7 +2691,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false requestBody: required: true @@ -2804,7 +2804,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: put_api_v1_execution_targets_targetId @@ -2813,7 +2813,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: targetId @@ -2883,7 +2883,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: delete_api_v1_execution_targets_targetId @@ -2892,7 +2892,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: targetId @@ -2984,7 +2984,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_execution_targets_targetId_diagnostics @@ -2993,7 +2993,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: targetId @@ -3056,7 +3056,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the jobs:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_job_trigger_availability @@ -3065,7 +3065,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: false /api/v1/schedules/preview: post: @@ -3102,7 +3102,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the jobs:read scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_schedules_preview @@ -3111,7 +3111,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: false requestBody: required: true @@ -3185,7 +3185,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_integrations_cloudflare_tail @@ -3194,7 +3194,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false post: summary: Create a Tail integration @@ -3243,7 +3243,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_integrations_cloudflare_tail @@ -3252,7 +3252,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false requestBody: required: true @@ -3466,7 +3466,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_integrations @@ -3475,7 +3475,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false /api/v1/integrations/exe: put: @@ -3520,7 +3520,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: put_api_v1_integrations_exe @@ -3529,7 +3529,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false requestBody: required: true @@ -3630,7 +3630,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_integrations_exe_test @@ -3639,7 +3639,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false requestBody: required: true @@ -3705,7 +3705,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: put_api_v1_integrations_amp @@ -3714,7 +3714,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false requestBody: required: true @@ -3774,7 +3774,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_integrations_amp_test @@ -3783,7 +3783,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false requestBody: required: true @@ -3843,7 +3843,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_providers_linear_projects @@ -3852,7 +3852,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false /api/v1/providers/linear/options: get: @@ -3926,7 +3926,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_providers_linear_options @@ -3935,7 +3935,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false /api/v1/providers/clickup/lists: get: @@ -3975,7 +3975,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_providers_clickup_lists @@ -3984,7 +3984,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false /api/v1/providers/clickup/options: get: @@ -4058,7 +4058,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_providers_clickup_options @@ -4067,7 +4067,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false parameters: - name: listId @@ -4128,7 +4128,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_providers_github_installations @@ -4137,7 +4137,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false /api/v1/access/authorized-clients: get: @@ -4198,7 +4198,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the jobs:read scope. An interactive owner session is required; bearer tokens cannot call this operation. operationId: get_api_v1_access_authorized_clients @@ -4207,7 +4207,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: true /api/v1/access-tokens: get: @@ -4231,10 +4231,15 @@ paths: items: type: string enum: - - flows:read - - flows:write + - projects:read + - projects:write + - jobs:read + - jobs:write - runs:read - - runs:write + - runs:invoke + - runs:cancel + - integrations:read + - integrations:write created_at: type: string expires_at: @@ -4271,7 +4276,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the jobs:read scope. An interactive owner session is required; bearer tokens cannot call this operation. operationId: get_api_v1_access_tokens @@ -4280,7 +4285,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: true post: summary: Create an access token @@ -4301,10 +4306,15 @@ paths: items: type: string enum: - - flows:read - - flows:write + - projects:read + - projects:write + - jobs:read + - jobs:write - runs:read - - runs:write + - runs:invoke + - runs:cancel + - integrations:read + - integrations:write created_at: type: string expires_at: @@ -4346,7 +4356,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the jobs:write scope. An interactive owner session is required; bearer tokens cannot call this operation. operationId: post_api_v1_access_tokens @@ -4355,7 +4365,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: true requestBody: required: true @@ -4372,12 +4382,23 @@ paths: minItems: 1 type: array items: - type: string - enum: - - flows:read - - flows:write - - runs:read - - runs:write + anyOf: + - type: string + enum: + - projects:read + - projects:write + - jobs:read + - jobs:write + - runs:read + - runs:invoke + - runs:cancel + - integrations:read + - integrations:write + - type: string + enum: + - flows:read + - flows:write + - runs:write expiryDays: anyOf: - type: number @@ -4417,7 +4438,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the jobs:write scope. An interactive owner session is required; bearer tokens cannot call this operation. operationId: delete_api_v1_access_tokens_tokenId @@ -4426,7 +4447,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: true parameters: - name: tokenId @@ -4462,7 +4483,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the jobs:write scope. An interactive owner session is required; bearer tokens cannot call this operation. operationId: delete_api_v1_access_authorized_clients_clientId @@ -4471,7 +4492,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: true parameters: - name: clientId @@ -4507,7 +4528,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: delete_api_v1_integrations_exe_connectionId @@ -4516,7 +4537,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: connectionId @@ -4552,7 +4573,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: delete_api_v1_integrations_amp_connectionId @@ -4561,7 +4582,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: connectionId @@ -4618,7 +4639,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: put_api_v1_integrations_cloudflare_tail_integrationId @@ -4627,7 +4648,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: integrationId @@ -4687,7 +4708,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: delete_api_v1_integrations_cloudflare_tail_integrationId @@ -4696,7 +4717,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: integrationId @@ -4738,7 +4759,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_integrations_cloudflare_tail_integrationId_test @@ -4747,7 +4768,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: integrationId @@ -4808,7 +4829,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_providers_github_installations_installationId_repositories @@ -4817,7 +4838,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false parameters: - name: installationId @@ -4898,7 +4919,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the integrations:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_providers_github_installations_installationId_repositories_repositoryId_issue_options @@ -4907,7 +4928,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: integrations:read x-owner-session-required: false parameters: - name: installationId @@ -4949,7 +4970,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: delete_api_v1_providers_github_installations_installationId @@ -4958,7 +4979,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: installationId @@ -4994,7 +5015,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the integrations:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_integrations_exe_connectionId_diagnostics @@ -5003,7 +5024,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: integrations:write x-owner-session-required: false parameters: - name: connectionId @@ -5018,7 +5039,7 @@ paths: description: |- Additive list representation, ordered by immutable UUID descending. Cursor is the last ID; filters must remain the same between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array. - Requires the flows:read scope. + Requires the jobs:read scope. Accepts a scoped bearer token or interactive owner session. responses: @@ -5129,7 +5150,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: false parameters: - name: projectId @@ -5228,7 +5249,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the jobs:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_job_selector @@ -5237,7 +5258,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: false parameters: - name: projectId @@ -5330,7 +5351,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the projects:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_projects @@ -5339,7 +5360,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: projects:read x-owner-session-required: false post: summary: Create project @@ -5393,7 +5414,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the projects:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_projects @@ -5402,7 +5423,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: projects:write x-owner-session-required: false requestBody: required: true @@ -5472,7 +5493,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the projects:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_projects_projectId @@ -5481,7 +5502,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: projects:read x-owner-session-required: false parameters: - name: projectId @@ -5542,7 +5563,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the projects:write scope. Accepts a scoped bearer token or interactive owner session. operationId: put_api_v1_projects_projectId @@ -5551,7 +5572,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: projects:write x-owner-session-required: false parameters: - name: projectId @@ -5603,7 +5624,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the projects:write scope. Accepts a scoped bearer token or interactive owner session. operationId: delete_api_v1_projects_projectId @@ -5612,7 +5633,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: projects:write x-owner-session-required: false parameters: - name: projectId @@ -6078,7 +6099,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the projects:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_jobs_jobId_project @@ -6087,7 +6108,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: projects:write x-owner-session-required: false parameters: - name: jobId @@ -6570,7 +6591,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the jobs:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_jobs @@ -6579,7 +6600,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: false post: summary: Create job @@ -7037,7 +7058,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the jobs:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_jobs @@ -7046,7 +7067,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: false requestBody: required: true @@ -7060,7 +7081,7 @@ paths: description: |- Evaluates supplied prepared webhook context only; does not authenticate the example, route events, verify GitHub state, or invoke jobs. - Requires the flows:write scope. + Requires the jobs:write scope. Accepts a scoped bearer token or interactive owner session. responses: @@ -7114,7 +7135,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: false requestBody: required: true @@ -7166,7 +7187,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the runs:write scope. + Requires the runs:invoke scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_jobs_jobId_invocations @@ -7175,7 +7196,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: runs:write + x-required-scope: runs:invoke x-owner-session-required: false parameters: - name: jobId @@ -7272,7 +7293,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the jobs:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_jobs_jobId_enable @@ -7281,7 +7302,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: false parameters: - name: jobId @@ -7317,7 +7338,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the jobs:write scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_jobs_jobId_disable @@ -7326,7 +7347,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: false parameters: - name: jobId @@ -7790,7 +7811,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:read scope. + Requires the jobs:read scope. Accepts a scoped bearer token or interactive owner session. operationId: get_api_v1_jobs_jobId @@ -7799,7 +7820,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:read + x-required-scope: jobs:read x-owner-session-required: false parameters: - name: jobId @@ -7813,7 +7834,7 @@ paths: description: |- Supply expectedUpdatedAt from GET for atomic optimistic concurrency. Stale edits return 409 stale_job. Omission preserves legacy REST/MCP last-writer-wins updates. Trigger identity is preserved. - Requires the flows:write scope. + Requires the jobs:write scope. Accepts a scoped bearer token or interactive owner session. responses: @@ -8276,7 +8297,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: false parameters: - name: jobId @@ -8622,7 +8643,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the flows:write scope. + Requires the jobs:write scope. Accepts a scoped bearer token or interactive owner session. operationId: delete_api_v1_jobs_jobId @@ -8631,7 +8652,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: flows:write + x-required-scope: jobs:write x-owner-session-required: false parameters: - name: jobId @@ -8774,7 +8795,7 @@ paths: description: |- Search uses PostgreSQL pg_trgm approximate matching over job names/slugs and run names, issue titles, and issue identifiers. Identifier matching is whole-field trigram matching; names and titles use word-level trigram matching. Exact identifiers and metadata names rank first, followed by the strongest individual field score. Results are unique, tenant-scoped, deterministically ordered, and limited to 100. Blank or punctuation-only queries return no results. One- and two-character queries may return no results because trigram matching is approximate; this is not ordered-character or substring matching. - Requires the runs:read scope. + Requires the jobs:read and runs:read scopes. Accepts a scoped bearer token or interactive owner session. responses: @@ -8882,7 +8903,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: runs:read + x-required-scope: jobs:read+runs:read x-owner-session-required: false parameters: - name: q @@ -9393,9 +9414,9 @@ paths: post: summary: Replay a retained trace artifact or restore a native-session projection description: |- - Requires runs:write and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run. + Requires runs:cancel and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run. - Requires the runs:write scope. + Requires the runs:cancel scope. An interactive owner session is required; bearer tokens cannot call this operation. responses: @@ -9413,7 +9434,7 @@ paths: description: Invalid owner session "403": $ref: "#/components/responses/Error403" - description: Missing runs:write scope or interactive owner session + description: Missing runs:cancel scope or interactive owner session "404": $ref: "#/components/responses/Error404" description: Run not found within the tenant @@ -9436,7 +9457,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: runs:write + x-required-scope: runs:cancel x-owner-session-required: true parameters: - name: runId @@ -9524,7 +9545,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the runs:write scope. + Requires the runs:cancel scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_runs_runId_stop @@ -9533,7 +9554,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: runs:write + x-required-scope: runs:cancel x-owner-session-required: false parameters: - name: runId @@ -9569,7 +9590,7 @@ paths: "503": $ref: "#/components/responses/Error503" description: |- - Requires the runs:write scope. + Requires the runs:cancel scope. Accepts a scoped bearer token or interactive owner session. operationId: post_api_v1_runs_runId_kill @@ -9578,7 +9599,7 @@ paths: security: - bearerAuth: [] - cookieAuth: [] - x-required-scope: runs:write + x-required-scope: runs:cancel x-owner-session-required: false parameters: - name: runId