diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 21842e3d..bb1d1697 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -4598,6 +4598,7 @@ export interface operations { credentialStatus: "connected"; /** @default [] */ accountTags: string[]; + tags?: string[]; /** @enum {string} */ agentKind?: "codex" | "claude" | "pi"; /** @default [] */ @@ -4842,6 +4843,7 @@ export interface operations { credentialStatus: "connected"; /** @default [] */ accountTags: string[]; + tags?: string[]; /** @enum {string} */ agentKind?: "codex" | "claude" | "pi"; /** @default [] */ @@ -4855,6 +4857,7 @@ export interface operations { credentialStatus: "connected"; /** @default [] */ accountTags: string[]; + tags?: string[]; /** @enum {string} */ agentKind?: "codex" | "claude" | "pi"; /** @default [] */ @@ -7670,10 +7673,11 @@ export interface operations { integrations: { /** Format: uuid */ id: string; + credentialId: string; name: string; description: string | null; /** @enum {string} */ - kind: "bearer" | "github" | "linear" | "model"; + kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x"; /** @enum {string} */ policy: "baseline" | "requestable" | "disabled"; available: boolean; @@ -7824,10 +7828,11 @@ export interface operations { integrations: { /** Format: uuid */ id: string; + credentialId: string; name: string; description: string | null; /** @enum {string} */ - kind: "bearer" | "github" | "linear" | "model"; + kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x"; /** @enum {string} */ policy: "baseline" | "requestable" | "disabled"; available: boolean; @@ -7876,10 +7881,11 @@ export interface operations { integrations: { /** Format: uuid */ id: string; + credentialId: string; name: string; description: string | null; /** @enum {string} */ - kind: "bearer" | "github" | "linear" | "model"; + kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x"; /** @enum {string} */ policy: "baseline" | "requestable" | "disabled"; available: boolean; diff --git a/packages/api/migrations/0059_all_proxy_integration_policies.sql b/packages/api/migrations/0059_all_proxy_integration_policies.sql new file mode 100644 index 00000000..12cffa63 --- /dev/null +++ b/packages/api/migrations/0059_all_proxy_integration_policies.sql @@ -0,0 +1,71 @@ +-- All outbound API credentials share the agent integration registry and policy. +-- Tail signing secrets authenticate inbound webhooks and are deliberately excluded. +ALTER TABLE app.agent_integrations DROP CONSTRAINT agent_integrations_kind_check; +ALTER TABLE app.agent_integrations ADD CONSTRAINT agent_integrations_kind_check + CHECK(kind IN ('bearer','github','linear','model','fly','exe','amp','clickup','x')); + +CREATE FUNCTION app.agent_connection_changed() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE + t uuid; connection_kind text; k text; c text; n text; d text; +BEGIN + IF TG_OP='DELETE' THEN t=OLD.tenant_id; connection_kind=OLD.kind; + ELSE t=NEW.tenant_id; connection_kind=NEW.kind; END IF; + IF connection_kind IN ('linear','clickup') THEN + k=connection_kind; c=connection_kind; + n=CASE k WHEN 'linear' THEN 'Linear' ELSE 'ClickUp' END; + d=CASE k WHEN 'linear' THEN 'Linear GraphQL API' ELSE 'ClickUp API' END; + ELSIF connection_kind LIKE 'exe:%' THEN + k='exe'; c=substring(connection_kind FROM 5); n='exe.dev · '||c; d='exe.dev account API'; + ELSIF connection_kind LIKE 'amp:%' THEN + k='amp'; c=substring(connection_kind FROM 5); n='Amp · '||c; d='Amp project API'; + ELSE RETURN NULL; + END IF; + PERFORM app.sync_agent_integration(t,k,c,n,d,TG_OP<>'DELETE'); + RETURN NULL; +END; +$$; +DROP TRIGGER agent_linear_sync ON app.connections; +CREATE TRIGGER agent_connection_sync AFTER INSERT OR UPDATE OR DELETE ON app.connections + FOR EACH ROW EXECUTE FUNCTION app.agent_connection_changed(); + +CREATE FUNCTION app.agent_fly_changed() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='DELETE' THEN + PERFORM app.sync_agent_integration(OLD.tenant_id,'fly','fly','Fly.io · '||OLD.organization_name,'Fly Machines API',false); + ELSE + -- Switching organizations revokes prior approvals, just like disconnecting. + IF TG_OP='UPDATE' AND OLD.organization_slug<>NEW.organization_slug THEN + PERFORM app.sync_agent_integration(OLD.tenant_id,'fly','fly','Fly.io · '||OLD.organization_name,'Fly Machines API',false); + END IF; + PERFORM app.sync_agent_integration(NEW.tenant_id,'fly','fly','Fly.io · '||NEW.organization_name,'Fly Machines API',true); + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER agent_fly_sync AFTER INSERT OR UPDATE OR DELETE ON app.fly_connections + FOR EACH ROW EXECUTE FUNCTION app.agent_fly_changed(); + +INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available) + SELECT tenant_id, + CASE WHEN kind='clickup' THEN 'clickup' WHEN kind LIKE 'exe:%' THEN 'exe' ELSE 'amp' END, + CASE WHEN kind='clickup' THEN kind ELSE substring(kind FROM 5) END, + CASE WHEN kind='clickup' THEN 'ClickUp' WHEN kind LIKE 'exe:%' THEN 'exe.dev · '||substring(kind FROM 5) ELSE 'Amp · '||substring(kind FROM 5) END, + CASE WHEN kind='clickup' THEN 'ClickUp API' WHEN kind LIKE 'exe:%' THEN 'exe.dev account API' ELSE 'Amp project API' END,true + FROM app.connections WHERE kind='clickup' OR kind LIKE 'exe:%' OR kind LIKE 'amp:%'; +INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available) + SELECT tenant_id,'fly','fly','Fly.io · '||organization_name,'Fly Machines API',true FROM app.fly_connections; +CREATE FUNCTION app.agent_x_changed() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='DELETE' THEN + PERFORM app.sync_agent_integration(OLD.tenant_id,'x',OLD.id::text,'X · '||OLD.name,'X API v2',false); + ELSE + PERFORM app.sync_agent_integration(NEW.tenant_id,'x',NEW.id::text,'X · '||NEW.name,'X API v2',NEW.status='connected'); + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER agent_x_sync AFTER INSERT OR UPDATE OR DELETE ON app.x_connections + FOR EACH ROW EXECUTE FUNCTION app.agent_x_changed(); +INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available) + SELECT tenant_id,'x',id::text,'X · '||name,'X API v2',status='connected' FROM app.x_connections; +INSERT INTO app.schema_migrations(version) VALUES ('0059_all_proxy_integration_policies') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/agent-api-contracts.ts b/packages/api/src/agent-api-contracts.ts index 4d19a01a..0be22e46 100644 --- a/packages/api/src/agent-api-contracts.ts +++ b/packages/api/src/agent-api-contracts.ts @@ -3,7 +3,7 @@ export const integrationScopePattern = /^integration:([0-9a-f]{8}-[0-9a-f]{4}-[0 export const isIntegrationScope = (scope: string) => integrationScopePattern.test(scope); export const integrationRef = z.uuid(); export const apiPolicyInput = z.object({ policy: z.enum(["baseline", "requestable", "disabled"]), expectedRevision: z.number().int().positive() }).strict(); -export const apiPolicy = z.object({ id: integrationRef, name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model"]), policy: z.enum(["baseline", "requestable", "disabled"]), available: z.boolean(), revision: z.number().int(), requiredScope: z.string() }); +export const apiPolicy = z.object({ id: integrationRef, credentialId: z.string(), name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model", "fly", "exe", "amp", "clickup", "x"]), policy: z.enum(["baseline", "requestable", "disabled"]), available: z.boolean(), revision: z.number().int(), requiredScope: z.string() }); export const apiPolicyList = z.object({ integrations: z.array(apiPolicy) }); export const apiReflection = z.object({ identity: z.object({ id: z.uuid(), kind: z.enum(["oauth", "run"]) }), scopes: z.array(z.string()), integrations: z.array(apiPolicy.extend({ access: z.enum(["granted", "requestable", "unavailable"]), instructions: z.string() })) }); export const requestApiInput = z.object({ diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index 50de865e..bf4a3b70 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -12,12 +12,12 @@ import type { z } from "zod"; export class AgentApiError extends Error { constructor(readonly status: number, readonly code: string, message: string, readonly scope?: string) { super(message); } } -export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number}; +export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear" | "fly" | "exe" | "amp" | "clickup" | "x"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number}; export const requiredIntegrationScope = (row: AgentIntegration) => `integration:${row.id}:${row.epoch}`; const STORAGE_BLOCK_BYTES = 1024 * 1024; const forbidden = () => new AgentApiError(403, "forbidden", "This integration is not authorized."); const invalidIdentity = () => new AgentApiError(401, "invalid_token", "The agent authorization is no longer active."); -const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, name: row.name, description: row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) }); +const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, credentialId: row.credential_id, name: row.name, description: row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) }); /** Restrict the generic X v2 proxy to resources with an explicit OAuth-scope * mapping. Unsupported resources and credential-management routes fail closed. */ @@ -83,8 +83,11 @@ export class AgentApiService { case "bearer": return Array.isArray(config.portableIntegrationIds) && config.portableIntegrationIds.includes(row.credential_id); case "github": return Array.isArray(config.githubInstallationIds) && config.githubInstallationIds.includes(Number(row.credential_id)); case "linear": return config.linearConnectionId === "linear"; + case "x": return Array.isArray(config.xConnectionIds) && config.xConnectionIds.includes(row.credential_id); case "model": return config.modelAccess === "portable" && config.modelAccountId === row.credential_id; } + // Execution-provider credentials are not implicitly selected by a run. + return false; } async authorize(integration: string) { const identity = await this.identity(); @@ -111,12 +114,13 @@ export class AgentApiService { if (!(error instanceof AgentApiError) || error.status === 401) throw error; access = error.code === "insufficient_scope" ? "requestable" : "unavailable"; } - result.push({...publicIntegration(row), access, instructions: row.kind === "linear" ? "Use request_api with path /graphql and a JSON GraphQL body." : row.kind === "model" ? "Use request_api with an OpenAI-compatible path relative to /v1." : "Use request_api with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions."}); + result.push({...publicIntegration(row), access, instructions: row.kind === "x" ? "Use request_api with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use request_api with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use request_api with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use request_api with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use request_api with a path relative to /api/v2." : row.kind === "fly" ? "Use request_api with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use request_api with an OpenAI-compatible path relative to /v1." : "Use request_api with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions."}); } return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes), integrations: result}; } async forward(integration: string, path: string, request: Request) { const grant = await this.authorize(integration); + if (grant.integration.kind === "x") return this.forwardX(grant.integration.credential_id, path, request); let credential; try { credential = await resolveAgentCredential(this.env, this.auth.tenantId, grant.integration.kind, grant.integration.credential_id, path); } catch { throw new AgentApiError(502, "credential_unavailable", "The upstream credential could not be resolved."); } @@ -129,7 +133,14 @@ export class AgentApiService { } async forwardX(connectionId: string, path: string, request: Request) { const identity = await this.identity(); - if (identity.kind !== "run" || !Array.isArray(identity.config?.xConnectionIds) || !identity.config.xConnectionIds.includes(connectionId)) throw forbidden(); + let apiGrant: {integration: AgentIntegration} | undefined; + if (identity.kind === "run") { + if (!Array.isArray(identity.config?.xConnectionIds) || !identity.config.xConnectionIds.includes(connectionId)) throw forbidden(); + } else { + const row = (await this.database.pool.query<{id: string}>("SELECT id FROM app.agent_integrations WHERE tenant_id=$1 AND kind='x' AND credential_id=$2", [this.auth.tenantId, connectionId])).rows[0]; + if (!row) throw forbidden(); + apiGrant = await this.authorize(row.id); + } const required = xRequiredScope(path, request.method); if (!required) throw forbidden(); const repository = new XConnectionRepository(this.database, this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); @@ -159,7 +170,11 @@ export class AgentApiService { if (!accessToken) throw forbidden(); const currentIdentity = await this.identity(); const current = await repository.get(connectionId); - if (currentIdentity.kind !== "run" || !Array.isArray(currentIdentity.config?.xConnectionIds) || !currentIdentity.config.xConnectionIds.includes(connectionId) || current?.status !== "connected" || !current.scopes.includes(required) || !current.grantedScopes.includes(required)) throw forbidden(); + if (apiGrant) { + const currentGrant = await this.authorize(apiGrant.integration.id); + if (currentGrant.integration.epoch !== apiGrant.integration.epoch) throw forbidden(); + } else if (currentIdentity.kind !== "run" || !Array.isArray(currentIdentity.config?.xConnectionIds) || !currentIdentity.config.xConnectionIds.includes(connectionId)) throw forbidden(); + if (current?.status !== "connected" || !current.scopes.includes(required) || !current.grantedScopes.includes(required)) throw forbidden(); try { return await forwardRunOutbound(request, { origin: "https://api.x.com", path: path, credential: accessToken }); } catch { throw new AgentApiError(502, "proxy_failed", "The X API request failed. Check X API access, credits, and rate limits, then retry if safe."); } } diff --git a/packages/api/src/agent-credentials.ts b/packages/api/src/agent-credentials.ts index 7ed7d5c6..aee25b57 100644 --- a/packages/api/src/agent-credentials.ts +++ b/packages/api/src/agent-credentials.ts @@ -4,11 +4,40 @@ import { CredentialRepository } from "./postgres/credential-repository"; import { resolveRunProviderCredentials } from "./provider-credentials"; import type { OutboundCredential } from "./run-outbound-forwarder"; import { resolveManagedModelCredential } from "./managed-model-credentials"; +import { CLICKUP_API_BASE } from "./clickup"; +import { ConnectionRepository } from "./postgres/connection-repository"; +import { FlyConnectionRepository } from "./postgres/fly-connection-repository"; import { isPublicHttpsOrigin } from "./public-address"; /** Only call after shared identity/grant authorization. No caller origin or secret. */ export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string): Promise { const database = databaseFor(env); + if (kind === "fly") { + if (credentialId !== "fly") return null; + const token = await new FlyConnectionRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY).token(); + return token ? {origin: "https://api.machines.dev", path: relativePath, credential: token} : null; + } + if (kind === "exe" || kind === "amp" || kind === "clickup") { + if (kind === "clickup" && credentialId !== "clickup") return null; + const connection = await new ConnectionRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY) + .get<{apiToken?: string; accessToken?: string; apiBaseUrl?: string}>(kind === "clickup" ? kind : `${kind}:${credentialId}`); + const credential = kind === "exe" ? connection?.apiToken : connection?.accessToken; + if (!credential) return null; + if (kind === "exe") return {origin: "https://exe.dev", path: relativePath, credential}; + if (kind === "clickup") { + const base = new URL(CLICKUP_API_BASE), target = new URL(`${CLICKUP_API_BASE}${relativePath}`); + if (!target.pathname.startsWith(`${base.pathname}/`)) return null; + return {origin: target.origin, path: `${target.pathname}${target.search}`, credential, authorization: "raw"}; + } + const base = new URL(connection?.apiBaseUrl || "https://ampcode.com/api/cloud/v1"); + if (!isPublicHttpsOrigin(base.origin, env.APP_ORIGIN) || base.username || base.password || base.search || base.hash) return null; + const prefix = base.pathname.replace(/\/$/, ""); + const target = new URL(`${base.origin}${prefix}${relativePath}`); + // Relative dot segments must not escape the configured API prefix. + if (!target.pathname.startsWith(`${prefix}/`)) return null; + return {origin: base.origin, path: `${target.pathname}${target.search}`, credential}; + } + if (!["bearer", "github", "linear", "model"].includes(kind)) return null; const modelAccountId = credentialId; const prefix = kind === "bearer" ? `/integrations/${credentialId}` : kind === "github" ? `/providers/github/${credentialId}` : kind === "linear" ? "/providers/linear" : "/providers/model/v1"; const separator = relativePath.indexOf("?"); diff --git a/packages/api/src/clickup.ts b/packages/api/src/clickup.ts index f117d2a1..28fae9d6 100644 --- a/packages/api/src/clickup.ts +++ b/packages/api/src/clickup.ts @@ -12,10 +12,12 @@ export function matchingClickUpTask(task: ClickUpTask, listId: string, rules: Ma }); } +export const CLICKUP_API_BASE = "https://api.clickup.com/api/v2"; + export const clickUpHeaders = (token: string) => ({ Authorization: token, "Content-Type": "application/json" }); export async function clickUpJson(token: string, path: string): Promise { - const response = await fetch(`https://api.clickup.com/api/v2${path}`, { headers: clickUpHeaders(token) }); + const response = await fetch(`${CLICKUP_API_BASE}${path}`, { headers: clickUpHeaders(token) }); const body = await response.json().catch(() => ({})) as any; if (!response.ok) throw new Error(body.err ?? body.error ?? `ClickUp request failed (${response.status})`); return body; diff --git a/packages/api/src/postgres/integration-service.ts b/packages/api/src/postgres/integration-service.ts index c99f39c4..3d89b1f7 100644 --- a/packages/api/src/postgres/integration-service.ts +++ b/packages/api/src/postgres/integration-service.ts @@ -92,7 +92,7 @@ export class IntegrationService { const connectionsPromise = this.connections.all(["linear", "clickup", "exe:", "amp:", "cloudflare-tail:"]); const [connections, tails] = await Promise.all([connectionsPromise, this.tails(connectionsPromise)]); const linear = connections.get("linear"), clickup = connections.get("clickup"); - const exeConnections = [...connections].filter(([kind]) => kind.startsWith("exe:")).map(([kind, value]) => { const agentKind = value?.agentKind; return { connectionId: kind.slice(4), credentialStatus: "connected" as const, accountTags: selectableExeTags(value ?? {}), ...(agentKind ? { agentKind } : {}), models: (agentKind && (value?.modelsByAgent?.[agentKind] ?? value?.models)) ?? [], efforts: agentKind ? effortOptions[agentKind as keyof typeof effortOptions] ?? [] : [] }; }); + const exeConnections = [...connections].filter(([kind]) => kind.startsWith("exe:")).map(([kind, value]) => { const agentKind = value?.agentKind; return { connectionId: kind.slice(4), credentialStatus: "connected" as const, accountTags: selectableExeTags(value ?? {}), tags: selectableExeTags({ tags: value?.tags }), ...(agentKind ? { agentKind } : {}), models: (agentKind && (value?.modelsByAgent?.[agentKind] ?? value?.models)) ?? [], efforts: agentKind ? effortOptions[agentKind as keyof typeof effortOptions] ?? [] : [] }; }); const ampConnections = [...connections].filter(([kind]) => kind.startsWith("amp:")).map(([kind, value]) => ({ connectionId: kind.slice(4), project: text(value?.project) ?? "Unnamed Amp project", ...(text(value?.apiBaseUrl) ? { apiBaseUrl: text(value.apiBaseUrl) } : {}) })); return { linear: linear ? { organizationName: text(linear.organizationName) ?? null, viewerEmail: text(linear.viewerEmail) ?? null } : null, clickup: clickup ? { teamName: text(clickup.teamName) ?? null } : null, exe: exeConnections[0] ?? null, exeConnections, ampConnections, cloudflareTail: { count: tails.length, installations: tails } }; } diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index f45f0f48..031725e3 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -65,7 +65,7 @@ export const xOAuthAttempts = app.table("x_oauth_attempts", { }, t => [primaryKey({ columns: [t.tenantId, t.nonce] }), foreignKey({ columns: [t.tenantId, t.connectionId], foreignColumns: [xConnections.tenantId, xConnections.id] }).onDelete("cascade"), index("x_oauth_attempt_expiry").on(t.expiresAt)]); export const agentIntegrations = app.table("agent_integrations", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, {onDelete:"cascade"}), id: uuid("id").notNull().defaultRandom(), - kind: text("kind").$type<"bearer"|"github"|"linear"|"model">().notNull(), credentialId: text("credential_id").notNull(), name:text("name").notNull(), description:text("description"), available:boolean("available").notNull(), + kind: text("kind").$type<"bearer"|"github"|"linear"|"model"|"fly"|"exe"|"amp"|"clickup"|"x">().notNull(), credentialId: text("credential_id").notNull(), name:text("name").notNull(), description:text("description"), available:boolean("available").notNull(), policy:text("policy").$type<"baseline"|"requestable"|"disabled">().notNull().default("requestable"),epoch:integer("epoch").notNull().default(1),revision:integer("revision").notNull().default(1), },t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.credentialId)]); export const agentIdentities = app.table("agent_identities", { diff --git a/packages/api/src/run-outbound-forwarder.ts b/packages/api/src/run-outbound-forwarder.ts index 4ee0101f..21afc165 100644 --- a/packages/api/src/run-outbound-forwarder.ts +++ b/packages/api/src/run-outbound-forwarder.ts @@ -3,7 +3,7 @@ * Destinations and credentials are resolved server-side before this function. */ export type OutboundCredential = { origin: string; path: string; credential: string; - authorization?: "bearer" | "github-git-basic"; + authorization?: "bearer" | "github-git-basic" | "raw"; headers?: Record; }; const hop = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"]); @@ -44,7 +44,7 @@ export async function forwardRunOutbound(request: Request, selected: OutboundCre target.pathname = separator < 0 ? selected.path : selected.path.slice(0, separator); target.search = separator < 0 ? "" : selected.path.slice(separator); const headers = filteredHeaders(request.headers, true); - headers.set("Authorization", selected.authorization === "github-git-basic" ? `Basic ${btoa(`x-access-token:${selected.credential}`)}` : `Bearer ${selected.credential}`); + headers.set("Authorization", selected.authorization === "github-git-basic" ? `Basic ${btoa(`x-access-token:${selected.credential}`)}` : selected.authorization === "raw" ? selected.credential : `Bearer ${selected.credential}`); headers.set("Accept-Encoding", "identity"); headers.set("User-Agent", "Factorize-Run-Proxy"); for (const [name, value] of Object.entries(selected.headers ?? {})) headers.set(name, value); diff --git a/packages/api/src/settings-contracts.ts b/packages/api/src/settings-contracts.ts index ddd4ff20..5afb73fc 100644 --- a/packages/api/src/settings-contracts.ts +++ b/packages/api/src/settings-contracts.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import { ACCESS_SCOPES } from "./access-tokens"; import { tailIntegration } from "./editor-contracts"; const timestamp = z.string(); -export const exeConnection = z.object({ connectionId: z.string(), credentialStatus: z.literal("connected"), accountTags: z.array(z.string()).default([]), agentKind: z.enum(["codex", "claude", "pi"]).optional(), models: z.array(z.string()).default([]), efforts: z.array(z.string()).default([]) }); +export const exeConnection = z.object({ connectionId: z.string(), credentialStatus: z.literal("connected"), accountTags: z.array(z.string()).default([]), tags: z.array(z.string()).optional(), agentKind: z.enum(["codex", "claude", "pi"]).optional(), models: z.array(z.string()).default([]), efforts: z.array(z.string()).default([]) }); 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() }); diff --git a/packages/api/test/loading-parallel.test.ts b/packages/api/test/loading-parallel.test.ts index f59cff85..72d78d78 100644 --- a/packages/api/test/loading-parallel.test.ts +++ b/packages/api/test/loading-parallel.test.ts @@ -35,11 +35,12 @@ describe("independent loading", () => { it("keeps configured exe.dev tags visible when inventory refresh omits them", async () => { vi.spyOn(ConnectionRepository.prototype, "all").mockResolvedValue(new Map([ - ["exe:vm", { availableTags: ["current"], tags: ["anarack", "current"], agentKind: "codex" }], + ["exe:vm", { availableTags: ["current", "unselected"], tags: ["anarack", "current"], agentKind: "codex" }], ])); vi.spyOn(IntegrationService.prototype, "tails").mockResolvedValue([]); const result = await new IntegrationService({ pool: { query: vi.fn(async () => ({ rows: [] })) } } as any, "tenant", "key").status(); - expect(result.exeConnections[0].accountTags).toEqual(["anarack", "current"]); + expect(result.exeConnections[0].accountTags).toEqual(["anarack", "current", "unselected"]); + expect(result.exeConnections[0].tags).toEqual(["anarack", "current"]); }); it("propagates a failed integration read without leaving an unhandled sibling promise", async () => { vi.spyOn(ConnectionRepository.prototype, "all").mockRejectedValue(new Error("Connection read failed")); diff --git a/packages/api/test/pages-smoke.e2e.test.ts b/packages/api/test/pages-smoke.e2e.test.ts index 56425fbb..c523a154 100644 --- a/packages/api/test/pages-smoke.e2e.test.ts +++ b/packages/api/test/pages-smoke.e2e.test.ts @@ -75,8 +75,8 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("every page E2E smoke", () "run info": { path: () => run() + "/info", ready: info }, "legacy run context": { path: () => run() + "/context", destination: () => run() + "/info", ready: info }, "legacy run settings": { path: () => run() + "/settings", destination: () => run() + "/info", ready: info }, - "settings": { path: () => "/settings", ready: heading("Bearer integrations") }, - "integrations": { path: () => "/settings/integrations", ready: heading("Model accounts") }, + "settings": { path: () => "/settings", ready: heading("Your integrations") }, + "integrations": { path: () => "/settings/integrations", ready: heading("Available integrations") }, "API keys": { path: () => "/settings/api-keys", ready: heading("API keys") }, "create API key": { path: () => "/settings/api-keys/new", ready: label("Key name") }, "authorized clients": { path: () => "/settings/authorized-clients", ready: heading("Authorized clients") }, diff --git a/packages/app/src/features/settings/api-policies.tsx b/packages/app/src/features/settings/api-policies.tsx index 5ff9a841..442a5edb 100644 --- a/packages/app/src/features/settings/api-policies.tsx +++ b/packages/app/src/features/settings/api-policies.tsx @@ -1,21 +1,49 @@ +import { createContext, useContext, useState, type ReactNode } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; -import { Card, Label } from "../../shared/ui"; +import { Input, Label, Select } from "../../shared/ui"; +import { Dialog } from "../../shared/dialog"; import { messageOf } from "../auth/session"; -export function ApiPolicies() { +type Policy = {id: string; credentialId: string; kind: string; name: string; available: boolean; revision: number; policy: "baseline" | "requestable" | "disabled"}; +const queryKey = ["settings", "api-policies"]; +function usePolicies() { const cache = useQueryClient(); - const policies = useQuery({queryKey:["settings","api-policies"],queryFn:async ({signal}) => { - const {data,error} = await api.GET("/api/v1/integration-api-policies",{signal}); - if (!data || error) throw new Error(messageOf(error)); return data; + const query = useQuery({queryKey, queryFn: async ({signal}) => { + const {data,error} = await api.GET("/api/v1/integration-api-policies", {signal}); + if (!data || error) throw new Error(messageOf(error)); + if (!Array.isArray(data.integrations)) throw new Error("API access settings could not be loaded. Reload the page to try again."); + return data; }}); - const change = useMutation({retry:false,mutationFn:async (input:{id:string;revision:number;policy:"baseline"|"requestable"|"disabled"}) => { - const {data,error} = await api.PUT("/api/v1/integration-api-policies/{integrationId}",{params:{path:{integrationId:input.id}},body:{policy:input.policy,expectedRevision:input.revision}}); + const change = useMutation({retry: false, mutationFn: async (input: {row: Policy; policy: Policy["policy"]}) => { + const {data,error} = await api.PUT("/api/v1/integration-api-policies/{integrationId}", {params: {path: {integrationId: input.row.id}}, body: {policy: input.policy, expectedRevision: input.row.revision}}); if (!data || error) throw new Error(messageOf(error)); return data; - },onSuccess:data=>cache.setQueryData(["settings","api-policies"],data),onSettled:()=>cache.invalidateQueries({queryKey:["settings","api-policies"]})}); - return

MCP API access

Baseline APIs are available immediately to every connected MCP client. Requestable APIs require separate approval for each connection. Disabling access or disconnecting an integration invalidates its approvals; re-enabling requires fresh consent. Runs keep their own selected connections.

- {policies.isPending &&

Loading API policies…

} - {[policies.error,change.error].filter(Boolean).map((error,i)=>

{error?.message}

)} - {policies.data?.integrations.map(row=>{row.description &&

{row.description}

}
)} -
; + }, onSuccess: data => cache.setQueryData(queryKey, data), onSettled: () => cache.invalidateQueries({queryKey})}); + // Read these fields in the subscribing component so context consumers receive query updates. + return {query: {data: query.data, isPending: query.isPending, error: query.error}, change}; +} +const PoliciesContext = createContext | null>(null); +export function IntegrationPoliciesProvider({children}: {children: ReactNode}) { + const policies = usePolicies(); + return {policies.query.error &&

MCP access settings: {policies.query.error.message}

}{children}
; +} +export function useIntegrationPolicy(kind: string, credentialId: string) { + const context = useContext(PoliciesContext); + const row = context?.query.data?.integrations.find(row => row.kind === kind && row.credentialId === credentialId); + return {context, row}; +} +export function IntegrationPolicy({kind, credentialId, name}: {kind: string; credentialId: string; name: string}) { + const {context, row} = useIntegrationPolicy(kind, credentialId); + const [desired, setDesired] = useState(null); + if (kind === "tail") return Inbound webhook; + if (!context || context.query.isPending) return Loading API access…; + if (!row) return API access unavailable; + const current = context.change.variables?.row.id === row.id; + const error = current ? context.change.error : null; + return
{desired !== null &&

Saving API access…

}{row.policy === "disabled" &&

MCP access disabled

}{error &&

{error.message}

}
; +} +export function PolicyDialog({kind, credentialId, close}: {kind: string; credentialId: string; close: () => void}) { + const {context, row} = useIntegrationPolicy(kind, credentialId); + if (!context || !row) return null; + return

Default access applies to connected MCP clients. Requiring approval keeps existing approvals. Disabling access revokes approvals; enabling it again requires fresh consent. Job selections are independent.

{context.change.variables?.row.id === row.id && context.change.error &&

{context.change.error.message}

}
; } diff --git a/packages/app/src/features/settings/bearer-integrations.tsx b/packages/app/src/features/settings/bearer-integrations.tsx index 8a7ea399..46a56faa 100644 --- a/packages/app/src/features/settings/bearer-integrations.tsx +++ b/packages/app/src/features/settings/bearer-integrations.tsx @@ -1,9 +1,12 @@ import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; -import { Button, Card, Input, Label } from "../../shared/ui"; +import { Button, Input, Label } from "../../shared/ui"; import { messageOf } from "../auth/session"; +import { Dialog } from "../../shared/dialog"; +import { IntegrationRow, ProviderTile } from "./integration-ui"; + type BearerRecord = { id: string; name: string; origin: string; description: string | null; revision: number }; const recordsQuery = { queryKey: ["settings", "bearer-integrations"], queryFn: async ({ signal }: { signal: AbortSignal }) => { const { data, error } = await api.GET("/api/v1/integrations/bearer", { signal }); @@ -29,9 +32,10 @@ function validOrigin(value: string): boolean { } catch { return false; } } -export function BearerIntegrations() { +export function useBearerIntegrations() { const cache = useQueryClient(), records = useQuery(recordsQuery); const [editing, setEditing] = useState(null), [name, setName] = useState(""), [origin, setOrigin] = useState(""), [description, setDescription] = useState(""), [token, setToken] = useState(""); + const [open, setOpen] = useState(false); const [notice, setNotice] = useState(""); const clearFields = () => { setToken(""); }; const save = useMutation({ retry: false, mutationFn: async () => { @@ -50,27 +54,31 @@ export function BearerIntegrations() { const { data, error } = await api.POST("/api/v1/integrations/bearer", { body: { ...body, id } }); if (!data || error) throw new Error(messageOf(error)); return data; - }, onSuccess: async () => { clearFields(); setNotice("Saved integration in Factorize managed encrypted storage."); setEditing(null); setName(""); setOrigin(""); setDescription(""); await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); }, onError: async error => { clearFields(); setNotice(error.message); if (error.message.includes("changed") || error.message.includes("revision")) await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); } }); + }, onSuccess: async () => { clearFields(); setNotice("Bearer integration saved."); setOpen(false); setEditing(null); setName(""); setOrigin(""); setDescription(""); await cache.invalidateQueries({ queryKey: ["settings"] }); }, onError: async error => { clearFields(); setNotice(error.message); if (error.message.includes("changed") || error.message.includes("revision")) await cache.invalidateQueries({ queryKey: ["settings"] }); } }); const remove = useMutation({ retry: false, mutationFn: async (record: BearerRecord) => { const { data, error } = await api.DELETE("/api/v1/integrations/bearer/{integrationId}", { params: { path: { integrationId: record.id } }, body: { expectedRevision: records.data?.revision ?? 0, idempotencyKey: crypto.randomUUID() } }); if (!data || error) throw new Error(messageOf(error)); return data; - }, onSuccess: async () => { setNotice("Integration deleted."); await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); }, onError: async error => { setNotice(error.message); await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); } }); - const beginEdit = (record: BearerRecord) => { clearFields(); setNotice(""); setEditing(record.id); setName(record.name); setOrigin(record.origin); setDescription(record.description ?? ""); }; + }, onSuccess: async () => { setNotice("Integration deleted."); await cache.invalidateQueries({ queryKey: ["settings"] }); }, onError: async error => { setNotice(error.message); await cache.invalidateQueries({ queryKey: ["settings"] }); } }); + const beginEdit = (record: BearerRecord) => { setOpen(true); clearFields(); setNotice(""); setEditing(record.id); setName(record.name); setOrigin(record.origin); setDescription(record.description ?? ""); }; const reset = () => { clearFields(); setEditing(null); setName(""); setOrigin(""); setDescription(""); setNotice(""); }; - return
-

Bearer integrations

Factorize encrypts credentials before storing them. Stored tokens cannot be viewed; edit to replace one.

- {records.isPending &&

Loading bearer integrations…

}{records.error &&

{records.error.message}

} - {records.data?.integrations.map(record =>

{record.name}

{record.origin}

{record.description &&

{record.description}

}

Bearer token stored encrypted

)} -

{editing ? "Edit bearer integration" : "Add bearer integration"}

-
{ event.preventDefault(); setNotice(""); save.mutate(); }}> + return { + count: records.data?.integrations.length ?? 0, pending: records.isPending, + rows: records.data?.integrations.map(record => beginEdit(record)}, + {label: "Delete", destructive: true, disabled: remove.isPending, onClick: () => {if (window.confirm(`Delete ${record.name}?`)) remove.mutate(record);}}, + ]} />), + tile: {reset(); setOpen(true);}} />, + feedback: <>{records.error &&

{records.error.message}

}{notice && !open &&

{notice}

}, + dialog: open && {reset(); setOpen(false);}}> +

Stored tokens cannot be viewed. Editing requires a replacement token.

+ {event.preventDefault(); setNotice(""); save.mutate();}}> -
{editing && }
- -
- {notice &&

{notice}

} -
; +
+ {notice &&

{notice}

} + , + }; } diff --git a/packages/app/src/features/settings/fly.tsx b/packages/app/src/features/settings/fly.tsx index f346eaa3..6b5b7f8c 100644 --- a/packages/app/src/features/settings/fly.tsx +++ b/packages/app/src/features/settings/fly.tsx @@ -1,9 +1,12 @@ import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; -import { Button, Card, Input, Label, Select } from "../../shared/ui"; +import { Button, Input, Label, Select } from "../../shared/ui"; import { messageOf } from "../auth/session"; +import { Dialog } from "../../shared/dialog"; +import { IntegrationRow, ProviderTile } from "./integration-ui"; + export const flyConnectionQuery = { queryKey: ["settings", "fly"], queryFn: async ({ signal }: { signal: AbortSignal }) => { const { data, error } = await api.GET("/api/v1/fly/connection", { signal }); if (!data || error) throw new Error(messageOf(error)); return data.connection; @@ -12,27 +15,35 @@ export const flyConfigurationsQuery = { queryKey: ["editor", "fly-configurations const { data, error } = await api.GET("/api/v1/fly/execution-configurations", { signal }); if (!data || error) throw new Error(messageOf(error)); return data.configurations; } }; -export function FlyIntegration() { +export function useFlyIntegration() { const cache = useQueryClient(), connection = useQuery(flyConnectionQuery); + const [open, setOpen] = useState(false); const [token, setToken] = useState(""), [organizationSlug, setOrganizationSlug] = useState(""); const action = useMutation({ retry: false, mutationFn: async (kind: "verify" | "save" | "disconnect") => { const body = { token, organizationSlug: organizationSlug || connection.data?.organizationSlug || "" }; const result = kind === "verify" ? await api.POST("/api/v1/fly/connection/test", { body }) : kind === "save" ? await api.PUT("/api/v1/fly/connection", { body }) : await api.DELETE("/api/v1/fly/connection"); if (!result.data || result.error) throw new Error(messageOf(result.error)); return kind; - }, onSuccess: async kind => { if (kind !== "verify") { setToken(""); await cache.invalidateQueries({ queryKey: ["settings", "fly"] }); await cache.invalidateQueries({ queryKey: ["editor"] }); } } }); - return

Fly.io

Run jobs on Fly Machines in your organization.

- {connection.isPending &&

Loading Fly.io connection…

} - {connection.data &&

Connected to {connection.data.organizationName} ({connection.data.organizationSlug})

} -
{ event.preventDefault(); action.mutate("save"); }}> - - -

Use an organization deploy token with Machines permissions. Enter the token to verify or replace the connection. Verification checks credentials without launching a VM.

-
{connection.data && }
-
- {action.isSuccess &&

{action.data === "verify" ? "Fly.io connection verified." : action.data === "save" ? "Fly.io integration saved." : "Fly.io disconnected."}

} - {[connection.error, action.error].filter(Boolean).map((error, index) =>

{error?.message}

)} -
; + }, onSuccess: async kind => { if (kind !== "verify") { setToken(""); setOpen(false); await cache.invalidateQueries({ queryKey: ["settings"] }); await cache.invalidateQueries({ queryKey: ["editor"] }); } } }); + const close = () => {setToken(""); setOrganizationSlug(""); setOpen(false); action.reset();}; + return { + count: connection.data ? 1 : 0, pending: connection.isPending, + rows: connection.data ? [ {action.reset(); setOpen(true);}}, + {label: "Disconnect", destructive: true, disabled: action.isPending, onClick: () => {if (window.confirm("Disconnect Fly.io? Jobs using this connection will no longer run.")) action.mutate("disconnect");}}, + ]} />] : [], + tile: {action.reset(); setOpen(true);}} />, + feedback: <>{connection.error &&

{connection.error.message}

}{!open && action.error &&

{action.error.message}

}{!open && action.isSuccess &&

{action.data === "save" ? "Fly.io integration saved." : "Fly.io disconnected."}

}, + dialog: open && +
{event.preventDefault(); action.mutate("save");}}> + + +

Use an organization deploy token with Machines permissions. Enter the token to verify or replace the connection. Verification checks credentials without launching a VM.

+
+
+ {action.isSuccess && action.data === "verify" &&

Fly.io connection verified.

}{action.error &&

{action.error.message}

} +
, + }; } type Configuration = { name: string; image: string; region: string; size: string }; diff --git a/packages/app/src/features/settings/icon.tsx b/packages/app/src/features/settings/icon.tsx index 08399799..d61099ae 100644 --- a/packages/app/src/features/settings/icon.tsx +++ b/packages/app/src/features/settings/icon.tsx @@ -5,6 +5,10 @@ const icons: Record = { github: , exe: , amp: , + x: , + fly: , + bearer: , + model: , tail: , }; export function IntegrationIcon({ kind }: { kind: string }) { return ; } diff --git a/packages/app/src/features/settings/integration-form.tsx b/packages/app/src/features/settings/integration-form.tsx index 206b35db..f05a6412 100644 --- a/packages/app/src/features/settings/integration-form.tsx +++ b/packages/app/src/features/settings/integration-form.tsx @@ -3,7 +3,6 @@ import { AutosaveStatus, useDebouncedAutosave } from "../../shared/use-debounced import { useRef, useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; -import { integrationsQuery } from "./queries"; import { messageOf } from "../auth/session"; export function IntegrationForm({ kind, connectionId, initialName = "", initialAgent = "codex", initialTags = [], initialApiBaseUrl }: { kind: "exe" | "amp" | "cloudflareTail"; connectionId?: string; initialName?: string; initialAgent?: "codex" | "claude" | "pi"; initialTags?: string[]; initialApiBaseUrl?: string }) { const cache = useQueryClient(), [credential, setCredential] = useState(""), [name, setName] = useState(initialName), [agentKind, setAgentKind] = useState<"codex" | "claude" | "pi">(initialAgent), [tags, setTags] = useState(initialTags), [generatedSecret, setGeneratedSecret] = useState(""), [savedFeedback, setSavedFeedback] = useState(false), savedSnapshot = useRef(""); @@ -18,7 +17,7 @@ export function IntegrationForm({ kind, connectionId, initialName = "", initialA const body = { name, signingSecret: credential || undefined, generateSecret: !credential && !connectionId }; const { data, error } = connectionId ? await api.PUT("/api/v1/integrations/cloudflare-tail/{integrationId}", { params: { path: { integrationId: connectionId } }, body }) : await api.POST("/api/v1/integrations/cloudflare-tail", { body }); if (!data || error) throw new Error(messageOf(error)); setGeneratedSecret(data.generatedSecret ?? ""); return { saved: true }; - }, onSuccess: async () => { setCredential(""); setSavedFeedback(true); test.reset(); await cache.invalidateQueries({ queryKey: integrationsQuery.queryKey }); await cache.invalidateQueries({ queryKey: ["providers"] }); await cache.invalidateQueries({ queryKey: ["editor"] }); } }); + }, onSuccess: async () => { setCredential(""); setSavedFeedback(true); test.reset(); await cache.invalidateQueries({ queryKey: ["settings"] }); await cache.invalidateQueries({ queryKey: ["providers"] }); await cache.invalidateQueries({ queryKey: ["editor"] }); } }); const value = { credential, name, agentKind, tags }; if (!savedSnapshot.current) savedSnapshot.current = JSON.stringify({ credential: "", name: initialName, agentKind: initialAgent, tags: initialTags }); const validate = (next: typeof value) => { diff --git a/packages/app/src/features/settings/integration-ui.tsx b/packages/app/src/features/settings/integration-ui.tsx new file mode 100644 index 00000000..d1303202 --- /dev/null +++ b/packages/app/src/features/settings/integration-ui.tsx @@ -0,0 +1,30 @@ +import { useEffect, useRef, useState, type ReactNode } from "react"; +import { IntegrationIcon } from "./icon"; +import { Badge } from "../../shared/ui"; +import { IntegrationPolicy, PolicyDialog, useIntegrationPolicy } from "./api-policies"; + +export function ProviderTile({kind, name, description, count, onAdd, href}: {kind: string; name: string; description: string; count: number; onAdd?: () => void; href?: string}) { + const content = <>{name}{count} {count === 1 ? "integration" : "integrations"}{description}; + const className = "relative flex min-h-44 w-full flex-col items-center justify-center gap-2 rounded-xl border border-stone-200 bg-white px-4 py-5 text-center transition hover:border-factorize-500 focus-visible:outline-2 focus-visible:outline-factorize-500 dark:border-slate-700 dark:bg-slate-900"; + return href ? {content} : ; +} +export type IntegrationAction = {label: string; onClick?: () => void; href?: string; external?: boolean; destructive?: boolean; disabled?: boolean}; +function ActionMenu({name, actions}: {name: string; actions: IntegrationAction[]}) { + const ref = useRef(null); + useEffect(() => { + const outside = (event: MouseEvent) => {if (ref.current && !ref.current.contains(event.target as Node)) ref.current.open = false;}; + const escape = (event: KeyboardEvent) => {if (event.key === "Escape" && ref.current?.open) {ref.current.open = false; ref.current.querySelector("summary")?.focus();}}; + document.addEventListener("mousedown", outside); document.addEventListener("keydown", escape); + return () => {document.removeEventListener("mousedown", outside); document.removeEventListener("keydown", escape);}; + }, []); + return
⋯
{actions.map(action => { + const className = `flex min-h-10 w-full items-center rounded px-3 py-2 text-left text-sm hover:bg-stone-100 dark:hover:bg-slate-800 disabled:opacity-50 ${action.destructive ? "text-red-700 dark:text-red-400" : ""}`; + const close = () => {if (ref.current) {ref.current.open = false; ref.current.querySelector("summary")?.focus();} action.onClick?.();}; + return action.href ? {action.label} : ; + })}
; +} +export function IntegrationRow({kind, credentialId, name, detail, connected = true, status, actions, children}: {kind: string; credentialId: string; name: string; detail?: string; connected?: boolean; status?: string; actions: IntegrationAction[]; children?: ReactNode}) { + const [policyOpen, setPolicyOpen] = useState(false); + const {row} = useIntegrationPolicy(kind, credentialId); + return

{name}

{detail &&

{detail}

}
{status ?? (connected ? "Connected" : "Needs attention")}
setPolicyOpen(true)}] : [])]} />
{children}{policyOpen && setPolicyOpen(false)} />}
; +} diff --git a/packages/app/src/features/settings/integrations.tsx b/packages/app/src/features/settings/integrations.tsx index 179d11bc..0d13ed76 100644 --- a/packages/app/src/features/settings/integrations.tsx +++ b/packages/app/src/features/settings/integrations.tsx @@ -1,7 +1,4 @@ -import { ApiPolicies } from "./api-policies"; import { useState, type ReactNode } from "react"; -import { IntegrationIcon } from "./icon"; -import { Disclosure, Summary, Button, Card, Badge } from "../../shared/ui"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { integrationsQuery } from "./queries"; @@ -9,61 +6,76 @@ import { installationsQuery } from "../jobs/provider-queries"; import { SettingsLayout } from "./navigation"; import { IntegrationForm } from "./integration-form"; import { messageOf } from "../auth/session"; -import { BearerIntegrations } from "./bearer-integrations"; -import { FlyIntegration, flyConnectionQuery } from "./fly"; -import { ModelAccounts } from "./model-accounts"; -import { XConnections } from "./x-connections"; +import { useBearerIntegrations } from "./bearer-integrations"; +import { useFlyIntegration } from "./fly"; +import { useXConnections } from "./x-connections"; +import { useModelAccounts } from "./model-accounts"; +import { IntegrationPoliciesProvider } from "./api-policies"; +import { IntegrationRow, ProviderTile, type IntegrationAction } from "./integration-ui"; +import { Dialog } from "../../shared/dialog"; +type Kind = "exe" | "amp" | "cloudflareTail" | "github"; const linkClass = "inline-flex min-h-10 items-center rounded-lg border border-stone-200 px-3 py-2 text-sm font-semibold hover:bg-stone-100 dark:border-slate-700 dark:hover:bg-slate-800"; - -function SetupDisclosure({ title, onToggle, children }: { title: string; onToggle: (open: boolean) => void; children: ReactNode }) { - return onToggle(event.currentTarget.open)}>{title}{children}; -} - -function ProviderCard({ kind, name, description, children }: { kind: string; name: string; description: string; children: ReactNode }) { - return

{name}

{description}

{children}
; -} - export function Integrations() { - const cache = useQueryClient(), status = useQuery(integrationsQuery), fly = useQuery(flyConnectionQuery), github = useQuery(installationsQuery), [openSetup, setOpenSetup] = useState(null), [feedback, setFeedback] = useState<{ key: string; test: boolean; message: string; error: boolean } | null>(null); - const action = useMutation({ retry: false, mutationFn: async ({ kind, id, test }: { kind: "exe" | "amp" | "cloudflareTail" | "github"; id: string; test?: boolean }) => { + return ; +} +function IntegrationsContent() { + const cache = useQueryClient(), status = useQuery(integrationsQuery), github = useQuery(installationsQuery); + const fly = useFlyIntegration(), bearer = useBearerIntegrations(), models = useModelAccounts(), x = useXConnections(); + const [setup, setSetup] = useState<{title: string; form: ReactNode} | null>(null); + const [feedback, setFeedback] = useState<{key: string; message: string; error: boolean} | null>(null); + const action = useMutation({retry: false, mutationFn: async ({kind, id, test}: {kind: Kind; id: string; test?: boolean}) => { let result; - if (kind === "exe") result = test ? await api.POST("/api/v1/integrations/exe/test", { body: { connectionId: id } }) : await api.DELETE("/api/v1/integrations/exe/{connectionId}", { params: { path: { connectionId: id } } }); - else if (kind === "amp") result = test ? await api.POST("/api/v1/integrations/amp/test", { body: { connectionId: id } }) : await api.DELETE("/api/v1/integrations/amp/{connectionId}", { params: { path: { connectionId: id } } }); - else if (kind === "cloudflareTail") result = test ? await api.POST("/api/v1/integrations/cloudflare-tail/{integrationId}/test", { params: { path: { integrationId: id } } }) : await api.DELETE("/api/v1/integrations/cloudflare-tail/{integrationId}", { params: { path: { integrationId: id } } }); - else result = await api.DELETE("/api/v1/providers/github/installations/{installationId}", { params: { path: { installationId: id } } }); + if (kind === "exe") result = test ? await api.POST("/api/v1/integrations/exe/test", {body: {connectionId: id}}) : await api.DELETE("/api/v1/integrations/exe/{connectionId}", {params: {path: {connectionId: id}}}); + else if (kind === "amp") result = test ? await api.POST("/api/v1/integrations/amp/test", {body: {connectionId: id}}) : await api.DELETE("/api/v1/integrations/amp/{connectionId}", {params: {path: {connectionId: id}}}); + else if (kind === "cloudflareTail") result = test ? await api.POST("/api/v1/integrations/cloudflare-tail/{integrationId}/test", {params: {path: {integrationId: id}}}) : await api.DELETE("/api/v1/integrations/cloudflare-tail/{integrationId}", {params: {path: {integrationId: id}}}); + else result = await api.DELETE("/api/v1/providers/github/installations/{installationId}", {params: {path: {installationId: id}}}); if (result.error) throw new Error(messageOf(result.error)); if (test && (!result.data || !("ok" in result.data) || result.data.ok !== true)) { - const missing = result.data && "missingPermissions" in result.data && Array.isArray(result.data.missingPermissions) - ? result.data.missingPermissions.filter((permission): permission is string => typeof permission === "string") : []; + const missing = result.data && "missingPermissions" in result.data && Array.isArray(result.data.missingPermissions) ? result.data.missingPermissions.filter((permission): permission is string => typeof permission === "string") : []; throw new Error(missing.length ? `Connection verification failed. Missing exe.dev permissions: ${missing.join(", ")}.` : "Connection verification failed."); } - return { test, result: result.data }; - }, onSuccess: async (_result, variables) => { setFeedback({ key: `${variables.kind}:${variables.id}`, test: Boolean(variables.test), message: variables.test ? "Connection verified." : "Integration disconnected.", error: false }); await cache.invalidateQueries({ queryKey: ["settings"] }); await cache.invalidateQueries({ queryKey: ["providers"] }); await cache.invalidateQueries({ queryKey: ["editor"] }); }, onError: (error, variables) => setFeedback({ key: `${variables.kind}:${variables.id}`, test: Boolean(variables.test), message: error.message, error: true }) }); - const buttons = (kind: "exe" | "amp" | "cloudflareTail" | "github", id: string) => { const key = `${kind}:${id}`, current = feedback?.key === key ? feedback : null; return
{kind !== "github" && }{current &&

{current.error ? current.message : `✓ ${current.message}`}

}
; }; - const manage = (key: string, form: ReactNode) => openSetup === key &&
{form}
; - const hasConnections = Boolean(status.data?.linear || status.data?.clickup || status.data?.exeConnections.length || status.data?.ampConnections.length || status.data?.cloudflareTail.installations.length || github.data?.length); - return - {status.isPending &&

Loading integrations…

}{[status.error, github.error].filter(Boolean).map((error, i) =>

{error?.message}

)} -

Your integrations

Manage the connections already available to your workspace.

- {!hasConnections && !fly.data && !status.isPending && !fly.isPending &&

No integrations added yet

Choose a provider from the available integrations below to get started.

} - {hasConnections &&
- {status.data?.linear &&

Linear

{status.data.linear.organizationName ?? status.data.linear.viewerEmail ?? "Connected account"}

Connected{manage("linear", Reconnect Linear)}
} - {status.data?.clickup &&

ClickUp

{status.data.clickup.teamName ?? "Connected workspace"}

Connected{manage("clickup", Reconnect ClickUp)}
} - {github.data?.map(i =>

GitHub

{i.accountLogin} · {i.accountType}

{i.state === "active" ? "Connected" : `Needs attention · ${i.state}`}Manage{buttons("github", String(i.installationId))}
)} - {status.data?.exeConnections.map(c =>

exe.dev · {c.connectionId}

{(c.accountTags ?? []).join(", ") || "Account tags available"}

Connected{buttons("exe", c.connectionId)}
{manage(`exe:${c.connectionId}`, )}
)} - {status.data?.ampConnections.map(c =>

Amp · {c.project}

Project connection

Connected{buttons("amp", c.connectionId)}
{manage(`amp:${c.connectionId}`, )}
)} - {status.data?.cloudflareTail.installations.map(c =>

Cloudflare Tail · {c.name}

Referenced by {c.referencedJobCount} {c.referencedJobCount === 1 ? "job" : "jobs"}

Connected{buttons("cloudflareTail", c.integrationId)}
{manage(`tail:${c.integrationId}`, )}
)} + return result.data; + }, onSuccess: async (_result, variables) => { + setFeedback({key: `${variables.kind}:${variables.id}`, message: variables.test ? "Connection verified." : "Integration disconnected.", error: false}); + await Promise.all([cache.invalidateQueries({queryKey: ["settings"]}), cache.invalidateQueries({queryKey: ["providers"]}), cache.invalidateQueries({queryKey: ["editor"]})]); + }, onError: (error, variables) => setFeedback({key: `${variables.kind}:${variables.id}`, message: error.message, error: true})}); + const actions = (kind: Kind, id: string, edit?: () => void): IntegrationAction[] => [ + ...(edit ? [{label: "Edit integration", onClick: edit}] : []), + ...(kind !== "github" ? [{label: "Test connection", disabled: action.isPending, onClick: () => {setFeedback(null); action.mutate({kind, id, test: true});}}] : []), + {label: "Disconnect", destructive: true, disabled: action.isPending, onClick: () => {if (window.confirm("Disconnect this integration? Jobs that still reference it must be updated first.")) {setFeedback(null); action.mutate({kind, id});}}}, + ]; + const result = (key: string) => feedback?.key === key &&

{feedback.message}

; + const open = (title: string, form: ReactNode) => setSetup({title, form}); + const data = status.data; + const count = (data?.linear ? 1 : 0) + (data?.clickup ? 1 : 0) + (github.data?.length ?? 0) + (data?.exeConnections.length ?? 0) + (data?.ampConnections.length ?? 0) + (data?.cloudflareTail.installations.length ?? 0) + fly.count + bearer.count + models.count + x.count; + const pending = status.isPending || github.isPending || fly.pending || bearer.pending || models.pending || x.pending; + return <> + {[status.error, github.error].filter(Boolean).map((error, i) =>

{error?.message}

)} +

Your integrations

Manage workspace connections. Default API access applies to connected MCP clients; other access requires approval.

+ {pending &&

Loading integrations…

} + {!count && !pending &&

No integrations added yet. Choose a provider below to get started.

} + {Boolean(count) &&
+ {data?.linear && } + {data?.clickup && } + {github.data?.map(i => {result(`github:${i.installationId}`)})} + {data?.exeConnections.map(c => open("Edit exe.dev integration", ))}>{result(`exe:${c.connectionId}`)})} + {data?.ampConnections.map(c => open("Edit Amp integration", ))}>{result(`amp:${c.connectionId}`)})} + {fly.rows}{bearer.rows}{models.rows}{x.rows} + {data?.cloudflareTail.installations.map(c => open("Edit Tail integration", ))}>{result(`cloudflareTail:${c.integrationId}`)})}
} + {feedback && !feedback.error && feedback.message === "Integration disconnected." &&

Integration disconnected.

} + {fly.feedback}{bearer.feedback}{models.feedback}{x.feedback}
- -

Available integrations

Connect a provider to add it to your workspace. Connected providers remain available for additional connections.

- setOpenSetup(open ? "linear-new" : null)}>{status.data?.linear ? "Add another Linear account" : "Connect Linear"} - setOpenSetup(open ? "clickup-new" : null)}>{status.data?.clickup ? "Add another ClickUp workspace" : "Connect ClickUp"} -

{github.data?.length ?? 0} added

{github.data?.length ? "Add another GitHub installation" : "Connect GitHub"}
-

{status.data?.exeConnections.length ?? 0} added

setOpenSetup(open ? "exe-new" : null)}>
-

{status.data?.ampConnections.length ?? 0} added

setOpenSetup(open ? "amp-new" : null)}>
-

{status.data?.cloudflareTail.installations.length ?? 0} added

setOpenSetup(open ? "tail-new" : null)}>
+

Available integrations

Choose a provider to connect or configure an integration.

+ + + + open("Add exe.dev integration", )} /> + open("Add Amp integration", )} /> + {fly.tile}{bearer.tile}{models.tile}{x.tile} + open("Add Tail integration", )} />
- ; + {setup && setSetup(null)}>{setup.form}}{fly.dialog}{bearer.dialog}{models.dialog}{x.dialog} + ; } diff --git a/packages/app/src/features/settings/model-accounts.tsx b/packages/app/src/features/settings/model-accounts.tsx index 5d334a7b..90068fb5 100644 --- a/packages/app/src/features/settings/model-accounts.tsx +++ b/packages/app/src/features/settings/model-accounts.tsx @@ -1,9 +1,12 @@ import {useEffect, useState} from "react"; import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query"; import {api} from "factorize-api-client"; -import {Button, Card, Input, Label} from "../../shared/ui"; +import {Button, Input, Label} from "../../shared/ui"; import {messageOf} from "../auth/session"; +import { Dialog } from "../../shared/dialog"; +import { IntegrationRow, ProviderTile } from "./integration-ui"; + type Account={id:string; name:string; description:string|null; revision:number; credentialConfigured:boolean}; type Authorization={state:string; verificationUrl?:string; userCode?:string; pollAfterSeconds?:number}; const queryKey=["settings","model-accounts"]; @@ -13,12 +16,13 @@ async function authorization(accountId:string,action:"authorize"|"status"|"cance if(!data || error) throw new Error(messageOf(error)); return data; } -export function ModelAccounts() { +export function useModelAccounts() { const cache=useQueryClient(); const accounts=useQuery({queryKey,queryFn:async({signal})=>{const {data,error}=await api.GET("/api/v1/model-accounts",{signal}); if(!data || error) throw new Error(messageOf(error)); if(!Array.isArray(data.accounts) || !Number.isSafeInteger(data.revision)) throw new Error("Model accounts could not be loaded. Reload the page to try again."); return data;}}); + const [open,setOpen]=useState(false); const [active,setActive]=useState(null),[states,setStates]=useState>({}),[error,setError]=useState(""); const [name,setName]=useState(""),[description,setDescription]=useState(""),[kind,setKind]=useState<"chatgpt"|"api-key">("chatgpt"),[key,setKey]=useState(""),[editId,setEditId]=useState(null); - const refresh=()=>cache.invalidateQueries({queryKey}); + const refresh=()=>cache.invalidateQueries({queryKey:["settings"]}); const connect=async(id:string)=>{ setError(""); try {const state=await authorization(id,"authorize"); setStates(current=>({...current,[id]:state})); setActive(state.state==="pending"?id:null);} @@ -46,7 +50,7 @@ export function ModelAccounts() { const response=editId?await api.PUT("/api/v1/model-accounts/{accountId}",{params:{path:{accountId:id}},body}):await api.POST("/api/v1/model-accounts",{body:{...body,id}}); if(!response.data || response.error) throw new Error(messageOf(response.error)); return{id,connect:kind==="chatgpt"}; - },onSuccess:async(result)=>{reset();setError("");await refresh();if(result.connect) await connect(result.id);},onError:async(reason)=>{setError(reason.message);await refresh();}}); + },onSuccess:async(result)=>{reset();setOpen(false);setError("");await refresh();if(result.connect) await connect(result.id);},onError:async(reason)=>{setError(reason.message);await refresh();}}); const remove=useMutation({retry:false,mutationFn:async(account:Account)=>{ if(!accounts.data) throw new Error("Model accounts are still loading."); const {data,error}=await api.DELETE("/api/v1/model-accounts/{accountId}",{params:{path:{accountId:account.id}},body:{expectedRevision:accounts.data.revision,idempotencyKey:crypto.randomUUID()}}); @@ -56,26 +60,30 @@ export function ModelAccounts() { try {const state=await authorization(id,"cancel");setStates(current=>({...current,[id]:state}));setActive(null);} catch(reason) {setError(reason instanceof Error?reason.message:"Could not cancel authorization.");} }; - return
-

Model accounts

Connect ChatGPT or save an OpenAI API key. Factorize stores and refreshes credentials on the server. Stored credentials cannot be viewed.

- {accounts.isPending&&

Loading model accounts…

}{accounts.error&&

{accounts.error.message}

}{error&&

{error}

} - {accounts.data?.accounts.length===0&&

No model accounts are configured yet.

} - {accounts.data?.accounts.map(account=>{const state=states[account.id];return -

{account.name}

{account.description&&

{account.description}

}

{account.credentialConfigured?"Credentials saved":"Not connected"}

- {state?.state==="pending"&&

Enter this one-time code to connect ChatGPT:

{state.userCode}

Open ChatGPT device authorization
} + const close=()=>{reset();setOpen(false);setError("");}; + return { + count:accounts.data?.accounts.length??0,pending:accounts.isPending, + rows:accounts.data?.accounts.map(account=>{ + const state=states[account.id]; + return void cancel(account.id)} : {label:account.credentialConfigured?"Reconnect ChatGPT":"Connect ChatGPT",disabled:Boolean(active)||remove.isPending,onClick:()=>void connect(account.id)}, + {label:"Replace API key",disabled:Boolean(active)||save.isPending,onClick:()=>{setEditId(account.id);setName(account.name);setDescription(account.description??"");setKind("api-key");setKey("");setOpen(true);}}, + {label:"Delete account",destructive:true,disabled:remove.isPending||Boolean(active),onClick:()=>{if(window.confirm(`Delete ${account.name}? Existing run access will remain revoked even after reconnection.`)) remove.mutate(account);}}, + ]}> + {state?.state==="pending"&&

Enter this one-time code to connect ChatGPT: {state.userCode}

Open ChatGPT device authorization
} {state?.state==="authorized"&&

Account connected.

}{state?.state==="canceled"&&

Authorization attempt canceled.

} {["expired","failed","reauthentication-required"].includes(state?.state??"")&&

Authorization did not complete. Connect the account again.

} -
- {state?.state==="pending"?:} - - -
;})} -

{editId?"Replace model credential":"Add a model account"}

{event.preventDefault();setError("");save.mutate();}}> + ; + }), + tile:{reset();setError("");setOpen(true);}} />, + feedback:<>{accounts.error&&

{accounts.error.message}

}{error&&!open&&

{error}

}, + dialog:open&&

Connect ChatGPT or save an OpenAI API key. Stored credentials cannot be viewed.

+ {event.preventDefault();setError("");save.mutate();}}> {!editId&&} {kind==="api-key"&&} -
{editId&&}
-
-
; +
{editId&&}
+ {error&&

{error}

}, + }; } diff --git a/packages/app/src/features/settings/x-connections.tsx b/packages/app/src/features/settings/x-connections.tsx index 68959d26..570876b4 100644 --- a/packages/app/src/features/settings/x-connections.tsx +++ b/packages/app/src/features/settings/x-connections.tsx @@ -1,9 +1,12 @@ import { useEffect, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; -import { Button, Card } from "../../shared/ui"; +import { Button } from "../../shared/ui"; import { messageOf } from "../auth/session"; +import { Dialog } from "../../shared/dialog"; +import { IntegrationRow, ProviderTile } from "./integration-ui"; + const permissions = [ ["tweet.read", "Read posts the authorized account can view."], ["tweet.write", "Post and delete posts for the authorized account."], @@ -26,8 +29,9 @@ const permissions = [ type XScope = typeof permissions[number][0]; const suggested: XScope[] = ["tweet.read", "users.read", "offline.access"]; -export function XConnections() { +export function useXConnections() { const cache = useQueryClient(); + const [open, setOpen] = useState(false); const [name, setName] = useState(""), [clientId, setClientId] = useState(""), [clientSecret, setClientSecret] = useState(""); const [replaceId, setReplaceId] = useState(null), [replacementClientId, setReplacementClientId] = useState(""), [replacementSecret, setReplacementSecret] = useState(""); const [scopes, setScopes] = useState(suggested), [error, setError] = useState(null), [notice, setNotice] = useState(null); @@ -48,7 +52,7 @@ export function XConnections() { if (result && messages[result]) { setNotice(messages[result]); const clean = new URL(location.href); clean.searchParams.delete("x"); history.replaceState(null, "", clean); - void cache.invalidateQueries({ queryKey: ["settings", "x-connections"] }); + void cache.invalidateQueries({ queryKey: ["settings"] }); } }, [cache]); const create = useMutation({ retry: false, mutationFn: async () => { @@ -57,7 +61,7 @@ export function XConnections() { return response.data; }, onSuccess: async connection => { setClientSecret(""); setName(""); setClientId(""); - await cache.invalidateQueries({ queryKey: ["settings", "x-connections"] }); + await cache.invalidateQueries({ queryKey: ["settings"] }); const response = await api.POST("/api/v1/x/connections/{connectionId}/authorize", { params: { path: { connectionId: connection.id } }, body: {} }); if (!response.data || response.error) throw new Error(messageOf(response.error)); location.assign(response.data.authorizationUrl); @@ -78,33 +82,28 @@ export function XConnections() { return response.data; }, onSuccess: async connection => { setReplacementSecret(""); setReplacementClientId(""); setReplaceId(null); - await cache.invalidateQueries({ queryKey: ["settings", "x-connections"] }); + await cache.invalidateQueries({ queryKey: ["settings"] }); setNotice("App credentials replaced. Reauthorize the same X account to restore access."); authorize.mutate(connection.id); }, onError: value => setError(value.message) }); const toggle = (scope: XScope) => setScopes(current => current.includes(scope) ? current.filter(item => item !== scope) : [...current, scope]); const callback = `${location.origin}/oauth/x/callback`; - return
-

X connections

Connect your own X developer app and account. API usage is billed to your X developer account.

- {notice &&

{notice}

} - {connections.error &&

{connections.error.message}

} - {connections.data?.map(connection => -

{connection.name}

{connection.accountHandle ? `@${connection.accountHandle} · ${connection.accountId}` : "No X account connected yet"}

{connection.status === "connected" ? "Connected" : connection.status === "reconnect_required" ? "Needs attention" : connection.status === "revoked" ? "Disconnected" : "Setup incomplete"}
- {connection.grantedScopes.length > 0 &&

Granted permissions: {connection.grantedScopes.join(", ")}

} - {connection.status === "revoked" ?

Disconnected. Create a new connection to use X again.

: connection.status !== "connected" && } - {connection.status !== "revoked" &&
- - -
} - {replaceId === connection.id &&
-

Replacing credentials clears saved tokens and pauses this connection until reauthorization. The existing X account stays bound; to connect another account, create a new connection.

- - - -
} -
)} - + const close = () => {setOpen(false); setReplaceId(null); setName(""); setClientId(""); setClientSecret(""); setReplacementClientId(""); setReplacementSecret(""); setError(null);}; + return { + count: connections.data?.length ?? 0, pending: connections.isPending, + rows: connections.data?.map(connection => {setError(null); authorize.mutate(connection.id);}}] : []), + {label: "Test connection", disabled: testConnection.isPending || connection.status !== "connected", onClick: () => {setError(null); setNotice(null); testConnection.mutate(connection.id);}}, + {label: "Replace app credentials", onClick: () => {setError(null); setNotice(null); setReplaceId(connection.id); setReplacementClientId(""); setReplacementSecret("");}}, + ]}> + {connection.grantedScopes.length > 0 &&

Granted permissions: {connection.grantedScopes.join(", ")}

} + {connection.status === "revoked" &&

Disconnected. Create a new connection to use X again.

} +
), + tile: {close(); setScopes(suggested); setOpen(true);}} />, + feedback: <>{notice &&

{notice}

}{connections.error &&

{connections.error.message}

}{error && !open && !replaceId &&

{error}

}, + dialog: <>{open &&
+

Set up your X developer app

  1. Open the X Developer Console and create a project and app. In app permissions, choose Read and write only if you plan to grant write scopes below.
  2. Enable OAuth 2.0, choose a Web App / confidential client, and add this callback URL exactly: {callback} .
  3. @@ -117,6 +116,11 @@ export function XConnections() {
    X permissions

    Suggested access is read-only posts and user profiles, plus offline access. Write permissions are opt-in. Direct Messages and other sensitive access are never selected automatically.

    {permissions.map(([scope, description]) => )}

    tweet.read, users.read, and offline.access are required for this connection. The server validates the selected permission set.

    {error &&

    {error}

    } - -
; +
}{replaceId &&
+

Replacing credentials clears saved tokens and pauses this connection until reauthorization. The existing X account stays bound; to connect another account, create a new connection.

+ + + +
{error &&

{error}

}
}, + }; } diff --git a/packages/app/test/settings.browser.test.mjs b/packages/app/test/settings.browser.test.mjs index 7ff9cf24..17b1c459 100644 --- a/packages/app/test/settings.browser.test.mjs +++ b/packages/app/test/settings.browser.test.mjs @@ -6,15 +6,21 @@ import { chromium } from "playwright"; let server, origin, browser; before(async () => { server = createServer(async (req, res) => { const path = new URL(req.url, "http://local").pathname, file = (/^(\/assets\/|\/theme-init.js$|\/bee-mark-monochrome.png$|\/favicon.ico$)/.test(path)) ? path : "/index.html"; try { const body = await readFile(new URL("../dist" + file, import.meta.url)); res.setHeader("Content-Type", file.endsWith(".js") ? "application/javascript" : file.endsWith(".css") ? "text/css" : "text/html"); res.end(body); } catch { res.statusCode = 404; res.end(); } }); await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); origin = "http://127.0.0.1:" + server.address().port; browser = await chromium.launch({ headless: true }); }); after(async () => { await browser?.close(); if (server) await new Promise(resolve => server.close(resolve)); }); -async function setup() { const context = await browser.newContext(), page = await context.newPage(); page.setDefaultTimeout(10000); await page.route("**/api/v1/session", route => route.fulfill({ json: { authenticated: true, user: { id: "owner", email: "owner@example.test" }, workspace: { id: "tenant", name: "Workspace" }, capabilities: [], expiresAt: "2026-10-10T00:00:00Z" } })); return { context, page }; } +async function setup() { const context = await browser.newContext(), page = await context.newPage(); page.setDefaultTimeout(10000); + await page.route("**/api/v1/x/connections", route => route.fulfill({json:{connections:[]}})); + await page.route("**/api/v1/fly/connection", route => route.fulfill({json:{connection:null}})); + await page.route("**/api/v1/integrations/bearer", route => route.fulfill({json:{revision:0,integrations:[]}})); + await page.route("**/api/v1/model-accounts", route => route.fulfill({json:{revision:0,accounts:[]}})); + await page.route("**/api/v1/integration-api-policies", route => route.fulfill({json:{integrations:[]}})); + await page.route("**/api/v1/session", route => route.fulfill({ json: { authenticated: true, user: { id: "owner", email: "owner@example.test" }, workspace: { id: "tenant", name: "Workspace" }, capabilities: [], expiresAt: "2026-10-10T00:00:00Z" } })); return { context, page }; } test("integration setup tests credentials, submits typed fields, clears secrets and refreshes installed status", async () => { const { context, page } = await setup(); let saved = false, body; await page.route("**/api/v1/providers/github/installations", route => route.fulfill({ json: [] })); await page.route("**/api/v1/integrations", route => route.fulfill({ json: { linear: null, clickup: null, exe: null, exeConnections: saved ? [{ connectionId: "vm", accountTags: ["dev"] }] : [], ampConnections: [], cloudflareTail: { count: 0, installations: [] } } })); await page.route("**/api/v1/integrations/exe/test", route => route.fulfill({ json: { ok: true, missingPermissions: [], tags: ["dev"], checks: [] } })); await page.route("**/api/v1/integrations/exe", route => { body = route.request().postDataJSON(); saved = true; return route.fulfill({ json: { ok: true, connectionId: "vm", models: [] } }); }); - await page.goto(origin + "/settings/integrations"); await page.getByText("Add exe.dev integration", { exact: true }).click(); - const form = page.locator("details").filter({ has: page.getByText("Add exe.dev integration", { exact: true }) }); + await page.goto(origin + "/settings/integrations"); await page.getByRole("button", {name:"Add exe.dev integration",exact:true}).click(); + const form = page.getByRole("dialog", {name:"Add exe.dev integration"}); await form.getByLabel("exe.dev account token").fill("private-input"); await form.getByRole("button", { name: "Test credentials" }).click(); await form.getByText("✓ Credentials verified.", { exact: true }).waitFor(); await form.getByLabel("VM tags").selectOption(["dev"]); await form.getByRole("button", { name: "Save integration", exact: true }).click(); await form.getByText("Integration saved", { exact: true }).waitFor(); assert.deepEqual(body.tags, ["dev"]); assert.equal(body.agentKind, "codex"); assert.equal(await form.getByLabel("exe.dev account token").inputValue(), ""); assert.equal(await page.evaluate(() => JSON.stringify(localStorage).includes("private-input")), false); await page.getByText("dev", { exact: true }).waitFor(); await context.close(); }); @@ -28,7 +34,8 @@ test("model authorization stays on the backend and displays only the public devi return route.fulfill({json:route.request().url().endsWith("/cancel")?{state:"canceled"}:{state:"pending",verificationUrl:"https://auth.openai.com/codex/device",userCode:"ABCD-1234",pollAfterSeconds:5}}); }); await page.goto(origin+"/settings/integrations"); - const models=page.getByRole("region",{name:"Model accounts"}); + const models=page.getByRole("region",{name:"Your integrations"}); + await models.getByLabel("Actions for Work account",{exact:true}).click(); await models.getByRole("button",{name:"Connect ChatGPT",exact:true}).click(); await models.getByText("ABCD-1234",{exact:true}).waitFor(); assert.equal(await models.getByRole("link",{name:"Open ChatGPT device authorization"}).getAttribute("href"),"https://auth.openai.com/codex/device"); @@ -52,20 +59,21 @@ test("owner browser stores bearer integration in Factorize managed storage witho }); await page.goto(origin + "/settings/integrations"); - const integrations = page.getByRole("region", { name: "Bearer integrations" }); + await page.getByRole("button",{name:"Add Bearer API integration",exact:true}).click(); + const integrations = page.getByRole("dialog", { name: "Add bearer integration" }); await integrations.getByLabel("Name").fill("Example service"); await integrations.getByLabel("HTTPS origin").fill("https://api.example.test"); await integrations.getByLabel("Description or help (optional)").fill("Fixture API"); await integrations.getByLabel("Bearer token").fill("synthetic-upstream-secret"); await integrations.getByRole("button", { name: "Add integration" }).click(); - await integrations.getByText("Saved integration in Factorize managed encrypted storage.", { exact: true }).waitFor(); + await page.getByText("Bearer integration saved.", { exact: true }).waitFor(); assert.equal(createBody.name, "Example service"); assert.equal(createBody.origin, "https://api.example.test"); assert.equal(createBody.description, "Fixture API"); assert.equal(createBody.token, "synthetic-upstream-secret"); assert.equal(createBody.unlockKey, undefined); - assert.equal(await integrations.getByLabel("Bearer token").inputValue(), ""); + assert.equal(await integrations.count(), 0); assert.equal(await integrations.getByText("synthetic-upstream-secret", { exact: true }).count(), 0); assert.equal(await page.evaluate(() => JSON.stringify(localStorage).includes("synthetic-upstream-secret")), false); await context.close(); @@ -99,24 +107,28 @@ test("model account create/delete uses server-managed state without an unlock ke }); await page.goto(origin + "/settings/integrations"); - const models = page.getByRole("region", { name: "Model accounts" }); - await models.getByLabel("Name").fill("Work account"); - await models.getByLabel("Description (optional)").fill("Personal account"); - await models.getByRole("combobox", {name:/^Connection/}).selectOption("api-key"); - await models.getByLabel("API key", {exact:true}).fill("synthetic-model-key"); - await models.getByRole("button", { name: "Save model account" }).click(); + await page.getByRole("button",{name:"Add Model account integration",exact:true}).click(); + const form = page.getByRole("dialog",{name:"Add a model account"}); + const models = page.getByRole("region", { name: "Your integrations" }); + await form.getByLabel("Name").fill("Work account"); + await form.getByLabel("Description (optional)").fill("Personal account"); + await form.getByRole("combobox", {name:/^Connection/}).selectOption("api-key"); + await form.getByLabel("API key", {exact:true}).fill("synthetic-model-key"); + await form.getByRole("button", { name: "Save model account" }).click(); await models.getByText("Work account", { exact: true }).waitFor(); assert.equal(createBody.expectedRevision, 0); assert.equal(createBody.description, "Personal account"); page.once("dialog", dialog => dialog.accept()); const refreshAfterConflict = page.waitForResponse(response => response.url().includes("/api/v1/model-accounts") && response.request().method() === "GET" && response.status() === 200); + await models.getByLabel("Actions for Work account",{exact:true}).click(); await models.getByRole("button", { name: "Delete account" }).click(); await models.getByRole("alert").filter({ hasText: "collection changed" }).waitFor(); await refreshAfterConflict; page.once("dialog", dialog => dialog.accept()); + await models.getByLabel("Actions for Work account",{exact:true}).click(); await models.getByRole("button", { name: "Delete account" }).click(); - await models.getByText("No model accounts are configured yet.", { exact: true }).waitFor(); + await models.getByText(/No integrations added yet/).waitFor(); assert.equal(deleteBodies.length, 2); assert.equal(deleteBodies[0].expectedRevision, 1); assert.equal(deleteBodies[1].expectedRevision, 2); @@ -142,3 +154,73 @@ for (const malformed of ["bearer integrations", "model accounts"]) test(`setting assert.deepEqual(errors, []); } finally { await context.close(); } }); + +test("all connections share one list, row policies save by identity and disabled access is preserved", async () => { + const {context,page}=await setup(); + const id='aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + await page.route('**/api/v1/providers/github/installations',route=>route.fulfill({json:[{installationId:17,accountLogin:'fixture',accountType:'Organization',state:'active'}]})); + await page.route('**/api/v1/integrations',route=>route.fulfill({json:{linear:{organizationName:'Workspace'},clickup:{teamName:'Tasks'},exeConnections:[{connectionId:'vm',accountTags:['dev'],tags:['dev'],agentKind:'codex'}],ampConnections:[{connectionId:'amp',project:'Project'}],cloudflareTail:{installations:[{integrationId:'tail',name:'Logs',referencedJobCount:1}]}}})); + await page.route('**/api/v1/fly/connection',route=>route.fulfill({json:{connection:{organizationName:'Machines',organizationSlug:'machines'}}})); + await page.route('**/api/v1/integrations/bearer',route=>route.fulfill({json:{revision:1,integrations:[{id,name:'Example API',origin:'https://api.example.test',description:null,revision:1}]}})); + await page.route('**/api/v1/model-accounts',route=>route.fulfill({json:{revision:1,accounts:[{id,name:'Model fixture',description:null,credentialConfigured:true,revision:1}]}})); + await page.route('**/api/v1/x/connections',route=>route.fulfill({json:{connections:[{id,name:'Social account',accountId:'123',accountHandle:'social',status:'connected',scopes:['users.read'],grantedScopes:['users.read']}]}})); + const policies=[['linear','linear'],['clickup','clickup'],['github','17'],['exe','vm'],['amp','amp'],['fly','fly'],['bearer',id],['model',id],['x',id]].map(([kind,credentialId],index)=>({id:`00000000-0000-4000-8000-${String(index).padStart(12,'0')}`,kind,credentialId,name:kind,available:true,policy:kind==='model'?'disabled':'requestable',revision:1})); + await page.route('**/api/v1/integration-api-policies',route=>route.fulfill({json:{integrations:policies}})); + const updates=[];let conflict=true; + await page.route('**/api/v1/integration-api-policies/*',route=>{ + const row=policies.find(row=>route.request().url().endsWith(row.id)), body=route.request().postDataJSON();updates.push({id:row.id,...body}); + if(conflict){conflict=false;row.revision++;return route.fulfill({status:409,json:{error:{code:'stale_revision',message:'Integration policy changed. Try again.'}}});} + assert.equal(body.expectedRevision,row.revision);row.policy=body.policy;row.revision++; + return route.fulfill({json:{integrations:policies}}); + }); + await page.goto(origin+'/settings/integrations'); + const list=page.getByRole('list',{name:'Your integrations'}); + await list.getByText('Example API',{exact:true}).waitFor(); + assert.equal(await list.getByRole('listitem').count(),10); + assert.equal(await page.getByRole('heading',{name:'MCP API access',exact:true}).count(),0); + assert.equal(await page.locator('form').count(),0); + await list.getByRole('checkbox',{name:'Example API available by default',exact:true}).waitFor(); + assert.equal(await list.getByRole('checkbox').count(),9); + const checkbox=list.getByRole('checkbox',{name:'Example API available by default',exact:true}); + await checkbox.click();await list.getByRole('alert').filter({hasText:'Integration policy changed'}).waitFor(); + await checkbox.check();await page.waitForFunction(()=>document.querySelector('input[aria-label="Example API available by default"]')?.checked); + assert.equal(updates.at(-1).id,policies.find(row=>row.kind==='bearer').id); + assert.equal(updates.at(-1).expectedRevision,2); + assert.equal(updates.at(-1).policy,'baseline'); + await page.waitForFunction(()=>!document.querySelector('input[aria-label="Example API available by default"]')?.disabled); + await Promise.all([page.waitForResponse(response=>response.url().endsWith(policies.find(row=>row.kind==='bearer').id)&&response.request().method()==='PUT'),checkbox.uncheck()]); + assert.equal(updates.at(-1).policy,'requestable'); + const disabled=list.getByRole('checkbox',{name:'Model fixture available by default',exact:true}); + assert.equal(await disabled.isDisabled(),true);assert.equal(await disabled.isChecked(),false); + await list.getByLabel('Actions for Model fixture',{exact:true}).click();await list.getByRole('button',{name:'MCP access…',exact:true}).click(); + const dialog=page.getByRole('dialog',{name:'model MCP access'}); + assert.equal(await dialog.getByRole('combobox').inputValue(),'disabled'); + assert.equal(updates.filter(row=>row.id===policies.find(row=>row.kind==='model').id).length,0,'opening settings does not enable access'); + await page.keyboard.press('Escape'); + assert.equal(await dialog.count(),0); + await context.close(); +}); + +test("Fly setup opens from its tile, verifies and saves, then appears in the unified list", async () => { + const {context,page}=await setup();let connection=null, savedBody; + await page.route('**/api/v1/providers/github/installations',route=>route.fulfill({json:[]})); + await page.route('**/api/v1/integrations',route=>route.fulfill({json:{linear:null,clickup:null,exeConnections:[],ampConnections:[],cloudflareTail:{installations:[]}}})); + await page.route('**/api/v1/fly/connection/test',route=>route.fulfill({json:{ok:true}})); + await page.route('**/api/v1/fly/connection',route=>{ + if(route.request().method()==='PUT') {savedBody=route.request().postDataJSON();connection={organizationSlug:savedBody.organizationSlug,organizationName:'Fixture org'};} + return route.fulfill({json:{connection}}); + }); + await page.goto(origin+'/settings/integrations'); + await page.getByRole('button',{name:'Add Fly.io integration',exact:true}).click(); + const dialog=page.getByRole('dialog',{name:'Add Fly.io integration',exact:true}); + await dialog.getByLabel('Fly organization slug',{exact:true}).fill('fixture');await dialog.getByLabel('Fly organization token',{exact:true}).fill('synthetic-fly-token'); + await dialog.getByRole('button',{name:'Verify connection',exact:true}).click();await dialog.getByText('Fly.io connection verified.',{exact:true}).waitFor(); + await dialog.getByRole('button',{name:'Save Fly.io integration',exact:true}).click(); + const list=page.getByRole('list',{name:'Your integrations'});await list.getByText('Fixture org (fixture)',{exact:true}).waitFor(); + assert.equal(await dialog.count(),0);assert.deepEqual(savedBody,{token:'synthetic-fly-token',organizationSlug:'fixture'}); + await list.getByLabel('Actions for Fly.io',{exact:true}).click();await list.getByRole('button',{name:'Edit / verify connection',exact:true}).click(); + assert.equal(await page.getByRole('dialog').getByLabel('Fly organization token',{exact:true}).inputValue(),''); + await page.keyboard.press('Escape');assert.equal(await page.getByRole('dialog').count(),0); + assert.equal(await page.evaluate(()=>JSON.stringify(localStorage).includes('synthetic-fly-token')),false); + await context.close(); +}); diff --git a/packages/app/test/visual/baselines/settings-dark-1280.png b/packages/app/test/visual/baselines/settings-dark-1280.png index c8340397..67aa6557 100644 Binary files a/packages/app/test/visual/baselines/settings-dark-1280.png and b/packages/app/test/visual/baselines/settings-dark-1280.png differ diff --git a/packages/app/test/visual/baselines/settings-dark-390.png b/packages/app/test/visual/baselines/settings-dark-390.png index 118ace19..04e82360 100644 Binary files a/packages/app/test/visual/baselines/settings-dark-390.png and b/packages/app/test/visual/baselines/settings-dark-390.png differ diff --git a/packages/app/test/visual/baselines/settings-light-1280.png b/packages/app/test/visual/baselines/settings-light-1280.png index eabf8e9b..2f52a1ab 100644 Binary files a/packages/app/test/visual/baselines/settings-light-1280.png and b/packages/app/test/visual/baselines/settings-light-1280.png differ diff --git a/packages/app/test/visual/baselines/settings-light-390.png b/packages/app/test/visual/baselines/settings-light-390.png index e6153331..acc08b5b 100644 Binary files a/packages/app/test/visual/baselines/settings-light-390.png and b/packages/app/test/visual/baselines/settings-light-390.png differ diff --git a/packages/app/test/visual/design.spec.mjs b/packages/app/test/visual/design.spec.mjs index c81bcdd8..c8019ac6 100644 --- a/packages/app/test/visual/design.spec.mjs +++ b/packages/app/test/visual/design.spec.mjs @@ -27,6 +27,7 @@ for (const theme of ["light", "dark"]) for (const width of [1280, 390]) { await mockApi(page, { authenticated: name !== "login" }); await page.goto(origin + path); await expect(page.getByRole("heading", { name: heading, exact: true })).toBeVisible(); + if (name === "settings") await expect(page.getByRole("checkbox", { name: "Linear available by default", exact: true })).toBeVisible(); if (name === "editor") await expect(page.getByLabel("Name", { exact: true })).toHaveValue("Review release builds"); if (name === "trace") { await expect(page.getByText("User · user_message", { exact: true })).toBeVisible(); diff --git a/packages/app/test/visual/fixtures.mjs b/packages/app/test/visual/fixtures.mjs index d84cd9b0..3b3ee1d6 100644 --- a/packages/app/test/visual/fixtures.mjs +++ b/packages/app/test/visual/fixtures.mjs @@ -49,6 +49,11 @@ export async function mockApi(page, { legacy = false, authenticated = true, empt else if (path === "/api/v1/execution-integrations") json = targets; else if (path === "/api/v1/trigger-contexts") json = { manual: [{ path: "prompt", type: "string", description: "Manual prompt" }] }; else if (path === "/api/v1/job-trigger-availability") json = { manual: true, schedule: true, jobLifecycle: true, linear: false, github: false, clickup: false, cloudflareTail: false }; + else if (path === "/api/v1/x/connections") json = {connections:[]}; + else if (path === "/api/v1/fly/connection") json = {connection:null}; + else if (path === "/api/v1/integrations/bearer") json = {revision:0,integrations:[]}; + else if (path === "/api/v1/model-accounts") json = {revision:0,accounts:[]}; + else if (path === "/api/v1/integration-api-policies") json = {integrations:[{id:"00000000-0000-4000-8000-000000000050",kind:"linear",credentialId:"linear",name:"Linear",available:true,policy:"requestable",revision:1}]}; else if (path === "/api/v1/integrations") json = integrations; else if (path === "/api/v1/search") json = { items: [{ kind: "job", id: jobId, title: job.name, subtitle: "Manual · codex", url: "/jobs/" + jobId, source: { kind: "job", label: job.name, id: jobId }, match: { text: job.name, ranges: [{ start: 7, end: 14 }] } }] }; else if (path.endsWith("/consent/preview")) json = { clientName: "Release CLI", scopes: ["flows:read", "runs:read"], request: "fixture", signature: "fixture", expiresAt: time }; diff --git a/packages/app/test/x-connections.browser.test.mjs b/packages/app/test/x-connections.browser.test.mjs index e178a0ab..21cab491 100644 --- a/packages/app/test/x-connections.browser.test.mjs +++ b/packages/app/test/x-connections.browser.test.mjs @@ -25,6 +25,7 @@ test("X settings guides app callback setup, validated permissions, and starts ow await page.route("**/api/v1/**", route => { const path = new URL(route.request().url()).pathname; if (path === "/api/v1/session") return route.fulfill({ json: { authenticated: true, user: { id: "owner", email: "owner@example.test" }, workspace: { id: "workspace", name: "Workspace", role: "owner" }, capabilities: ["integrations:read", "integrations:write"] } }); + if (path === "/api/v1/fly/connection") return route.fulfill({json:{connection:null}}); if (path === "/api/v1/projects") return route.fulfill({ json: [] }); if (path === "/api/v1/integrations") return route.fulfill({ json: { exeConnections: [], ampConnections: [], cloudflareTail: { installations: [] }, linear: null, clickup: null } }); if (path.includes("providers/github/installations")) return route.fulfill({ json: [] }); @@ -41,7 +42,8 @@ test("X settings guides app callback setup, validated permissions, and starts ow }); await page.route("https://x.com/**", route => route.fulfill({ contentType: "text/html", body: "X consent" })); await page.goto(origin + "/settings/integrations"); - await page.getByRole("heading", { name: "X connections", exact: true }).waitFor(); + await page.getByRole("button", {name:"Add X integration",exact:true}).click(); + await page.getByRole("dialog",{name:"Add X integration",exact:true}).waitFor(); const callback = origin + "/oauth/x/callback"; await page.locator("code").filter({ hasText: callback }).waitFor({ timeout: 3000 }); assert.match(await page.getByText(/X Developer Console/).textContent(), /X Developer Console/); @@ -69,6 +71,7 @@ test("X settings explains terminal authorization failures and offers an explicit await page.route("**/api/v1/**", route => { const path = new URL(route.request().url()).pathname; if (path === "/api/v1/session") return route.fulfill({ json: { authenticated: true, user: { id: "owner", email: "owner@example.test" }, workspace: { id: "workspace", name: "Workspace", role: "owner" }, capabilities: ["integrations:read", "integrations:write"] } }); + if (path === "/api/v1/fly/connection") return route.fulfill({json:{connection:null}}); if (path === "/api/v1/projects") return route.fulfill({ json: [] }); if (path === "/api/v1/integrations") return route.fulfill({ json: { exeConnections: [], ampConnections: [], cloudflareTail: { installations: [] }, linear: null, clickup: null } }); if (path.includes("providers/github/installations")) return route.fulfill({ json: [] }); @@ -82,6 +85,7 @@ test("X settings explains terminal authorization failures and offers an explicit await page.route("https://x.com/**", route => route.fulfill({ contentType: "text/html", body: "X consent" })); await page.goto(origin + "/settings/integrations"); await page.getByText("Needs attention", { exact: true }).waitFor(); + await page.getByLabel("Actions for X · Work account",{exact:true}).click(); await page.getByRole("button", { name: "Connect X", exact: true }).click(); await page.waitForURL("https://x.com/i/oauth2/authorize**"); assert.equal(authorizeCalls, 1); @@ -95,6 +99,7 @@ test("X owner can test safely and replace app credentials before same-account re await page.route("**/api/v1/**", route => { const path = new URL(route.request().url()).pathname; if (path === "/api/v1/session") return route.fulfill({ json: { authenticated: true, user: { id: "owner", email: "owner@example.test" }, workspace: { id: "workspace", name: "Workspace", role: "owner" }, capabilities: ["integrations:read", "integrations:write"] } }); + if (path === "/api/v1/fly/connection") return route.fulfill({json:{connection:null}}); if (path === "/api/v1/projects") return route.fulfill({ json: [] }); if (path === "/api/v1/integrations") return route.fulfill({ json: { exeConnections: [], ampConnections: [], cloudflareTail: { installations: [] }, linear: null, clickup: null } }); if (path.includes("providers/github/installations")) return route.fulfill({ json: [] }); @@ -109,10 +114,13 @@ test("X owner can test safely and replace app credentials before same-account re }); await page.route("https://x.com/**", route => route.fulfill({ contentType: "text/html", body: "X consent" })); await page.goto(origin + "/settings/integrations"); - await page.getByRole("button", { name: "Test connection" }).click(); + await page.getByLabel("Actions for X · Work account",{exact:true}).click(); + await page.getByRole("button", { name: "Test connection",exact:true }).click(); await page.getByRole("status").filter({ hasText: "X could not verify the connection" }).waitFor(); assert.equal(tested, 1); + await page.getByLabel("Actions for X · Work account",{exact:true}).click(); await page.getByRole("button", { name: "Replace app credentials" }).click(); + await page.getByRole("dialog",{name:"Replace X app credentials",exact:true}).waitFor(); await page.getByLabel("Replacement OAuth 2.0 Client ID").fill("replacement-client"); await page.getByLabel("Replacement OAuth 2.0 Client Secret").fill("replacement-secret"); await page.getByRole("button", { name: "Replace credentials and reauthorize" }).click(); diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index a7bfe2a3..36726f5a 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -754,6 +754,36 @@ MCP is a selected tool surface, **not full REST parity**. Signup, verification, Job creation and updates accept optional `runScopes`, an array of Factorize API scope names. Omitting it on update preserves the current policy; an explicit empty array grants no application scopes to future runs. Jobs granted `jobs:write` can configure this field too. See [run permissions](https://docs.factorize.sh/work/manual-invocation-permissions) for defaults and credential snapshot semantics. +## Integration API access + +In **Settings → Integrations**, each connected API integration has an +**Available by default** checkbox. Checked integrations are available immediately +to connected MCP clients. Unchecked integrations require approval for each client +connection. Existing approvals remain valid when default access is unchecked. +Use the integration's **⋯ → MCP access…** action to disable access entirely; +disabling or disconnecting revokes approvals, and re-enabling requires fresh consent. +Job runs retain their independent, explicit credential selections. + +`get_api_reflection` lists integration references and access instructions. +`request_api` forwards a relative path using the selected integration's stored +credential. The same policy applies to Bearer APIs, GitHub, Linear, model accounts, +Fly.io, exe.dev, Amp, ClickUp, and X. Credentials stay on the server. + +| Integration | Path convention | +| --- | --- | +| Bearer API | Relative to its configured HTTPS origin | +| GitHub | GitHub API path, with existing Git/raw/archive routing | +| Linear | `/graphql` with a JSON GraphQL body | +| Model account | Relative to the account's model API prefix, such as `/responses` | +| Fly.io | Fly Machines API path, such as `/v1/apps` | +| exe.dev | `POST /exec` with a `text/plain` command body | +| Amp | Relative to the configured API base, defaulting to `/api/cloud/v1` | +| ClickUp | Relative to `/api/v2`, such as `/team` | +| X | Supported API v2 paths, such as `/2/users/me`, bounded by the connected account’s granted OAuth scopes | + +Cloudflare Tail connections contain inbound webhook signing secrets, not +Cloudflare API credentials, so they do not expose an outbound API. + ## Jobs, triggers, runs, and targets Source: https://docs.factorize.sh/concepts diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index e4e29e01..f5a63aea 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -185,3 +185,33 @@ Tool errors are `code: message`. `invalid_token` needs reauthorization; `insuffi MCP is a selected tool surface, **not full REST parity**. Signup, verification, integration credential management, authorized-client management, provider resource selection, schedule preview, specialized run status/trace pagination and retained-artifact replay have no corresponding tools in this inventory. Some REST operations require an interactive owner session rather than delegated tokens. Use the browser for setup/resource selection and [REST reference](/api/reference) for exact routes, restrictions and schemas. MCP cannot pass your conversational client's credentials to the execution agent. Job creation and updates accept optional `runScopes`, an array of Factorize API scope names. Omitting it on update preserves the current policy; an explicit empty array grants no application scopes to future runs. Jobs granted `jobs:write` can configure this field too. See [run permissions](/work/manual-invocation-permissions) for defaults and credential snapshot semantics. + +## Integration API access + +In **Settings → Integrations**, each connected API integration has an +**Available by default** checkbox. Checked integrations are available immediately +to connected MCP clients. Unchecked integrations require approval for each client +connection. Existing approvals remain valid when default access is unchecked. +Use the integration's **⋯ → MCP access…** action to disable access entirely; +disabling or disconnecting revokes approvals, and re-enabling requires fresh consent. +Job runs retain their independent, explicit credential selections. + +`get_api_reflection` lists integration references and access instructions. +`request_api` forwards a relative path using the selected integration's stored +credential. The same policy applies to Bearer APIs, GitHub, Linear, model accounts, +Fly.io, exe.dev, Amp, ClickUp, and X. Credentials stay on the server. + +| Integration | Path convention | +| --- | --- | +| Bearer API | Relative to its configured HTTPS origin | +| GitHub | GitHub API path, with existing Git/raw/archive routing | +| Linear | `/graphql` with a JSON GraphQL body | +| Model account | Relative to the account's model API prefix, such as `/responses` | +| Fly.io | Fly Machines API path, such as `/v1/apps` | +| exe.dev | `POST /exec` with a `text/plain` command body | +| Amp | Relative to the configured API base, defaulting to `/api/cloud/v1` | +| ClickUp | Relative to `/api/v2`, such as `/team` | +| X | Supported API v2 paths, such as `/2/users/me`, bounded by the connected account’s granted OAuth scopes | + +Cloudflare Tail connections contain inbound webhook signing secrets, not +Cloudflare API credentials, so they do not expose an outbound API. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 9321f6a8..1ab39c8a 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -4627,6 +4627,10 @@ paths: type: array items: type: string + tags: + type: array + items: + type: string agentKind: type: string enum: @@ -5084,6 +5088,10 @@ paths: type: array items: type: string + tags: + type: array + items: + type: string agentKind: type: string enum: @@ -5123,6 +5131,10 @@ paths: type: array items: type: string + tags: + type: array + items: + type: string agentKind: type: string enum: @@ -11302,6 +11314,8 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + credentialId: + type: string name: type: string description: @@ -11315,6 +11329,11 @@ paths: - github - linear - model + - fly + - exe + - amp + - clickup + - x policy: type: string enum: @@ -11339,6 +11358,7 @@ paths: type: string required: - id + - credentialId - name - description - kind @@ -11618,6 +11638,8 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + credentialId: + type: string name: type: string description: @@ -11631,6 +11653,11 @@ paths: - github - linear - model + - fly + - exe + - amp + - clickup + - x policy: type: string enum: @@ -11647,6 +11674,7 @@ paths: type: string required: - id + - credentialId - name - description - kind @@ -11711,6 +11739,8 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + credentialId: + type: string name: type: string description: @@ -11724,6 +11754,11 @@ paths: - github - linear - model + - fly + - exe + - amp + - clickup + - x policy: type: string enum: @@ -11740,6 +11775,7 @@ paths: type: string required: - id + - credentialId - name - description - kind diff --git a/scripts/agent-api-runtime.test.mjs b/scripts/agent-api-runtime.test.mjs index cb67c41e..318e9fcb 100644 --- a/scripts/agent-api-runtime.test.mjs +++ b/scripts/agent-api-runtime.test.mjs @@ -31,7 +31,20 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const observed=[];let releaseStream; try { await admin.query(`CREATE DATABASE "${name}"`);address.pathname='/'+name;db=new pg.Client({connectionString:address.href});await db.connect(); - for(const file of (await readdir('packages/api/migrations')).filter(file=>/^\d+.*\.sql$/.test(file)).sort()) await db.query(await readFile('packages/api/migrations/'+file,'utf8')); + const backfillTenant=randomUUID(); + for(const file of (await readdir('packages/api/migrations')).filter(file=>/^\d+.*\.sql$/.test(file)).sort()) { + await db.query(await readFile('packages/api/migrations/'+file,'utf8')); + if(file==='0058_x_credential_versions.sql') { + await db.query("INSERT INTO app.tenants(id,name) VALUES($1,'Migration fixture')",[backfillTenant]); + for(const kind of ['exe:existing','amp:existing','clickup','cloudflare-tail:existing']) await db.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,$2,'cipher')",[backfillTenant,kind]); + await db.query("INSERT INTO app.fly_connections(tenant_id,organization_slug,organization_name,encrypted_token) VALUES($1,'existing','Existing','cipher')",[backfillTenant]); + for (const status of ['connected','pending']) await db.query("INSERT INTO app.x_connections(tenant_id,id,name,client_id,scopes,encrypted_secret,status) VALUES($1,$2,$3,'fixture',ARRAY['users.read'],'cipher',$3)",[backfillTenant,randomUUID(),status]); + } + } + const backfilled=(await db.query('SELECT kind,policy,available FROM app.agent_integrations WHERE tenant_id=$1 ORDER BY kind,available',[backfillTenant])).rows; + assert.deepEqual(backfilled.map(row=>row.kind),['amp','clickup','exe','fly','x','x']); + assert.deepEqual(backfilled.filter(row=>row.kind==='x').map(row=>row.available),[false,true]); + assert.ok(backfilled.every(row=>row.policy==='requestable'),'migration preserves explicit consent by default'); await db.query('INSERT INTO app.tenants(id,name) VALUES($1,$2)',[tenant,'Agent fixture']); await db.query('INSERT INTO app.auth_users(id,email,email_verified) VALUES($1,$2,true)',[user,'agent@example.test']); await db.query("INSERT INTO app.members(tenant_id,user_id,email,role) VALUES($1,$2,$3,'owner')",[tenant,user,'agent@example.test']); @@ -81,7 +94,7 @@ test('agent API OAuth, policy, connection isolation, run identity and response l try {const data=await readFile(resolve('packages/app/dist','.'+path));return new Response(data,{headers:{'Content-Type':path.endsWith('.js')?'application/javascript':path.endsWith('.css')?'text/css':'text/html'}});}catch{return new Response('Not found',{status:404});} }}, outboundService:async request=>{ - const target=new URL(request.url);assert.ok(['fixture.upstream.com','api.github.com','github.com','raw.githubusercontent.com','codeload.github.com','api.linear.app','api.openai.com','oidc.fly.io','auth.openai.com','chatgpt.com'].includes(target.hostname),'Unexpected upstream '+target.hostname); + const target=new URL(request.url);assert.ok(['fixture.upstream.com','api.github.com','github.com','raw.githubusercontent.com','codeload.github.com','api.linear.app','api.openai.com','oidc.fly.io','auth.openai.com','chatgpt.com','exe.dev','ampcode.com','api.clickup.com','api.machines.dev','custom.amp.upstream.com','api.x.com'].includes(target.hostname),'Unexpected upstream '+target.hostname); const headers=new Headers(request.headers);headers.set('x-fixture-target',target.href); const response=await fetch('http://127.0.0.1:'+upstream.address().port+target.pathname+target.search,{method:request.method,headers,body:request.method==='GET'||request.method==='HEAD'?undefined:await request.arrayBuffer(),redirect:'manual'}); return new Response(response.body,{status:response.status,headers:response.headers}); @@ -103,7 +116,7 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const verifier=randomBytes(32).toString('base64url'),query=new URLSearchParams({response_type:'code',client_id:clientId,redirect_uri:'http://127.0.0.1/callback',scope:scopes.join(' '),state:randomUUID(),code_challenge:createHash('sha256').update(verifier).digest('base64url'),code_challenge_method:'S256',resource:origin+'/mcp'}); const page=await context.newPage();page.setDefaultTimeout(15000); await page.goto(origin+'/authorize?'+query);await page.getByRole('heading',{name:'Authorize Agent fixture',exact:true}).waitFor(); - if(scopes.some(scope=>scope.startsWith('integration:'))) assert.ok(await page.getByText('Requestable API',{exact:false}).count()); + for (const scope of scopes.filter(scope=>scope.startsWith('integration:'))) assert.ok(await page.getByLabel(scope,{exact:true}).count()); if(narrow) await page.getByLabel(narrow,{exact:true}).uncheck(); await page.getByRole('button',{name:decision==='allow'?'Allow':'Deny',exact:true}).click();await page.waitForURL('http://127.0.0.1/callback?**'); const destination=new URL(page.url());await page.close(); @@ -174,6 +187,78 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const row=(await db.query('SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND kind=$2',[tenant,kind])).rows[0];await policy(row,'baseline'); const result=await request(first,row,path);assert.equal(result.result.status,200,result.text);assert.equal(observed.at(-1).target,expected);assert.equal(observed.at(-1).headers.authorization,'Bearer '+auth); } + // Execution and task providers use the same default, consent and revocation rules. + const extraProviders = [ + {kind:'exe', key:'exe:vm-api', credentialId:'vm-api', value:{apiToken:'exe-private'}, path:'/exec', target:'https://exe.dev/exec', authorization:'Bearer exe-private'}, + {kind:'amp', key:'amp:amp-api', credentialId:'amp-api', value:{accessToken:'amp-private',project:'fixture'}, path:'/projects?q=1', target:'https://ampcode.com/api/cloud/v1/projects?q=1', authorization:'Bearer amp-private'}, + {kind:'amp', key:'amp:custom-api', credentialId:'custom-api', value:{accessToken:'custom-private',project:'fixture',apiBaseUrl:'https://custom.amp.upstream.com/custom/v2'}, path:'/runs', target:'https://custom.amp.upstream.com/custom/v2/runs', authorization:'Bearer custom-private'}, + {kind:'clickup', key:'clickup', credentialId:'clickup', value:{accessToken:'clickup-private'}, path:'/team', target:'https://api.clickup.com/api/v2/team', authorization:'clickup-private'}, + {kind:'fly', credentialId:'fly', path:'/v1/apps?org_slug=fixture', target:'https://api.machines.dev/v1/apps?org_slug=fixture', authorization:'Bearer fly-private'}, + ]; + for (const provider of extraProviders) { + if (provider.key) await db.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,$2,$3)",[tenant,provider.key,encrypt(JSON.stringify(provider.value))]); + else await db.query("INSERT INTO app.fly_connections(tenant_id,organization_slug,organization_name,encrypted_token) VALUES($1,'fixture','Fixture',$2)",[tenant,encrypt('fly-private')]); + const row=(await db.query('SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND kind=$2 AND credential_id=$3',[tenant,provider.kind,provider.credentialId])).rows[0]; + assert.ok(row,provider.kind+' is registered'); assert.equal(row.policy,'requestable'); + const count=observed.length; + assert.equal((await request(first,row,provider.path)).status,403); assert.equal(observed.length,count,'unapproved calls never reach upstream'); + const approved=await authorize(['jobs:read',scopes(row)]); + const forwarded=await request(approved,row,provider.path,{method:'POST',body:'fixture command',headers:{Authorization:'caller-secret',Cookie:'private-cookie','Content-Type':'text/plain'}}); + assert.equal(forwarded.result.status,200,forwarded.text); assert.equal(observed.at(-1).target,provider.target); assert.equal(observed.at(-1).headers.authorization,provider.authorization); assert.equal(observed.at(-1).headers.cookie,undefined); assert.equal(observed.at(-1).body,'fixture command'); + assert.ok(!forwarded.text.includes(provider.authorization)); + await policy(row,'baseline'); assert.equal((await request(first,row,provider.path)).result.status,200); + await policy(row,'disabled'); assert.equal((await request(approved,row,provider.path)).status,403); + await policy(row,'requestable'); assert.equal((await request(approved,row,provider.path)).status,403,'disable revokes old consent for '+provider.kind); + await policy(row,'baseline'); + if (provider.kind==='amp' || provider.kind==='clickup') { + const beforeEscape=observed.length; + assert.ok((await request(first,row,'/../outside')).text.includes('credential_unavailable')); + assert.equal(observed.length,beforeEscape,'configured API prefix cannot be escaped'); + } + // Token rotation preserves identity; disconnect/reconnect invalidates approvals. + if(provider.kind==='fly') { + const before=(await db.query('SELECT epoch FROM app.agent_integrations WHERE id=$1',[row.id])).rows[0].epoch; + await db.query("UPDATE app.fly_connections SET organization_slug='other',organization_name='Other' WHERE tenant_id=$1",[tenant]); + assert.equal((await db.query('SELECT epoch FROM app.agent_integrations WHERE id=$1',[row.id])).rows[0].epoch,before+1,'switching Fly organizations revokes prior approvals'); + } + const epoch=(await db.query('SELECT epoch FROM app.agent_integrations WHERE id=$1',[row.id])).rows[0].epoch; + if (provider.key) { + await db.query('UPDATE app.connections SET encrypted_value=$3 WHERE tenant_id=$1 AND kind=$2',[tenant,provider.key,encrypt(JSON.stringify(provider.value))]); + assert.equal((await db.query('SELECT epoch FROM app.agent_integrations WHERE id=$1',[row.id])).rows[0].epoch,epoch); + await db.query('DELETE FROM app.connections WHERE tenant_id=$1 AND kind=$2',[tenant,provider.key]); + } else await db.query('DELETE FROM app.fly_connections WHERE tenant_id=$1',[tenant]); + assert.equal((await request(first,row,provider.path)).status,403); + const disconnected=(await db.query('SELECT * FROM app.agent_integrations WHERE id=$1',[row.id])).rows[0]; + assert.equal(disconnected.available,false); assert.equal(disconnected.epoch,epoch+1); + } + const listed=await json('/api/v1/integration-api-policies','GET',undefined,owner); + for(const provider of extraProviders) assert.ok(listed.body.integrations.some(row=>row.kind===provider.kind && row.credentialId===provider.credentialId)); + // Inbound webhook signing secrets are never registered as outbound APIs. + await db.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,'cloudflare-tail:fixture',$2)",[tenant,encrypt(JSON.stringify({signingSecret:'tail-private'}))]); + assert.equal((await db.query("SELECT 1 FROM app.agent_integrations WHERE tenant_id=$1 AND credential_id='fixture'",[tenant])).rowCount,0); + // X uses the same client policies while retaining upstream OAuth scope restrictions. + const xId=randomUUID(); + const xCredential={clientSecret:'x-client-private',accessToken:'x-private',refreshToken:'x-refresh',expiresAt:new Date(Date.now()+3600000).toISOString()}; + await db.query("INSERT INTO app.x_connections(tenant_id,id,name,client_id,scopes,encrypted_secret,status,account_id,account_handle,granted_scopes) VALUES($1,$2,'Social account','fixture',ARRAY['users.read','tweet.read','offline.access'],$3,'connected','123','fixture',ARRAY['users.read','tweet.read','offline.access'])",[tenant,xId,encrypt(JSON.stringify(xCredential))]); + const xRow=(await db.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND kind='x' AND credential_id=$2",[tenant,xId])).rows[0]; + assert.equal(xRow.available,true);assert.equal((await request(first,xRow,'/2/users/me')).status,403); + const xApproved=await authorize(['jobs:read',scopes(xRow)]); + assert.equal((await request(xApproved,xRow,'/2/users/me')).result.status,200);assert.equal(observed.at(-1).target,'https://api.x.com/2/users/me');assert.equal(observed.at(-1).headers.authorization,'Bearer x-private'); + const xCount=observed.length; + const xWrite=await request(xApproved,xRow,'/2/tweets',{method:'POST',body:'{}'}); + assert.equal(xWrite.result,undefined,'MCP consent cannot expand X OAuth scopes');assert.match(xWrite.text,/This X connection does not grant tweet.write/); + const xManagement=await request(xApproved,xRow,'/2/oauth2/token',{method:'POST',body:'{}'}); + assert.equal(xManagement.result,undefined,'credential management is not proxyable');assert.match(xManagement.text,/not authorized/);assert.equal(observed.length,xCount); + await policy(xRow,'baseline');assert.equal((await request(first,xRow,'/2/users/me')).result.status,200); + await policy(xRow,'disabled');assert.equal((await request(xApproved,xRow,'/2/users/me')).status,403); + await policy(xRow,'requestable');assert.equal((await request(xApproved,xRow,'/2/users/me')).status,403); + const oldEpoch=(await db.query('SELECT epoch FROM app.agent_integrations WHERE id=$1',[xRow.id])).rows[0].epoch; + await db.query("UPDATE app.x_connections SET status='reconnect_required',credential_version=credential_version+1 WHERE tenant_id=$1 AND id=$2",[tenant,xId]); + assert.equal((await db.query('SELECT epoch FROM app.agent_integrations WHERE id=$1',[xRow.id])).rows[0].epoch,oldEpoch+1); + await db.query("UPDATE app.x_connections SET status='connected' WHERE tenant_id=$1 AND id=$2",[tenant,xId]); + assert.equal((await request(xApproved,xRow,'/2/users/me')).status,403,'replacing X credentials invalidates old MCP approval'); + // Restore a baseline entry for run-selection isolation checks below. + await policy(xRow,'baseline'); const github=(await db.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND kind='github'",[tenant])).rows[0]; for(const [path,target] of [['/owner/repo.git/info/refs','https://github.com/owner/repo.git/info/refs'],['/raw/owner/repo/main/file','https://raw.githubusercontent.com/owner/repo/main/file'],['/archive/owner/repo/zip/main','https://codeload.github.com/owner/repo/zip/main']]) { assert.equal((await request(first,github,path)).result.status,200);assert.equal(observed.at(-1).target,target);