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
406 changes: 405 additions & 1 deletion packages/api-client/src/schema.d.ts

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions packages/api/migrations/0055_x_connections.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
CREATE TABLE app.x_connections (
tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE,
id uuid NOT NULL,
name text NOT NULL,
client_id text NOT NULL,
scopes text[] NOT NULL,
encrypted_secret text NOT NULL,
account_id text,
account_handle text,
granted_scopes text[] NOT NULL DEFAULT '{}',
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','connected','reconnect_required')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id,id)
);
CREATE UNIQUE INDEX x_connections_tenant_name_ci ON app.x_connections(tenant_id,lower(name));
INSERT INTO app.schema_migrations(version) VALUES ('0055_x_connections') ON CONFLICT DO NOTHING;
15 changes: 15 additions & 0 deletions packages/api/migrations/0056_x_oauth_attempts.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE TABLE app.x_oauth_attempts (
tenant_id uuid NOT NULL,
nonce text NOT NULL,
user_id uuid NOT NULL,
session_version integer NOT NULL,
connection_id uuid NOT NULL,
scopes text[] NOT NULL,
encrypted_verifier text NOT NULL,
expires_at timestamptz NOT NULL,
consumed_at timestamptz,
PRIMARY KEY (tenant_id, nonce),
FOREIGN KEY (tenant_id, connection_id) REFERENCES app.x_connections(tenant_id,id) ON DELETE CASCADE
);
CREATE INDEX x_oauth_attempt_expiry ON app.x_oauth_attempts(expires_at);
INSERT INTO app.schema_migrations(version) VALUES ('0056_x_oauth_attempts') ON CONFLICT DO NOTHING;
7 changes: 7 additions & 0 deletions packages/api/migrations/0057_revoke_x_connections.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
ALTER TABLE app.x_connections DROP CONSTRAINT x_connections_status_check;
ALTER TABLE app.x_connections ADD CONSTRAINT x_connections_status_check
CHECK (status IN ('pending','connected','reconnect_required','revoked'));
DROP INDEX app.x_connections_tenant_name_ci;
CREATE UNIQUE INDEX x_connections_tenant_name_ci
ON app.x_connections(tenant_id,lower(name)) WHERE status <> 'revoked';
INSERT INTO app.schema_migrations(version) VALUES ('0057_revoke_x_connections') ON CONFLICT DO NOTHING;
5 changes: 5 additions & 0 deletions packages/api/migrations/0058_x_credential_versions.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ALTER TABLE app.x_connections
ADD COLUMN credential_version integer NOT NULL DEFAULT 1;

ALTER TABLE app.x_oauth_attempts
ADD COLUMN credential_version integer NOT NULL DEFAULT 1;
5 changes: 5 additions & 0 deletions packages/api/migrations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,10 @@ record. Native sessions live in object storage. `run_artifacts` records exact
keys and checksums, while `run_trace_events` is the bounded projection used by
the cursor-paginated UI and PostgreSQL search.

X app secrets and OAuth tokens use the tenant-scoped encrypted payload in
`x_connections`; connection metadata queries never return that payload. Revoked
X connection IDs remain as secret-cleared tombstones so an old run selection
cannot be revived by reusing an ID.

The destructive artifact cutover is `0002`; `0003` completes runtime queue
ownership by binding deferred GitHub verification to an exact trigger.
55 changes: 55 additions & 0 deletions packages/api/src/agent-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { normalizeScopes } from "./access-tokens";
import { integrationScopePattern, requestApiInput, readApiResponseInput } from "./agent-api-contracts";
import { resolveAgentCredential } from "./agent-credentials";
import { forwardRunOutbound } from "./run-outbound-forwarder";
import { XConnectionRepository, XReconnectRequiredError } from "./postgres/x-connection-repository";
import type { z } from "zod";

export class AgentApiError extends Error {
Expand All @@ -18,6 +19,24 @@ const forbidden = () => new AgentApiError(403, "forbidden", "This integration is
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) });

/** Restrict the generic X v2 proxy to resources with an explicit OAuth-scope
* mapping. Unsupported resources and credential-management routes fail closed. */
function xRequiredScope(path: string, method: string): string | null {
const pathname = path.split("?", 1)[0] ?? "";
const verb = method.toUpperCase();
if (/^\/2\/users\/(?:me|[0-9]+)$/.test(pathname) && verb === "GET") return "users.read";
if (/^\/2\/tweets$/.test(pathname)) return verb === "GET" ? "tweet.read" : verb === "POST" ? "tweet.write" : null;
if (/^\/2\/tweets\/[0-9]+$/.test(pathname)) return verb === "GET" ? "tweet.read" : verb === "DELETE" ? "tweet.write" : null;
if (/^\/2\/users\/[0-9]+\/(?:tweets|mentions)$/.test(pathname) && verb === "GET") return "tweet.read";
if (/^\/2\/users\/[0-9]+\/followers$/.test(pathname) && verb === "GET") return "follows.read";
if (/^\/2\/users\/[0-9]+\/following$/.test(pathname)) return verb === "GET" ? "follows.read" : verb === "POST" ? "follows.write" : null;
if (/^\/2\/users\/[0-9]+\/following\/[0-9]+$/.test(pathname) && verb === "DELETE") return "follows.write";
if (/^\/2\/users\/[0-9]+\/liked_tweets$/.test(pathname) && verb === "GET") return "like.read";
if (/^\/2\/users\/[0-9]+\/likes$/.test(pathname)) return verb === "GET" ? "like.read" : verb === "POST" ? "like.write" : null;
if (/^\/2\/users\/[0-9]+\/likes\/[0-9]+$/.test(pathname) && verb === "DELETE") return "like.write";
return null;
}

/** These are structural checks only: reflection never refreshes/decrypts secrets. */
export async function integrationConsentLabels(env: Env, tenantId: string, scopes: string[]) {
const labels: Array<{scope: string; name: string; description: string | null}> = [];
Expand Down Expand Up @@ -108,6 +127,42 @@ export class AgentApiService {
try { return await forwardRunOutbound(request, credential); }
catch { throw new AgentApiError(502, "proxy_failed", "The upstream request failed."); }
}
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();
const required = xRequiredScope(path, request.method);
if (!required) throw forbidden();
const repository = new XConnectionRepository(this.database, this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY);
const connection = await repository.get(connectionId);
if (!connection || connection.status !== "connected") throw forbidden();
if (!connection.scopes.includes(required) || !connection.grantedScopes.includes(required)) throw new AgentApiError(403, "insufficient_scope", `This X connection does not grant ${required}.`);
let accessToken: string | null;
try {
accessToken = await repository.accessToken(connectionId, async credentials => {
const response = await fetch("https://api.x.com/2/oauth2/token", {
method: "POST", redirect: "error", signal: AbortSignal.timeout(15_000),
headers: { Authorization: `Basic ${btoa(`${credentials.clientId}:${credentials.clientSecret}`)}`, "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: credentials.refreshToken }),
});
const body = await response.json().catch(() => null) as { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown; error?: unknown } | null;
if (!response.ok) {
if (response.status === 401 || body?.error === "invalid_grant") throw new XReconnectRequiredError();
throw new Error("X token refresh temporarily failed");
}
if (typeof body?.access_token !== "string" || typeof body.refresh_token !== "string" || typeof body.expires_in !== "number" || !Number.isFinite(body.expires_in) || body.expires_in <= 0) throw new Error("X token refresh response was invalid");
return { accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: new Date(Date.now() + body.expires_in * 1000).toISOString() };
});
} catch (error) {
if (error instanceof XReconnectRequiredError) throw new AgentApiError(401, "reconnect_required", "X authorization expired or was revoked. Reconnect this connection in Settings.");
throw new AgentApiError(502, "refresh_unavailable", "X authorization could not be refreshed temporarily. Retry the request later.");
}
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();
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."); }
}
async request(input: z.infer<typeof requestApiInput>, signal?: AbortSignal) {
const parsed = requestApiInput.parse(input);
// Decode and size-check before any upstream operation.
Expand Down
3 changes: 2 additions & 1 deletion packages/api/src/agent-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { TraceSources } from "./trace-source";
import { JOB_RESULT_PATH } from "./job-result";
export type AgentKind = "codex" | "claude" | "pi";

export interface AgentConfiguration { model?: string; effort?: string; codexModel?: { baseUrl: string; providerName?: string }; providerEndpoints?: { githubInstallationIds?: number[]; linear?: boolean; model?: boolean }; }
export interface AgentConfiguration { model?: string; effort?: string; codexModel?: { baseUrl: string; providerName?: string }; providerEndpoints?: { githubInstallationIds?: number[]; linear?: boolean; model?: boolean; xConnectionIds?: string[] }; }
export interface ArtifactLocator {
/** Paths are interpreted inside the guest; the compute backend only transports files. */
roots: string[];
Expand Down Expand Up @@ -82,6 +82,7 @@ function providerEndpointEnv(config: AgentConfiguration): Record<string, string>
...(installations.length ? { FACTORIZE_GITHUB_INSTALLATIONS: JSON.stringify(installations) } : {}),
...(config.providerEndpoints?.linear ? { FACTORIZE_LINEAR_API_URL: `${proxy}/providers/linear/` } : {}),
...(config.providerEndpoints?.model ? { FACTORIZE_MODEL_API_URL: `${proxy}/providers/model/v1` } : {}),
...(config.providerEndpoints?.xConnectionIds?.length ? { FACTORIZE_X_CONNECTIONS: JSON.stringify([...new Set(config.providerEndpoints.xConnectionIds)].filter(id => /^[0-9a-f-]{36}$/i.test(id)).map(id => ({ id, apiUrl: `${proxy}/x/${id}/` }))) } : {}),
};
}
export function agentDriver(kind: AgentKind): AgentDriver {
Expand Down
Loading
Loading