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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 38 additions & 64 deletions TODO.md

Large diffs are not rendered by default.

725 changes: 722 additions & 3 deletions packages/api-client/src/schema.d.ts

Large diffs are not rendered by default.

23 changes: 23 additions & 0 deletions packages/api/migrations/0095_oauth_apps.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
CREATE TABLE app.oauth_apps (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE,
name text NOT NULL,
redirect_uris text[] NOT NULL,
is_public boolean NOT NULL DEFAULT false,
enabled boolean NOT NULL DEFAULT true,
secret_digest text,
secret_version integer NOT NULL DEFAULT 0
);
CREATE INDEX oauth_apps_team ON app.oauth_apps(tenant_id);
CREATE TABLE app.oauth_app_connections (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
app_id uuid NOT NULL REFERENCES app.oauth_apps(id) ON DELETE CASCADE,
tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE,
session_version integer NOT NULL,
scopes text[] NOT NULL,
authorized_at timestamptz NOT NULL DEFAULT now(),
revoked_at timestamptz
);
CREATE INDEX oauth_app_connections_owner ON app.oauth_app_connections(tenant_id, user_id);
INSERT INTO app.schema_migrations(version) VALUES ('0095_oauth_apps');
39 changes: 39 additions & 0 deletions packages/api/migrations/0096_oidc_provider.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
CREATE TABLE app.oidc_requests (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
app_id uuid NOT NULL REFERENCES app.oauth_apps(id) ON DELETE CASCADE,
redirect_uri text NOT NULL,
challenge text NOT NULL,
state text,
nonce text,
scopes text[] NOT NULL,
expires_at timestamptz NOT NULL,
decided_at timestamptz
);
CREATE INDEX oidc_requests_expiry ON app.oidc_requests(expires_at);
CREATE TABLE app.oidc_codes (
digest text PRIMARY KEY,
connection_id uuid NOT NULL REFERENCES app.oauth_app_connections(id) ON DELETE CASCADE,
secret_version integer NOT NULL,
redirect_uri text NOT NULL,
challenge text NOT NULL,
nonce text,
expires_at timestamptz NOT NULL
);
CREATE INDEX oidc_codes_expiry ON app.oidc_codes(expires_at);
CREATE TABLE app.oidc_tokens (
access_digest text PRIMARY KEY,
refresh_digest text UNIQUE,
connection_id uuid NOT NULL REFERENCES app.oauth_app_connections(id) ON DELETE CASCADE,
secret_version integer NOT NULL,
scopes text[] NOT NULL,
access_expires_at timestamptz NOT NULL,
refresh_expires_at timestamptz
);
CREATE INDEX oidc_tokens_expiry ON app.oidc_tokens(access_expires_at, refresh_expires_at);
CREATE TABLE app.oidc_signing_key (
singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
kid uuid NOT NULL DEFAULT gen_random_uuid(),
public_key jsonb NOT NULL,
encrypted_private_key text NOT NULL
);
INSERT INTO app.schema_migrations(version) VALUES ('0096_oidc_provider');
2 changes: 1 addition & 1 deletion packages/api/src/access-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { databaseFor } from "./postgres/database";
import { AccessTokenRepository } from "./postgres/access-token-repository";

export const ACCESS_SCOPES = ["team:read", "team:write", "triggers:read", "triggers:write", "runs:read", "runs:invoke", "runs:start", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const;
export const AGENT_SCOPES = [...ACCESS_SCOPES, "proxy:use", "vm:grant"] as const;
export const AGENT_SCOPES = [...ACCESS_SCOPES, "proxy:use", "vm:grant", "apps:manage"] as const;
export type AccessScope = typeof ACCESS_SCOPES[number];
export function normalizeScopes(scopes: readonly string[]): string[] {
return [...new Set(scopes.filter(scope => (AGENT_SCOPES as readonly string[]).includes(scope) || isIntegrationScope(scope)))];
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/agent-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import type { z } from "zod";
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}`;
type ConnectionPolicy = { integration_overrides: Record<string, string | false>; disabled_scopes: string[] };
function connectionAccess(row: AgentIntegration, scopes: string[], policy: ConnectionPolicy) {
export function connectionAccess(row: AgentIntegration, scopes: string[], policy: ConnectionPolicy) {
const scope = requiredIntegrationScope(row);
if (policy.disabled_scopes.includes("proxy:use") || policy.integration_overrides[row.id] === false || row.policy === "disabled" || !row.available) return "blocked";
return row.policy === "baseline" || policy.integration_overrides[row.id] === scope || scopes.includes(scope) ? "granted" : "requestable";
Expand Down
57 changes: 55 additions & 2 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@ import { queryOf } from "./query-params";
import { launchPayloadResponse } from "./launch-payload";
import { searchResponse } from "./search-contracts";
import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api";
import { exeConnection, integrationStatus, clientPermissionsInput, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts";
import { exeConnection, integrationStatus, clientPermissionsUpdate, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts";
import { eventAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts";
import { runSummaryResponse, runPageResponse, runStatusResponse, fullRunResponse, revisionTracePage, revisionTraceQuery, runtimeContextResponse, runtimeIntegrationsResponse } from "./run-read-contracts";
import { triggerPageQuery, triggerSummaryPage, triggerSelectorPage, triggerResponse, triggerUpdateInput } from "./job-contracts";
import { projectGraphResponse } from "./project-graph-contracts";
import { z } from "zod";
import { oidcConsentInput, oidcConsentPreview } from "./oidc-provider";
import { appRegistrationInput, appRegistrationUpdate, appSecret, connectedApp, registeredApp } from "./apps-contracts";
import { vmAttachments } from "./vm-attachment-contracts";
import type { ApiService } from "./flow-service";
import {
triggerInputSchema,
Expand Down Expand Up @@ -675,7 +678,7 @@ export const API_ROUTES: RouteContract[] = [
route("PUT", "/api/v1/access/authorizations/{grantId}/permissions", "triggers:write", {
summary: "Edit an OAuth connection’s scopes and integration access",
responses: {"200": {description: "Permissions saved", content: {"application/json": {schema: jsonSchema(okResult, "output")}}}},
}, (service, {params, body}) => service.updateClientPermissions(params.grantId, body), {ownerSession: true, body: clientPermissionsInput}),
}, (service, {params, body}) => service.updateClientPermissions(params.grantId, body), {ownerSession: true, body: clientPermissionsUpdate}),
route("DELETE", "/api/v1/access/authorizations/{grantId}", "triggers:write", {summary:"Revoke one isolated OAuth connection", description:"Other connections, including copies of the same client, retain their approvals.",responses:{"200":{description:"Authorization revoked",content:{"application/json":{schema:jsonSchema(z.object({revoked:z.number().int()}),"output")}}}}}, (service,{params})=>service.revokeOAuthAuthorization(params.grantId), {ownerSession:true}),
route(
"DELETE",
Expand Down Expand Up @@ -1085,6 +1088,56 @@ export const API_ROUTES: RouteContract[] = [
},
(service, { params }) => service.getWebhookDelivery(params.deliveryId),
),
route("GET", "/api/v1/app-consent/{requestId}", "team:read", {
summary: "Preview a registered app sign-in request",
responses: { "200": { description: "Requested app permissions", content: { "application/json": { schema: jsonSchema(oidcConsentPreview, "output") } } } },
}, (service, { params }) => service.inspectAppConsent(params.requestId), { parameters: z.object({ requestId: z.uuid() }), ownerSession: true }),
route("POST", "/api/v1/app-consent/decision", "team:read", {
summary: "Allow or deny a registered app sign-in request",
responses: { "200": { description: "Registered redirect destination", content: { "application/json": { schema: jsonSchema(z.object({ redirectTo: z.string() }), "output") } } } },
}, (service, { body }) => service.decideAppConsent(body), { body: oidcConsentInput, ownerSession: true }),
route("GET", "/api/v1/apps", "apps:manage", {
summary: "List the team's app registrations",
responses: { "200": { description: "Registered apps", content: { "application/json": { schema: jsonSchema(z.array(registeredApp), "output") } } } },
}, service => service.listApps()),
route("POST", "/api/v1/apps", "apps:manage", {
summary: "Register a server-side application",
responses: { "200": { description: "Registered app", content: { "application/json": { schema: jsonSchema(registeredApp, "output") } } } },
}, (service, { body }) => service.createApp(body), { body: appRegistrationInput }),
route("GET", "/api/v1/apps/{appId}", "apps:manage", {
summary: "Read an app registration",
responses: { "200": { description: "Registered app", content: { "application/json": { schema: jsonSchema(registeredApp, "output") } } } },
}, (service, { params }) => service.getApp(params.appId), { parameters: z.object({ appId: z.uuid() }) }),
route("PUT", "/api/v1/apps/{appId}", "apps:manage", {
summary: "Change an app registration, its visibility, or its enabled state",
responses: { "200": { description: "Registered app", content: { "application/json": { schema: jsonSchema(registeredApp, "output") } } } },
}, (service, { params, body }) => service.updateApp(params.appId, body), { parameters: z.object({ appId: z.uuid() }), body: appRegistrationUpdate }),
route("POST", "/api/v1/apps/{appId}/secret", "apps:manage", {
summary: "Issue or rotate a client secret in a browser session",
responses: { "200": { description: "One-time secret", content: { "application/json": { schema: jsonSchema(appSecret, "output") } } } },
}, (service, { params }) => service.rotateAppSecret(params.appId), { parameters: z.object({ appId: z.uuid() }), ownerSession: true }),
route("GET", "/api/v1/app-connections", "team:read", {
summary: "List sign-in apps authorized by the current user",
responses: { "200": { description: "Connected apps", content: { "application/json": { schema: jsonSchema(z.array(connectedApp), "output") } } } },
}, service => service.listConnectedApps(), { ownerSession: true }),
route("DELETE", "/api/v1/app-connections/{connectionId}", "team:write", {
summary: "Revoke one sign-in app connection",
responses: { "200": { description: "Connection revoked", content: { "application/json": { schema: jsonSchema(okResult, "output") } } } },
}, (service, { params }) => service.revokeConnectedApp(params.connectionId), { parameters: z.object({ connectionId: z.uuid() }), ownerSession: true }),
route("GET", "/api/v1/vms", "runs:read", {
summary: "List VMs with active Factorize proxy access",
description: "Requires an interactive owner session. Reports access status from Factorize records.",
responses: { "200": { description: "Active VM access attachments", content: { "application/json": { schema: jsonSchema(vmAttachments, "output") } } } },
}, service => service.listProxyVms()),
route("GET", "/api/v1/runs/{runId}/vms", "runs:read", {
summary: "List a run's current and historical VM access",
responses: { "200": { description: "Run VM attachments", content: { "application/json": { schema: jsonSchema(vmAttachments, "output") } } } },
}, (service, { params }) => service.listRunVms(params.runId), { parameters: z.object({ runId: z.guid() }) }),
route("GET", "/api/v1/access/authorizations/{grantId}/vms", "runs:read", {
summary: "List current and historical VM access delegated by an MCP connection",
description: "Requires an interactive owner session.",
responses: { "200": { description: "Connection VM attachments", content: { "application/json": { schema: jsonSchema(vmAttachments, "output") } } } },
}, (service, { params }) => service.listClientVms(params.grantId), { parameters: z.object({ grantId: z.string().min(1).max(255) }) }),
route("GET", "/api/v1/runs/{runId}/status", "runs:read", {
summary: "Get lightweight run status",
description: "Only bounded encrypted prompt/script previews are decrypted; full prompt, invocation context, artifacts, activity and diagnostics stay in the detail operation. Continue polling terminal runs while finalizing is true. trace_revision changes on generation transition or canonical projection/replay; live appends retain the revision. Full detail remains available at GET /runs/{runId}.",
Expand Down
36 changes: 36 additions & 0 deletions packages/api/src/apps-contracts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { z } from "zod";

const redirectUri = z.string().max(2048).refine(value => {
try {
const parsed = new URL(value);
return (parsed.protocol === "https:" ||
(parsed.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(parsed.hostname))) &&
!parsed.username && !parsed.password && !value.includes("#");
} catch {
return false;
}
}, "Use an HTTPS callback URL, or an HTTP loopback URL for local development.");

export const appRegistrationInput = z.object({
name: z.string().trim().min(1).max(100),
redirectUris: z.array(redirectUri).min(1).max(10).refine(values => new Set(values).size === values.length),
public: z.boolean().default(false),
}).strict();

export const appRegistrationUpdate = appRegistrationInput.extend({ enabled: z.boolean() });
export const registeredApp = z.object({
id: z.uuid(),
name: z.string(),
redirectUris: z.array(z.string()),
public: z.boolean(),
enabled: z.boolean(),
secretConfigured: z.boolean(),
});
export const appSecret = z.object({ clientId: z.uuid(), clientSecret: z.string() });
export const connectedApp = z.object({
id: z.uuid(),
appId: z.uuid(),
name: z.string(),
scopes: z.array(z.string()),
authorizedAt: z.iso.datetime(),
});
4 changes: 2 additions & 2 deletions packages/api/src/auth-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { databaseFor } from "./postgres/database";
import { readSession, requestCookie, signSession, type Session } from "./session";
import type { Env } from "./types";

export const SESSION_SCOPES = ACCESS_SCOPES;
export const SESSION_SCOPES = [...ACCESS_SCOPES, "apps:manage"] as const;
const email = z.string().trim().toLowerCase().email().max(320);
const password = z.string().min(12).max(200).meta({ writeOnly: true });
const connection = z.uuid().optional();
Expand Down Expand Up @@ -48,7 +48,7 @@ export function safeReturnTo(value: string | undefined): string {
try {
const url = new URL(value, "https://local.invalid");
if (url.origin !== "https://local.invalid") return "/integrations";
if (!/^\/(?:authorize|device|integrations|skills(?:\/[^/]+(?:\/(?:runs|settings(?:\/(?:general|vm|permissions|trigger))?))?)?|triggers(?:\/[^/]+(?:\/(?:edit|settings(?:\/(?:general|vm|context|permissions|events))?))?)?|runs(?:\/[^/]+(?:\/(?:trace|info))?)?|settings(?:\/(?:profile|vm|permissions|skills|vm-presets|integrations|api-keys(?:\/new)?|authorized-clients|password))?)$/.test(url.pathname)) return "/integrations";
if (!/^\/(?:authorize|device|integrations|app-consent|vms|clients(?:\/[^/]+)?|apps(?:\/registered)?|skills(?:\/[^/]+(?:\/(?:runs|settings(?:\/(?:general|vm|permissions|trigger))?))?)?|triggers(?:\/[^/]+(?:\/(?:edit|settings(?:\/(?:general|vm|context|permissions|events))?))?)?|runs(?:\/[^/]+(?:\/(?:trace|info|vms))?)?|settings(?:\/(?:profile|vm|permissions|skills|vm-presets|integrations|api-keys(?:\/new)?|authorized-clients|password))?)$/.test(url.pathname)) return "/integrations";
return url.pathname + url.search + url.hash;
} catch { return "/integrations"; }
}
Expand Down
Loading