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
146 changes: 144 additions & 2 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1806,6 +1806,54 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/agent/vm-grants": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Delegate selected proxy integrations to an exe.dev VM
* @description Requires an OAuth agent with proxy:use, vm:grant and access to the provider and each selected integration. Expires with the issuing access token.
*
* Requires the vm:grant and proxy:use scopes.
*
* Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session.
*/
post: operations["post_api_v1_agent_vm_grants"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/agent/vm-grants/{grantId}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/**
* Revoke an external VM grant
* @description Only the issuing OAuth grant can revoke. Access stops before provider cleanup.
*
* Requires the vm:grant scope.
*
* Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session.
*/
delete: operations["delete_api_v1_agent_vm_grants_grantId"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/agent/reflection": {
parameters: {
query?: never;
Expand Down Expand Up @@ -1839,7 +1887,7 @@ export interface paths {
put?: never;
/**
* Make an authorized credential-injected API request
* @description Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 24 hours and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects.
* @description OAuth requires proxy:use. An external VM sends its short-lived exe.dev WIF bearer token, X-Factorize-VM-Grant and X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 24 hours and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects.
*
* Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session.
*/
Expand All @@ -1861,7 +1909,7 @@ export interface paths {
put?: never;
/**
* Read up to 64 KiB of an identity-bound retained response
* @description Rechecks authorization, integration revocation epoch, tenant, identity and 24-hour expiry. Chunks are always base64 so arbitrary byte offsets are safe.
* @description Accepts the same OAuth, run or external VM authentication as the request endpoint. Rechecks authorization, integration revocation epoch, tenant, identity and 24-hour expiry. Chunks are always base64 so arbitrary byte offsets are safe.
*
* Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session.
*/
Expand Down Expand Up @@ -7647,6 +7695,91 @@ export interface operations {
503: components["responses"]["Error503"];
};
};
post_api_v1_agent_vm_grants: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** Format: uuid */
providerIntegrationId: string;
vm: string;
integrationIds: string[];
idempotencyKey: string;
};
};
};
responses: {
/** @description Verified VM grant */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** Format: uuid */
grantId: string;
vm: string;
integrationIds: string[];
expiresAt: string;
/** Format: uri */
tokenUrl: string;
proofFile: string;
/** Format: uri */
requestUrl: string;
instructions: string;
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
415: components["responses"]["Error415"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
delete_api_v1_agent_vm_grants_grantId: {
parameters: {
query?: never;
header?: never;
path: {
grantId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Revoked grant */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** Format: uuid */
grantId: string;
revoked: boolean;
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
get_api_v1_agent_reflection: {
parameters: {
query?: never;
Expand All @@ -7670,6 +7803,13 @@ export interface operations {
kind: "oauth" | "run";
};
scopes: string[];
proxy: {
/** Format: uri */
requestUrl: string;
/** Format: uri */
readResponseUrl: string;
authentication: string;
};
integrations: {
/** Format: uuid */
id: string;
Expand All @@ -7686,6 +7826,8 @@ export interface operations {
/** @enum {string} */
access: "granted" | "requestable" | "unavailable";
instructions: string;
/** @constant */
vmGrantProvider?: "exe.dev";
}[];
};
};
Expand Down
14 changes: 14 additions & 0 deletions packages/api/migrations/0060_external_vm_grants.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
ALTER TABLE app.agent_identities DROP CONSTRAINT agent_identities_kind_check;
ALTER TABLE app.agent_identities ADD CHECK(kind IN ('oauth','run','vm'));
CREATE TABLE app.vm_grants (
tenant_id uuid NOT NULL, id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
parent_id uuid NOT NULL, provider_id uuid NOT NULL, provider_epoch integer NOT NULL,
vm text NOT NULL, permissions jsonb NOT NULL, parent_scopes jsonb NOT NULL,
request_key text NOT NULL, issuer text, subject text, proof_hash text,
expires_at timestamptz NOT NULL, revoked_at timestamptz, cleaned_at timestamptz, cleanup_after timestamptz NOT NULL DEFAULT now(),
UNIQUE(tenant_id,parent_id,request_key),
FOREIGN KEY(tenant_id,parent_id) REFERENCES app.agent_identities(tenant_id,id) ON DELETE CASCADE,
FOREIGN KEY(tenant_id,provider_id) REFERENCES app.agent_integrations(tenant_id,id)
);
CREATE INDEX vm_grant_cleanup ON app.vm_grants(expires_at) WHERE cleaned_at IS NULL;
INSERT INTO app.schema_migrations(version) VALUES ('0060_external_vm_grants');
3 changes: 2 additions & 1 deletion packages/api/src/access-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { databaseFor } from "./postgres/database";
import { AccessTokenRepository } from "./postgres/access-token-repository";

export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const;
export const AGENT_SCOPES: readonly string[] = [...ACCESS_SCOPES, "proxy:use", "vm:grant"];
export type AccessScope = typeof ACCESS_SCOPES[number];
export type LegacyScope = "flows:read" | "flows:write";

Expand All @@ -14,7 +15,7 @@ export function normalizeScopes(scopes: readonly string[]): string[] {
if (scope === "flows:read") ["projects:read", "jobs:read", "integrations:read"].forEach(value => result.add(value));
else if (scope === "flows:write") ["projects:write", "jobs:write", "integrations:write"].forEach(value => result.add(value));
else if (scope === "runs:write") ["runs:read", "runs:invoke", "runs:cancel", "runs:write"].forEach(value => result.add(value));
else if (ACCESS_SCOPES.includes(scope as AccessScope) || isIntegrationScope(scope)) result.add(scope);
else if (AGENT_SCOPES.includes(scope) || isIntegrationScope(scope)) result.add(scope);
}
return [...result];
}
Expand Down
11 changes: 10 additions & 1 deletion packages/api/src/agent-api-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ 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, 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 apiReflection = z.object({ identity: z.object({ id: z.uuid(), kind: z.enum(["oauth", "run"]) }), scopes: z.array(z.string()), proxy: z.object({ requestUrl: z.url(), readResponseUrl: z.url(), authentication: z.string() }), integrations: z.array(apiPolicy.extend({ access: z.enum(["granted", "requestable", "unavailable"]), instructions: z.string(), vmGrantProvider: z.literal("exe.dev").optional() })) });
export const requestApiInput = z.object({
integration: integrationRef,
method: z.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]),
Expand All @@ -16,3 +16,12 @@ export const requestApiInput = z.object({
export const readApiResponseInput = z.object({ handle: z.uuid(), offset: z.number().int().nonnegative().default(0) }).strict();
export const apiResponseChunk = z.object({ handle: z.uuid(), offset: z.number().int().nonnegative(), nextOffset: z.number().int().nonnegative(), size: z.number().int().nonnegative(), encoding: z.literal("base64"), body: z.string(), done: z.boolean() });
export const requestApiResponse = z.object({ status: z.number().int(), headers: z.record(z.string(), z.string()), size: z.number().int().nonnegative(), encoding: z.enum(["utf8", "base64"]), body: z.string().optional(), handle: z.uuid().optional(), expiresAt: z.string().optional() });

export const grantVmInput = z.object({
providerIntegrationId: integrationRef,
vm: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/),
integrationIds: z.array(integrationRef).min(1).max(64).refine(ids => new Set(ids).size === ids.length),
idempotencyKey: z.string().min(1).max(160),
}).strict();
export const revokeVmInput = z.object({ grantId: z.uuid() }).strict();
export const vmGrantReceipt = z.object({ grantId: z.uuid(), vm: z.string(), integrationIds: z.array(integrationRef), expiresAt: z.string(), tokenUrl: z.url(), proofFile: z.string(), requestUrl: z.url(), instructions: z.string() });
28 changes: 24 additions & 4 deletions packages/api/src/agent-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class AgentApiService {
const auth = this.auth;
const member = await new IdentityRepository(this.database, auth.tenantId).member(auth.userId);
if (member?.role !== "owner" || member.sessionVersion !== auth.sessionVersion) throw invalidIdentity();
let kind: "run" | "oauth", subject: string, config: Record<string, any> | null = null;
let kind: "run" | "oauth" | "vm", subject: string, config: Record<string, any> | null = null;
if (auth.authMethod === "vendor_identity" && auth.runId) {
kind = "run"; subject = auth.runId;
const row = (await this.database.pool.query<{execution_config: Record<string, any>}>(`SELECT r.execution_config FROM app.runs r
Expand All @@ -69,6 +69,18 @@ export class AgentApiService {
AND r.state IN ('starting','running','blocked') AND j.state IN ('starting','running','blocked')`, [auth.tenantId, auth.runId, auth.runIdentityProvider, auth.userId, auth.sessionVersion])).rows[0];
if (!row) throw invalidIdentity();
config = row.execution_config;
} else if (auth.authMethod === "vm_grant" && auth.vmGrantId) {
kind = "vm"; subject = auth.vmGrantId;
const grant = (await this.database.pool.query(`SELECT g.permissions, g.parent_scopes FROM app.vm_grants g
JOIN app.agent_identities parent ON parent.tenant_id=g.tenant_id AND parent.id=g.parent_id
JOIN app.agent_integrations provider ON provider.tenant_id=g.tenant_id AND provider.id=g.provider_id
WHERE g.tenant_id=$1 AND g.id=$2 AND parent.user_id=$3 AND parent.session_version=$4
AND parent.revoked_at IS NULL AND g.issuer IS NOT NULL AND g.revoked_at IS NULL AND g.expires_at>now()
AND provider.available AND provider.epoch=g.provider_epoch AND (provider.policy='baseline' OR
(provider.policy='requestable' AND g.parent_scopes @> to_jsonb(ARRAY['integration:' || provider.id::text || ':' || provider.epoch::text])))`,
[auth.tenantId, subject, auth.userId, auth.sessionVersion])).rows[0];
if (!grant) throw invalidIdentity();
config = grant;
} else if (auth.authMethod === "oauth" && auth.oauthGrantId && auth.oauthClientId && auth.oauthExpiresAt && auth.oauthExpiresAt > Date.now()/1000) {
kind = "oauth"; subject = auth.oauthGrantId;
} else throw invalidIdentity();
Expand All @@ -93,7 +105,11 @@ export class AgentApiService {
const identity = await this.identity();
const row = (await this.database.pool.query<AgentIntegration>("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2", [this.auth.tenantId, integration])).rows[0];
if (!row) throw forbidden();
if (identity.kind === "run") {
if (identity.kind === "vm") {
const grant = identity.config!;
if (grant.permissions[row.id] !== row.epoch || !row.available || row.policy === "disabled"
|| (row.policy !== "baseline" && !grant.parent_scopes.includes(requiredIntegrationScope(row)))) throw forbidden();
} else if (identity.kind === "run") {
if (!this.selected(row, identity.config!)) throw forbidden();
const revoked = await this.database.pool.query("SELECT 1 FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2 AND kind=$3 AND credential_id=$4", [this.auth.tenantId, this.auth.runId, row.kind, row.credential_id]);
if (revoked.rowCount || !row.available) throw forbidden();
Expand All @@ -114,9 +130,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 === "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."});
result.push({...publicIntegration(row), access, ...(row.kind === "exe" && identity.kind === "oauth" && access === "granted" ? {vmGrantProvider: "exe.dev" as const} : {}), instructions: row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint 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};
return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes), proxy: {
requestUrl: this.env.APP_ORIGIN + "/api/v1/agent/requests",
readResponseUrl: this.env.APP_ORIGIN + "/api/v1/agent/responses/read",
authentication: identity.kind === "run" ? "Use your run identity helper." : "POST JSON with integration, method, and path. Use the agent OAuth credential with proxy:use. With the Factorize device launcher, curl -H @\"$FACTORIZE_AGENT_AUTH_FILE\" reads the authorization header.",
}, integrations: result};
}
async forward(integration: string, path: string, request: Request) {
const grant = await this.authorize(integration);
Expand Down
Loading