From f3cf919cdd264f384601524a19ab994d236d8078 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 19:58:43 +0000 Subject: [PATCH 1/9] Add X OAuth scope and PKCE foundation --- packages/api/src/x-oauth.ts | 99 +++++++++++++++++++++++++++++++ packages/api/test/x-oauth.test.ts | 48 +++++++++++++++ 2 files changed, 147 insertions(+) create mode 100644 packages/api/src/x-oauth.ts create mode 100644 packages/api/test/x-oauth.test.ts diff --git a/packages/api/src/x-oauth.ts b/packages/api/src/x-oauth.ts new file mode 100644 index 00000000..a793c9cf --- /dev/null +++ b/packages/api/src/x-oauth.ts @@ -0,0 +1,99 @@ +import { hmac } from "./crypto"; + +/** X OAuth 2.0 scopes supported by the v1 user-owned connection flow. + * Descriptions follow the current X OAuth 2.0 scope reference. */ +export const X_OAUTH_SCOPES = { + "tweet.read": "Read posts the authorized account can view.", + "tweet.write": "Post and delete posts for the authorized account.", + "tweet.moderate.write": "Hide or unhide replies to the authorized account's posts.", + "users.email": "Read the authorized account's email address.", + "users.read": "Read user profiles the authorized account can view.", + "follows.read": "Read who follows the authorized account and whom it follows.", + "follows.write": "Follow or unfollow accounts for the authorized account.", + "offline.access": "Keep the connection active with refresh tokens until access is revoked.", + "space.read": "Read Spaces the authorized account can view.", + "mute.read": "Read accounts muted by the authorized account.", + "mute.write": "Mute or unmute accounts for the authorized account.", + "like.read": "Read posts liked by the authorized account.", + "like.write": "Like or unlike posts for the authorized account.", + "list.read": "Read Lists the authorized account can access.", + "list.write": "Create and manage Lists for the authorized account.", + "block.read": "Read accounts blocked by the authorized account.", + "block.write": "Block or unblock accounts for the authorized account.", + "bookmark.read": "Read posts bookmarked by the authorized account.", + "bookmark.write": "Bookmark or remove bookmarks for the authorized account.", + "dm.read": "Read Direct Messages available to the authorized account.", + "dm.write": "Send and manage Direct Messages for the authorized account.", + "media.write": "Upload media for posts.", + "broadcast.read": "Read the authorized account's live broadcasts and chat.", + "broadcast.write": "Manage live broadcasts and send chat messages for the authorized account.", +} as const; + +export type XOAuthScope = keyof typeof X_OAUTH_SCOPES; +export const X_SUGGESTED_SCOPES: readonly XOAuthScope[] = ["tweet.read", "users.read", "offline.access"]; +const SCOPE_ORDER = Object.keys(X_OAUTH_SCOPES) as XOAuthScope[]; +const encoder = new TextEncoder(); +const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +const json64 = (value: unknown) => b64url(encoder.encode(JSON.stringify(value))); + +export function validateXOAuthScopes(input: readonly string[]): XOAuthScope[] { + if (!Array.isArray(input) || input.length === 0 || input.length > SCOPE_ORDER.length) throw new Error("Select at least one X permission."); + if (input.some(scope => !Object.hasOwn(X_OAUTH_SCOPES, scope))) throw new Error("One or more selected X permissions are not supported."); + const scopes = [...new Set(input)] as XOAuthScope[]; + if (!scopes.includes("offline.access")) throw new Error("Include offline.access so Factorize can refresh the connection while jobs run unattended."); + // X's v2 authentication mapping requires these scopes for posts and user + // lookup; all suggested and additional v1 permissions include that baseline. + if (!scopes.includes("tweet.read") || !scopes.includes("users.read")) throw new Error("Include tweet.read and users.read for X API v2 user access."); + return SCOPE_ORDER.filter(scope => scopes.includes(scope)); +} + +export type XOAuthState = { + tenantId: string; + userId: string; + sessionVersion: number; + connectionId: string; + scopes: XOAuthScope[]; + nonce: string; + exp: number; +}; + +export async function signXOAuthState(value: XOAuthState, secret: string): Promise { + const body = json64(value); + return `${body}.${(await hmac(body, secret)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "")}`; +} + +/** Verify the signed callback state against the cookie and current owner + * session. Callers must delete the cookie before exchanging the code so a + * callback replay cannot reuse the same state. */ +export async function readXOAuthState( + state: string | undefined, + cookieState: string | undefined, + session: { tenantId: string; userId: string; sessionVersion: number } | null, + secret: string, +): Promise { + if (!state || state !== cookieState || !session) return null; + const [body, signature] = state.split("."); + if (!body || !signature) return null; + const expected = (await hmac(body, secret)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); + if (!constantTimeText(expected, signature)) return null; + try { + const padded = body.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((body.length + 3) % 4); + const value = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(padded), char => char.charCodeAt(0)))) as XOAuthState; + if (value.exp <= Math.floor(Date.now() / 1000) || value.tenantId !== session.tenantId || value.userId !== session.userId + || value.sessionVersion !== session.sessionVersion || !value.connectionId || !value.nonce) return null; + return { ...value, scopes: validateXOAuthScopes(value.scopes) }; + } catch { return null; } +} + +function constantTimeText(leftText: string, rightText: string): boolean { + const left = encoder.encode(leftText), right = encoder.encode(rightText); + let difference = left.length ^ right.length; + for (let index = 0; index < Math.max(left.length, right.length); index++) difference |= (left[index] ?? 0) ^ (right[index] ?? 0); + return difference === 0; +} + +export async function createXPKCE(): Promise<{ verifier: string; challenge: string }> { + const verifier = b64url(crypto.getRandomValues(new Uint8Array(32))); + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(verifier))); + return { verifier, challenge: b64url(digest) }; +} diff --git a/packages/api/test/x-oauth.test.ts b/packages/api/test/x-oauth.test.ts new file mode 100644 index 00000000..2e390fce --- /dev/null +++ b/packages/api/test/x-oauth.test.ts @@ -0,0 +1,48 @@ +import { createHash } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { createXPKCE, readXOAuthState, signXOAuthState, validateXOAuthScopes, X_SUGGESTED_SCOPES } from "../src/x-oauth"; + +const session = { tenantId: "tenant-a", userId: "owner-a", sessionVersion: 3 }; +const stateValue = { + ...session, + connectionId: "connection-a", + scopes: [...X_SUGGESTED_SCOPES], + nonce: "nonce-a", + exp: Math.floor(Date.now() / 1000) + 600, +}; + +describe("X OAuth setup foundation", () => { + it("offers a posts and users preset with offline refresh", () => { + expect(validateXOAuthScopes(X_SUGGESTED_SCOPES)).toEqual(["tweet.read", "users.read", "offline.access"]); + }); + + it("rejects unknown scopes and missing API v2 baseline or offline access", () => { + expect(() => validateXOAuthScopes(["tweet.read", "users.read", "made.up", "offline.access"])).toThrow(/not supported/); + expect(() => validateXOAuthScopes(["tweet.read", "offline.access"])).toThrow(/users.read/); + expect(() => validateXOAuthScopes(["tweet.read", "users.read"])).toThrow(/offline.access/); + }); + + it("deduplicates and returns scopes in stable provider order", () => { + expect(validateXOAuthScopes(["users.read", "tweet.read", "offline.access", "tweet.read"])).toEqual([...X_SUGGESTED_SCOPES]); + }); + + it("generates an S256 PKCE challenge for the returned verifier", async () => { + const pair = await createXPKCE(); + const expected = createHash("sha256").update(pair.verifier).digest("base64url"); + expect(pair.verifier).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(pair.challenge).toBe(expected); + }); + + it("binds signed state to the cookie, owner, tenant, session version and expiry", async () => { + const token = await signXOAuthState(stateValue, "state-secret"); + await expect(readXOAuthState(token, token, session, "state-secret")).resolves.toMatchObject(stateValue); + await expect(readXOAuthState(token, undefined, session, "state-secret")).resolves.toBeNull(); + await expect(readXOAuthState(token, token, { ...session, tenantId: "tenant-b" }, "state-secret")).resolves.toBeNull(); + await expect(readXOAuthState(token, token, { ...session, userId: "owner-b" }, "state-secret")).resolves.toBeNull(); + await expect(readXOAuthState(token, token, { ...session, sessionVersion: 4 }, "state-secret")).resolves.toBeNull(); + await expect(readXOAuthState(token, token, session, "wrong-secret")).resolves.toBeNull(); + + const expired = await signXOAuthState({ ...stateValue, exp: Math.floor(Date.now() / 1000) - 1 }, "state-secret"); + await expect(readXOAuthState(expired, expired, session, "state-secret")).resolves.toBeNull(); + }); +}); From 53a6c0c6e86e64b55cf8117b6887187c7ec4b2a2 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 20:19:54 +0000 Subject: [PATCH 2/9] Add encrypted X connection management --- packages/api-client/src/schema.d.ts | 187 +++++++++++ .../api/migrations/0055_x_connections.sql | 17 + packages/api/migrations/README.md | 3 + packages/api/src/api-contract.ts | 23 ++ packages/api/src/flow-service.ts | 26 ++ packages/api/src/postgres/schema.ts | 9 + .../src/postgres/x-connection-repository.ts | 73 +++++ .../x-connection-repository.postgres.test.ts | 32 ++ packages/docs/openapi.yaml | 303 ++++++++++++++++++ 9 files changed, 673 insertions(+) create mode 100644 packages/api/migrations/0055_x_connections.sql create mode 100644 packages/api/src/postgres/x-connection-repository.ts create mode 100644 packages/api/test/x-connection-repository.postgres.test.ts diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index f8760e95..ee19c5ba 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1,5 +1,61 @@ // Generated from packages/docs/openapi.yaml. Do not edit. export interface paths { + "/api/v1/x/connections": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List X connections + * @description Requires an interactive owner session. Returns named connection metadata, account identity, selected/granted scopes, and status. Client secrets and OAuth tokens are never returned. + * + * Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_x_connections"]; + put?: never; + /** + * Add a user-owned X app connection + * @description Requires an interactive owner session. Stores the X OAuth client secret in Factorize-managed encrypted storage and never returns it. Selected scopes are validated before saving. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_x_connections"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/x/connections/{connectionId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** + * Delete an X connection + * @description Requires an interactive owner session. Deletes the encrypted client credential and connection metadata. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_x_connections_connectionId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/model-accounts": { parameters: { query?: never; @@ -2993,6 +3049,137 @@ export interface components { } export type $defs = Record; export interface operations { + get_api_v1_x_connections: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description X connection metadata */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + connections: { + /** Format: uuid */ + id: string; + name: string; + clientId: string; + scopes: string[]; + accountId: string | null; + accountHandle: string | null; + grantedScopes: string[]; + /** @enum {string} */ + status: "pending" | "connected" | "reconnect_required"; + createdAt: string; + updatedAt: string; + }[]; + }; + }; + }; + 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"]; + }; + }; + post_api_v1_x_connections: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + clientId: string; + clientSecret: string; + scopes: ("tweet.read" | "tweet.write" | "tweet.moderate.write" | "users.email" | "users.read" | "follows.read" | "follows.write" | "offline.access" | "space.read" | "mute.read" | "mute.write" | "like.read" | "like.write" | "list.read" | "list.write" | "block.read" | "block.write" | "bookmark.read" | "bookmark.write" | "dm.read" | "dm.write" | "media.write" | "broadcast.read" | "broadcast.write")[]; + }; + }; + }; + responses: { + /** @description X connection created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + clientId: string; + scopes: string[]; + accountId: string | null; + accountHandle: string | null; + grantedScopes: string[]; + /** @enum {string} */ + status: "pending" | "connected" | "reconnect_required"; + createdAt: string; + updatedAt: 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_x_connections_connectionId: { + parameters: { + query?: never; + header?: never; + path: { + connectionId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description X connection deleted */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + /** @constant */ + deleted: true; + }; + }; + }; + 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_model_accounts: { parameters: { query?: never; diff --git a/packages/api/migrations/0055_x_connections.sql b/packages/api/migrations/0055_x_connections.sql new file mode 100644 index 00000000..d47bef5a --- /dev/null +++ b/packages/api/migrations/0055_x_connections.sql @@ -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; diff --git a/packages/api/migrations/README.md b/packages/api/migrations/README.md index a0c72828..7871c761 100644 --- a/packages/api/migrations/README.md +++ b/packages/api/migrations/README.md @@ -26,5 +26,8 @@ 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. + The destructive artifact cutover is `0002`; `0003` completes runtime queue ownership by binding deferred GitHub verification to an exact trigger. diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index aa40c7ae..a5f3278c 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -27,6 +27,7 @@ import { } from "./flow-schemas"; import { traceReplaySchema } from "./trace-replay-schemas"; import {modelAuthorizationState} from "./model-device-auth"; +import { X_OAUTH_SCOPES } from "./x-oauth"; import document from "./api-document.json"; import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, type AuthAction } from "./auth-api"; import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput } from "./skills"; @@ -143,6 +144,13 @@ const modelAccountCreate = z.object({ }).strict(); const modelAccountDelete = z.object({ expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid() }).strict(); const modelAccountList = z.object({ revision: z.number().int().nonnegative(), accounts: z.array(modelAccountMetadata) }); +const xConnectionMetadata = z.object({ id: z.uuid(), name: z.string(), clientId: z.string(), scopes: z.array(z.string()), accountId: z.string().nullable(), accountHandle: z.string().nullable(), grantedScopes: z.array(z.string()), status: z.enum(["pending", "connected", "reconnect_required"]), createdAt: z.string(), updatedAt: z.string() }); +const xConnectionCreate = z.object({ + id: z.uuid(), name: z.string().trim().min(1).max(120), clientId: z.string().trim().min(1).max(256), + clientSecret: z.string().min(1).max(4096).regex(/^[^\r\n]+$/).meta({ writeOnly: true }), + scopes: z.array(z.enum(Object.keys(X_OAUTH_SCOPES) as [keyof typeof X_OAUTH_SCOPES, ...(keyof typeof X_OAUTH_SCOPES)[]])).min(1).max(Object.keys(X_OAUTH_SCOPES).length), +}).strict(); +const xConnectionList = z.object({ connections: z.array(xConnectionMetadata) }); const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonnegative(), duplicate: z.boolean() }); const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() }); @@ -223,6 +231,21 @@ function authRoute(method: string, path: string, action: AuthAction, summary: st } export const API_ROUTES: RouteContract[] = [ + route("GET", "/api/v1/x/connections", "integrations:read", { + summary: "List X connections", + description: "Requires an interactive owner session. Returns named connection metadata, account identity, selected/granted scopes, and status. Client secrets and OAuth tokens are never returned.", + responses: { "200": { description: "X connection metadata", content: { "application/json": { schema: jsonSchema(xConnectionList, "output") } } } }, + }, service => service.listXConnections(), { ownerSession: true }), + route("POST", "/api/v1/x/connections", "integrations:write", { + summary: "Add a user-owned X app connection", + description: "Requires an interactive owner session. Stores the X OAuth client secret in Factorize-managed encrypted storage and never returns it. Selected scopes are validated before saving.", + responses: { "201": { description: "X connection created", content: { "application/json": { schema: jsonSchema(xConnectionMetadata, "output") } } } }, + }, (service, { body }) => service.createXConnection(body), { body: xConnectionCreate, maxBodyBytes: 8192, ownerSession: true }), + route("DELETE", "/api/v1/x/connections/{connectionId}", "integrations:write", { + summary: "Delete an X connection", + description: "Requires an interactive owner session. Deletes the encrypted client credential and connection metadata.", + responses: { "200": { description: "X connection deleted", content: { "application/json": { schema: jsonSchema(z.object({ id: z.uuid(), deleted: z.literal(true) }), "output") } } } }, + }, (service, { params }) => service.deleteXConnection(params.connectionId), { ownerSession: true, parameters: z.object({ connectionId: z.uuid() }) }), route("GET", "/api/v1/model-accounts", "integrations:read", { summary: "List model accounts available to the owner", description: "Requires an interactive owner browser session. Returns account metadata and the collection revision only; encrypted account caches and credentials are never returned.", diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 7caf2a5b..25fbc77f 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -20,6 +20,8 @@ import type { JobPageQuery } from "./job-contracts"; import { PostgresJobRepository, StaleJobEdit } from "./postgres/job-repository"; import { ConnectionRepository } from "./postgres/connection-repository"; import { CredentialRepository, IntegrationIdempotencyConflictError, IntegrationValidationError, StaleIntegrationRevisionError } from "./postgres/credential-repository"; +import { XConnectionRepository } from "./postgres/x-connection-repository"; +import { validateXOAuthScopes, type XOAuthScope } from "./x-oauth"; import { decrypt, encrypt } from "./crypto"; import { InvocationService, type Job, type Trigger } from "./job-domain"; import { RunQueryRepository } from "./postgres/run-query-repository"; @@ -603,6 +605,30 @@ export class ApiService { async saveTailIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveTail(input); } async testTailIntegration(id: string) { await this.authorize("integrations:write"); const result = await this.integrations().testTail(id); if (!result) throw new ServiceError(404, "not_found", "Integration not found"); return result; } private credentials() { return new CredentialRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } + private xConnections() { return new XConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } + async listXConnections() { + await this.authorizeOwnerSession("integrations:read"); + return { connections: await this.xConnections().list() }; + } + async createXConnection(input: { id: string; name: string; clientId: string; clientSecret: string; scopes: string[] }) { + await this.authorizeOwnerSession("integrations:write"); + let scopes: XOAuthScope[]; + try { scopes = validateXOAuthScopes(input.scopes); } + catch (error) { throw new ServiceError(400, "invalid_request", error instanceof Error ? error.message : "Invalid X scopes."); } + if (!/^[A-Za-z0-9_-]{1,256}$/.test(input.clientId)) throw new ServiceError(400, "invalid_request", "Enter a valid X OAuth 2.0 client ID."); + if (!input.clientSecret.trim() || input.clientSecret.length > 4096 || /[\r\n]/.test(input.clientSecret)) throw new ServiceError(400, "invalid_request", "Enter a valid X OAuth client secret."); + if ((await this.xConnections().get(input.id)) !== null) throw new ServiceError(409, "conflict", "X connection already exists."); + try { return await this.xConnections().create({ ...input, name: input.name.trim(), clientId: input.clientId.trim(), scopes }); } + catch (error) { + if (error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "23505") throw new ServiceError(409, "conflict", "An X connection with this name already exists."); + throw error; + } + } + async deleteXConnection(id: string) { + await this.authorizeOwnerSession("integrations:write"); + if (!await this.xConnections().delete(id)) throw new ServiceError(404, "not_found", "X connection not found."); + return { id, deleted: true as const }; + } private async bearerWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; token?: string; operation: "upsert" | "delete" }) { try { return await this.credentials().write({ ...input, managedSecret: input.token, kind: "bearer" }); } catch (error) { diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 8e1f2cf6..9d2e10af 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -47,6 +47,15 @@ export const integrationCollections = app.table("integration_collections", { export const integrationRecords = app.table("integration_records", { tenantId: uuid("tenant_id").notNull().references(() => integrationCollections.tenantId, { onDelete: "cascade" }), id: uuid("id").notNull(), kind: text("kind").$type<"bearer" | "model">().notNull(), name: text("name").notNull(), origin: text("origin"), description: text("description"), revision: bigint("revision", { mode: "number" }).notNull(), encryptedPayload: text("encrypted_payload"), deletedAt: timestamp("deleted_at", { withTimezone: true, mode: "date" }), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("integration_records_active_name").on(t.tenantId, t.kind, sql`lower(${t.name})`).where(sql`${t.deletedAt} is null`), index("integration_records_collection_order").on(t.tenantId, t.revision, t.id), check("integration_records_kind_check", sql`${t.kind} IN ('bearer','model')`), check("integration_records_origin_check", sql`(${t.kind} = 'bearer' AND ${t.origin} IS NOT NULL) OR (${t.kind} = 'model' AND ${t.origin} IS NULL)`), check("integration_records_payload_check", sql`(${t.deletedAt} IS NULL AND ${t.encryptedPayload} IS NOT NULL) OR (${t.deletedAt} IS NOT NULL AND ${t.encryptedPayload} IS NULL)`)]); + +export const xConnections = app.table("x_connections", { + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), + id: uuid("id").notNull(), name: text("name").notNull(), clientId: text("client_id").notNull(), + scopes: text("scopes").array().notNull(), encryptedSecret: text("encrypted_secret").notNull(), + accountId: text("account_id"), accountHandle: text("account_handle"), grantedScopes: text("granted_scopes").array().notNull().default(sql`'{}'::text[]`), + status: text("status").$type<"pending" | "connected" | "reconnect_required">().notNull().default("pending"), + createdAt: createdAt(), updatedAt: updatedAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("x_connections_tenant_name").on(t.tenantId, sql`lower(${t.name})`), check("x_connections_status_check", sql`${t.status} IN ('pending','connected','reconnect_required')`)]); 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(), diff --git a/packages/api/src/postgres/x-connection-repository.ts b/packages/api/src/postgres/x-connection-repository.ts new file mode 100644 index 00000000..0b714bc5 --- /dev/null +++ b/packages/api/src/postgres/x-connection-repository.ts @@ -0,0 +1,73 @@ +import { decrypt, encrypt } from "../crypto"; +import type { Database } from "./database"; + +export type XConnectionMetadata = { + id: string; + name: string; + clientId: string; + scopes: string[]; + accountId: string | null; + accountHandle: string | null; + grantedScopes: string[]; + status: "pending" | "connected" | "reconnect_required"; + createdAt: string; + updatedAt: string; +}; + +type XConnectionRow = XConnectionMetadata & { encrypted_secret: string }; + +/** Tenant-scoped X app credentials. Client secrets and later OAuth tokens share + * one encrypted payload; all owner and runtime reads expose metadata only. */ +export class XConnectionRepository { + constructor(private database: Database, private tenantId: string, private encryptionKey: string) { + if (!tenantId) throw new Error("tenantId is required"); + } + + async create(input: { id: string; name: string; clientId: string; clientSecret: string; scopes: string[] }): Promise { + const encrypted = await encrypt(JSON.stringify({ clientSecret: input.clientSecret }), this.encryptionKey); + const { rows } = await this.database.pool.query( + `INSERT INTO app.x_connections(tenant_id,id,name,client_id,scopes,encrypted_secret,status) + VALUES($1,$2,$3,$4,$5,$6,'pending') + RETURNING id,name,client_id AS "clientId",scopes,account_id AS "accountId",account_handle AS "accountHandle", + granted_scopes AS "grantedScopes",status,created_at AS "createdAt",updated_at AS "updatedAt",encrypted_secret`, + [this.tenantId, input.id, input.name.trim(), input.clientId.trim(), input.scopes, encrypted], + ); + return metadata(rows[0]!); + } + + async get(id: string): Promise { + const { rows } = await this.database.pool.query( + `SELECT id,name,client_id AS "clientId",scopes,account_id AS "accountId",account_handle AS "accountHandle", + granted_scopes AS "grantedScopes",status,created_at AS "createdAt",updated_at AS "updatedAt",encrypted_secret + FROM app.x_connections WHERE tenant_id=$1 AND id=$2`, [this.tenantId, id]); + return rows[0] ? metadata(rows[0]) : null; + } + + async list(): Promise { + const { rows } = await this.database.pool.query( + `SELECT id,name,client_id AS "clientId",scopes,account_id AS "accountId",account_handle AS "accountHandle", + granted_scopes AS "grantedScopes",status,created_at AS "createdAt",updated_at AS "updatedAt",encrypted_secret + FROM app.x_connections WHERE tenant_id=$1 ORDER BY created_at,id`, [this.tenantId]); + return rows.map(metadata); + } + + async clientCredentials(id: string): Promise<{ clientId: string; clientSecret: string; scopes: string[] } | null> { + const { rows } = await this.database.pool.query<{ client_id: string; encrypted_secret: string; scopes: string[] }>( + "SELECT client_id,encrypted_secret,scopes FROM app.x_connections WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); + const row = rows[0]; + if (!row) return null; + const secret = JSON.parse(await decrypt(row.encrypted_secret, this.encryptionKey)) as { clientSecret?: unknown }; + if (typeof secret.clientSecret !== "string" || !secret.clientSecret) throw new Error("X connection requires credential replacement"); + return { clientId: row.client_id, clientSecret: secret.clientSecret, scopes: row.scopes }; + } + + async delete(id: string): Promise { + const { rowCount } = await this.database.pool.query("DELETE FROM app.x_connections WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); + return (rowCount ?? 0) > 0; + } +} + +function metadata(row: XConnectionRow): XConnectionMetadata { + const { encrypted_secret: _secret, ...value } = row; + return value; +} diff --git a/packages/api/test/x-connection-repository.postgres.test.ts b/packages/api/test/x-connection-repository.postgres.test.ts new file mode 100644 index 00000000..5860001a --- /dev/null +++ b/packages/api/test/x-connection-repository.postgres.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it, vi } from "vitest"; +import { decrypt } from "../src/crypto"; +import { XConnectionRepository } from "../src/postgres/x-connection-repository"; +import { loadingFixture } from "./helpers/loading-fixture"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); +const url = process.env.AUTH_TEST_DATABASE_URL; + +describe.skipIf(!url)("encrypted X app connections (PostgreSQL)", { timeout: 60_000 }, () => { + it("encrypts the client secret and exposes only tenant-scoped safe metadata", async () => { + const f = await loadingFixture(url!); + try { + const id = crypto.randomUUID(); + const input = { id, name: "My X app", clientId: "client-123", clientSecret: "private-x-secret", scopes: ["tweet.read", "users.read", "offline.access"] }; + const repository = new XConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + const created = await repository.create(input); + expect(created).toMatchObject({ id, name: input.name, clientId: input.clientId, scopes: input.scopes, status: "pending", accountId: null, accountHandle: null, grantedScopes: [] }); + expect(JSON.stringify(created)).not.toContain(input.clientSecret); + + const stored = (await f.db.pool.query("SELECT encrypted_secret FROM app.x_connections WHERE tenant_id=$1 AND id=$2", [f.tenantId, id])).rows[0].encrypted_secret; + expect(stored).not.toContain(input.clientSecret); + expect(JSON.parse(await decrypt(stored, f.env.CREDENTIAL_ENCRYPTION_KEY))).toEqual({ clientSecret: input.clientSecret }); + expect(JSON.stringify(await repository.list())).not.toContain(input.clientSecret); + expect(await repository.clientCredentials(id)).toEqual({ clientId: input.clientId, clientSecret: input.clientSecret, scopes: input.scopes }); + expect(await new XConnectionRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY).get(id)).toBeNull(); + expect(await new XConnectionRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY).clientCredentials(id)).toBeNull(); + expect(await repository.delete(id)).toBe(true); + expect(await repository.get(id)).toBeNull(); + } finally { await f.cleanup(); } + }); +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 61e68c27..ec4714c6 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1828,6 +1828,309 @@ components: schema: $ref: "#/components/schemas/Error" paths: + /api/v1/x/connections: + get: + summary: List X connections + description: |- + Requires an interactive owner session. Returns named connection metadata, account identity, selected/granted scopes, and status. Client secrets and OAuth tokens are never returned. + + Requires the integrations:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: X connection metadata + content: + application/json: + schema: + type: object + properties: + connections: + type: array + items: + type: object + properties: + id: + 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)$ + name: + type: string + clientId: + type: string + scopes: + type: array + items: + type: string + accountId: + type: + - string + - "null" + accountHandle: + type: + - string + - "null" + grantedScopes: + type: array + items: + type: string + status: + type: string + enum: + - pending + - connected + - reconnect_required + createdAt: + type: string + updatedAt: + type: string + required: + - id + - name + - clientId + - scopes + - accountId + - accountHandle + - grantedScopes + - status + - createdAt + - updatedAt + additionalProperties: false + required: + - connections + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: get_api_v1_x_connections + tags: + - x + security: + - cookieAuth: [] + x-required-scope: integrations:read + x-owner-session-required: true + post: + summary: Add a user-owned X app connection + description: |- + Requires an interactive owner session. Stores the X OAuth client secret in Factorize-managed encrypted storage and never returns it. Selected scopes are validated before saving. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "201": + description: X connection created + content: + application/json: + schema: + type: object + properties: + id: + 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)$ + name: + type: string + clientId: + type: string + scopes: + type: array + items: + type: string + accountId: + type: + - string + - "null" + accountHandle: + type: + - string + - "null" + grantedScopes: + type: array + items: + type: string + status: + type: string + enum: + - pending + - connected + - reconnect_required + createdAt: + type: string + updatedAt: + type: string + required: + - id + - name + - clientId + - scopes + - accountId + - accountHandle + - grantedScopes + - status + - createdAt + - updatedAt + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_x_connections + tags: + - x + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + id: + 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)$ + name: + type: string + minLength: 1 + maxLength: 120 + clientId: + type: string + minLength: 1 + maxLength: 256 + clientSecret: + type: string + minLength: 1 + maxLength: 4096 + pattern: ^[^\r\n]+$ + writeOnly: true + scopes: + minItems: 1 + maxItems: 24 + type: array + items: + type: string + enum: + - tweet.read + - tweet.write + - tweet.moderate.write + - users.email + - users.read + - follows.read + - follows.write + - offline.access + - space.read + - mute.read + - mute.write + - like.read + - like.write + - list.read + - list.write + - block.read + - block.write + - bookmark.read + - bookmark.write + - dm.read + - dm.write + - media.write + - broadcast.read + - broadcast.write + required: + - id + - name + - clientId + - clientSecret + - scopes + additionalProperties: false + /api/v1/x/connections/{connectionId}: + delete: + summary: Delete an X connection + description: |- + Requires an interactive owner session. Deletes the encrypted client credential and connection metadata. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: X connection deleted + content: + application/json: + schema: + type: object + properties: + id: + 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)$ + deleted: + type: boolean + const: true + required: + - id + - deleted + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: delete_api_v1_x_connections_connectionId + tags: + - x + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + parameters: + - name: connectionId + in: path + required: true + schema: + 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)$ /api/v1/model-accounts: get: summary: List model accounts available to the owner From 39841e877599ff20e267b3e936e3f6205e552b73 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 20:42:36 +0000 Subject: [PATCH 3/9] Add X Settings OAuth authorization flow --- packages/api-client/src/schema.d.ts | 62 ++++++++++++ .../api/migrations/0056_x_oauth_attempts.sql | 15 +++ packages/api/src/api-contract.ts | 9 ++ packages/api/src/flow-service.ts | 15 ++- packages/api/src/postgres/schema.ts | 5 + .../src/postgres/x-connection-repository.ts | 36 ++++++- packages/api/src/worker.ts | 2 + packages/api/src/x-oauth-callback.ts | 73 ++++++++++++++ .../x-connection-repository.postgres.test.ts | 9 +- .../api/test/x-oauth-flow.postgres.test.ts | 74 +++++++++++++++ .../src/features/settings/integrations.tsx | 3 +- .../src/features/settings/x-connections.tsx | 95 +++++++++++++++++++ .../app/test/x-connections.browser.test.mjs | 63 ++++++++++++ packages/docs/openapi.yaml | 64 +++++++++++++ 14 files changed, 519 insertions(+), 6 deletions(-) create mode 100644 packages/api/migrations/0056_x_oauth_attempts.sql create mode 100644 packages/api/src/x-oauth-callback.ts create mode 100644 packages/api/test/x-oauth-flow.postgres.test.ts create mode 100644 packages/app/src/features/settings/x-connections.tsx create mode 100644 packages/app/test/x-connections.browser.test.mjs diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index ee19c5ba..892a0e47 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -56,6 +56,30 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/x/connections/{connectionId}/authorize": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Start X OAuth authorization + * @description Requires an interactive owner session. Starts a short-lived PKCE authorization bound to this owner, tenant, session, connection, and selected scopes. The one-time state is set in an HttpOnly cookie. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_x_connections_connectionId_authorize"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/model-accounts": { parameters: { query?: never; @@ -3180,6 +3204,44 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + post_api_v1_x_connections_connectionId_authorize: { + parameters: { + query?: never; + header?: never; + path: { + connectionId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": Record; + }; + }; + responses: { + /** @description X authorization URL */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uri */ + authorizationUrl: 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"]; + }; + }; get_api_v1_model_accounts: { parameters: { query?: never; diff --git a/packages/api/migrations/0056_x_oauth_attempts.sql b/packages/api/migrations/0056_x_oauth_attempts.sql new file mode 100644 index 00000000..baecc541 --- /dev/null +++ b/packages/api/migrations/0056_x_oauth_attempts.sql @@ -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; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index a5f3278c..d46b3ca6 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -151,6 +151,7 @@ const xConnectionCreate = z.object({ scopes: z.array(z.enum(Object.keys(X_OAUTH_SCOPES) as [keyof typeof X_OAUTH_SCOPES, ...(keyof typeof X_OAUTH_SCOPES)[]])).min(1).max(Object.keys(X_OAUTH_SCOPES).length), }).strict(); const xConnectionList = z.object({ connections: z.array(xConnectionMetadata) }); +const xAuthorizationStart = z.object({ authorizationUrl: z.url() }); const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonnegative(), duplicate: z.boolean() }); const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() }); @@ -246,6 +247,14 @@ export const API_ROUTES: RouteContract[] = [ description: "Requires an interactive owner session. Deletes the encrypted client credential and connection metadata.", responses: { "200": { description: "X connection deleted", content: { "application/json": { schema: jsonSchema(z.object({ id: z.uuid(), deleted: z.literal(true) }), "output") } } } }, }, (service, { params }) => service.deleteXConnection(params.connectionId), { ownerSession: true, parameters: z.object({ connectionId: z.uuid() }) }), + route("POST", "/api/v1/x/connections/{connectionId}/authorize", "integrations:write", { + summary: "Start X OAuth authorization", + description: "Requires an interactive owner session. Starts a short-lived PKCE authorization bound to this owner, tenant, session, connection, and selected scopes. The one-time state is set in an HttpOnly cookie.", + responses: { "200": { description: "X authorization URL", content: { "application/json": { schema: jsonSchema(xAuthorizationStart, "output") } } } }, + }, async (service, { params }) => { + const started = await service.authorizeXConnection(params.connectionId); + return Response.json({ authorizationUrl: started.authorizationUrl }, { headers: { "Set-Cookie": `factorize_x_oauth_state=${started.stateCookie}; HttpOnly; Secure; SameSite=Lax; Path=/oauth/x/callback; Max-Age=600` } }); + }, { body: z.object({}).strict(), maxBodyBytes: 1024, ownerSession: true, parameters: z.object({ connectionId: z.uuid() }) }), route("GET", "/api/v1/model-accounts", "integrations:read", { summary: "List model accounts available to the owner", description: "Requires an interactive owner browser session. Returns account metadata and the collection revision only; encrypted account caches and credentials are never returned.", diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 25fbc77f..a45c2415 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -21,7 +21,7 @@ import { PostgresJobRepository, StaleJobEdit } from "./postgres/job-repository"; import { ConnectionRepository } from "./postgres/connection-repository"; import { CredentialRepository, IntegrationIdempotencyConflictError, IntegrationValidationError, StaleIntegrationRevisionError } from "./postgres/credential-repository"; import { XConnectionRepository } from "./postgres/x-connection-repository"; -import { validateXOAuthScopes, type XOAuthScope } from "./x-oauth"; +import { createXPKCE, signXOAuthState, validateXOAuthScopes, type XOAuthScope } from "./x-oauth"; import { decrypt, encrypt } from "./crypto"; import { InvocationService, type Job, type Trigger } from "./job-domain"; import { RunQueryRepository } from "./postgres/run-query-repository"; @@ -629,6 +629,19 @@ export class ApiService { if (!await this.xConnections().delete(id)) throw new ServiceError(404, "not_found", "X connection not found."); return { id, deleted: true as const }; } + async authorizeXConnection(id: string) { + await this.authorizeOwnerSession("integrations:write"); + const repository = this.xConnections(), connection = await repository.get(id), credentials = await repository.clientCredentials(id); + if (!connection || !credentials) throw new ServiceError(404, "not_found", "X connection not found."); + const scopes = validateXOAuthScopes(connection.scopes); + const pkce = await createXPKCE(), nonce = crypto.randomUUID(), expires = Math.floor(Date.now() / 1000) + 600; + const state = await signXOAuthState({ tenantId: this.auth.tenantId, userId: this.auth.userId, sessionVersion: this.auth.sessionVersion, connectionId: id, scopes, nonce, exp: expires }, this.env.SESSION_SIGNING_SECRET); + const saved = await repository.createOAuthAttempt({ nonce, userId: this.auth.userId, sessionVersion: this.auth.sessionVersion, connectionId: id, scopes, verifier: pkce.verifier, expiresAt: new Date(expires * 1000) }); + if (!saved) throw new ServiceError(404, "not_found", "X connection not found."); + const redirectUri = `${this.env.APP_ORIGIN}/oauth/x/callback`, authorize = new URL("https://x.com/i/oauth2/authorize"); + authorize.search = new URLSearchParams({ response_type: "code", client_id: credentials.clientId, redirect_uri: redirectUri, scope: scopes.join(" "), state, code_challenge: pkce.challenge, code_challenge_method: "S256" }).toString(); + return { authorizationUrl: authorize.toString(), stateCookie: state }; + } private async bearerWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; token?: string; operation: "upsert" | "delete" }) { try { return await this.credentials().write({ ...input, managedSecret: input.token, kind: "bearer" }); } catch (error) { diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 9d2e10af..f735bb32 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -56,6 +56,11 @@ export const xConnections = app.table("x_connections", { status: text("status").$type<"pending" | "connected" | "reconnect_required">().notNull().default("pending"), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("x_connections_tenant_name").on(t.tenantId, sql`lower(${t.name})`), check("x_connections_status_check", sql`${t.status} IN ('pending','connected','reconnect_required')`)]); +export const xOAuthAttempts = app.table("x_oauth_attempts", { + tenantId: uuid("tenant_id").notNull(), nonce: text("nonce").notNull(), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), + connectionId: uuid("connection_id").notNull(), scopes: text("scopes").array().notNull(), encryptedVerifier: text("encrypted_verifier").notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), consumedAt: timestamp("consumed_at", { withTimezone: true }), +}, 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(), diff --git a/packages/api/src/postgres/x-connection-repository.ts b/packages/api/src/postgres/x-connection-repository.ts index 0b714bc5..42758e85 100644 --- a/packages/api/src/postgres/x-connection-repository.ts +++ b/packages/api/src/postgres/x-connection-repository.ts @@ -51,14 +51,44 @@ export class XConnectionRepository { return rows.map(metadata); } - async clientCredentials(id: string): Promise<{ clientId: string; clientSecret: string; scopes: string[] } | null> { + async clientCredentials(id: string): Promise<{ clientId: string; clientSecret: string; scopes: string[]; accessToken?: string; refreshToken?: string; expiresAt?: string } | null> { const { rows } = await this.database.pool.query<{ client_id: string; encrypted_secret: string; scopes: string[] }>( "SELECT client_id,encrypted_secret,scopes FROM app.x_connections WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); const row = rows[0]; if (!row) return null; - const secret = JSON.parse(await decrypt(row.encrypted_secret, this.encryptionKey)) as { clientSecret?: unknown }; + const secret = JSON.parse(await decrypt(row.encrypted_secret, this.encryptionKey)) as { clientSecret?: unknown; accessToken?: unknown; refreshToken?: unknown; expiresAt?: unknown }; if (typeof secret.clientSecret !== "string" || !secret.clientSecret) throw new Error("X connection requires credential replacement"); - return { clientId: row.client_id, clientSecret: secret.clientSecret, scopes: row.scopes }; + return { clientId: row.client_id, clientSecret: secret.clientSecret, scopes: row.scopes, accessToken: typeof secret.accessToken === "string" ? secret.accessToken : undefined, refreshToken: typeof secret.refreshToken === "string" ? secret.refreshToken : undefined, expiresAt: typeof secret.expiresAt === "string" ? secret.expiresAt : undefined }; + } + + async createOAuthAttempt(input: { nonce: string; userId: string; sessionVersion: number; connectionId: string; scopes: string[]; verifier: string; expiresAt: Date }): Promise { + const encryptedVerifier = await encrypt(input.verifier, this.encryptionKey); + const result = await this.database.pool.query(`INSERT INTO app.x_oauth_attempts(tenant_id,nonce,user_id,session_version,connection_id,scopes,encrypted_verifier,expires_at) + SELECT $1,$2,$3,$4,$5,$6,$7,$8 WHERE EXISTS (SELECT 1 FROM app.x_connections WHERE tenant_id=$1 AND id=$5)`, + [this.tenantId, input.nonce, input.userId, input.sessionVersion, input.connectionId, input.scopes, encryptedVerifier, input.expiresAt]); + return Boolean(result.rowCount); + } + + async consumeOAuthAttempt(nonce: string): Promise<{ userId: string; sessionVersion: number; connectionId: string; scopes: string[]; verifier: string } | null> { + const { rows } = await this.database.pool.query<{ user_id: string; session_version: number; connection_id: string; scopes: string[]; encrypted_verifier: string }>( + `UPDATE app.x_oauth_attempts SET consumed_at=now() WHERE tenant_id=$1 AND nonce=$2 AND consumed_at IS NULL AND expires_at>now() + RETURNING user_id,session_version,connection_id,scopes,encrypted_verifier`, [this.tenantId, nonce]); + const row = rows[0]; + if (!row) return null; + return { userId: row.user_id, sessionVersion: row.session_version, connectionId: row.connection_id, scopes: row.scopes, verifier: await decrypt(row.encrypted_verifier, this.encryptionKey) }; + } + + async completeOAuth(id: string, input: { accessToken: string; refreshToken: string; expiresAt: string; accountId: string; accountHandle: string; grantedScopes: string[] }): Promise { + const credentials = await this.clientCredentials(id); + if (!credentials) throw new Error("X connection not found"); + const encrypted = await encrypt(JSON.stringify({ clientSecret: credentials.clientSecret, accessToken: input.accessToken, refreshToken: input.refreshToken, expiresAt: input.expiresAt }), this.encryptionKey); + const result = await this.database.pool.query(`UPDATE app.x_connections SET encrypted_secret=$3,account_id=$4,account_handle=$5,granted_scopes=$6,status='connected',updated_at=now() WHERE tenant_id=$1 AND id=$2`, + [this.tenantId, id, encrypted, input.accountId, input.accountHandle, input.grantedScopes]); + if (!result.rowCount) throw new Error("X connection not found"); + } + + async resetOAuthAttempt(id: string): Promise { + await this.database.pool.query("UPDATE app.x_connections SET status='pending',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status<>'connected'", [this.tenantId, id]); } async delete(id: string): Promise { diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index 62a02aef..d51e5fe3 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -15,6 +15,7 @@ import { traceChunkUpload } from "./trace-chunk-upload"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; import { runOutboundProxyFetch } from "./run-outbound-proxy"; +import { xOAuthCallback } from "./x-oauth-callback"; const scopes = [...ACCESS_SCOPES]; // Keep accepting grants issued by the pre-resource-scope protocol. New @@ -87,6 +88,7 @@ function provider(env: Env) { return new OAuthProvider(providerOptions(env) export { AlarmCoordinator } from "./alarm-coordinator"; const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) { if (new URL(request.url).pathname.startsWith("/internal/run-proxy/")) return runOutboundProxyFetch(request, env); + if (new URL(request.url).pathname === "/oauth/x/callback") return request.method === "GET" ? xOAuthCallback(request, env) : new Response("Method not allowed", { status: 405, headers: { Allow: "GET" } }); const staticResponse = !["/authorize", "/device"].includes(new URL(request.url).pathname) ? await staticApp(request, env) : null; if (staticResponse) return staticResponse; const oauth = provider(env); diff --git a/packages/api/src/x-oauth-callback.ts b/packages/api/src/x-oauth-callback.ts new file mode 100644 index 00000000..10e4ca1b --- /dev/null +++ b/packages/api/src/x-oauth-callback.ts @@ -0,0 +1,73 @@ +import { requestCookie, readSession } from "./session"; +import { databaseFor } from "./postgres/database"; +import { IdentityRepository } from "./postgres/identity-repository"; +import { XConnectionRepository } from "./postgres/x-connection-repository"; +import { readXOAuthState } from "./x-oauth"; +import type { Env } from "./types"; + +const cookie = "factorize_x_oauth_state"; +const clearCookie = `${cookie}=; HttpOnly; Secure; SameSite=Lax; Path=/oauth/x/callback; Max-Age=0`; +const settings = (env: Env, result: string) => { + const target = new URL("/settings/integrations", env.APP_ORIGIN); + target.searchParams.set("x", result); + return Response.redirect(target.toString(), 303); +}; + +/** X's registered redirect URI is fixed; all credentials and the PKCE verifier + * stay server-side. The attempt row is consumed atomically before any exchange. */ +export async function xOAuthCallback(request: Request, env: Env): Promise { + const url = new URL(request.url), clear = { "Set-Cookie": clearCookie, "Cache-Control": "no-store" }; + const fail = (result: string) => { + const response = settings(env, result); + for (const [key, value] of Object.entries(clear)) response.headers.set(key, value); + return response; + }; + const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET); + if (!session) return fail("session_required"); + const database = databaseFor(env), identities = new IdentityRepository(database, session.tenantId); + const member = await identities.member(session.userId); + if (member?.role !== "owner" || member.sessionVersion !== session.sessionVersion) return fail("session_required"); + + const state = url.searchParams.get("state") ?? undefined; + const verified = await readXOAuthState(state, requestCookie(request, cookie), session, env.SESSION_SIGNING_SECRET); + if (!verified) return fail("expired"); + const repository = new XConnectionRepository(database, session.tenantId, env.CREDENTIAL_ENCRYPTION_KEY); + const attempt = await repository.consumeOAuthAttempt(verified.nonce); + if (!attempt || attempt.userId !== session.userId || attempt.sessionVersion !== session.sessionVersion || attempt.connectionId !== verified.connectionId + || JSON.stringify(attempt.scopes) !== JSON.stringify(verified.scopes)) return fail("expired"); + + if (url.searchParams.has("error")) return fail(url.searchParams.get("error") === "access_denied" ? "denied" : "failed"); + const code = url.searchParams.get("code"); + const credentials = await repository.clientCredentials(verified.connectionId); + if (!code || !credentials) { await repository.resetOAuthAttempt(verified.connectionId); return fail("failed"); } + + const redirectUri = `${env.APP_ORIGIN}/oauth/x/callback`; + try { + const tokenResponse = 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: "authorization_code", code, redirect_uri: redirectUri, code_verifier: attempt.verifier }), + }); + if (!tokenResponse.ok) throw new Error("token_exchange_failed"); + const token = await tokenResponse.json() as { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown; scope?: unknown }; + if (typeof token.access_token !== "string" || typeof token.refresh_token !== "string" || typeof token.expires_in !== "number" || token.expires_in <= 0 || typeof token.scope !== "string") throw new Error("invalid_token_response"); + const grantedScopes = [...new Set(token.scope.split(/\s+/).filter(Boolean))].sort(); + if (verified.scopes.some(scope => !grantedScopes.includes(scope))) { await repository.resetOAuthAttempt(verified.connectionId); return fail("scope_mismatch"); } + + const meResponse = await fetch("https://api.x.com/2/users/me?user.fields=id%2Cusername", { + headers: { Authorization: `Bearer ${token.access_token}`, Accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(15_000), + }); + if (!meResponse.ok) throw new Error("identity_verification_failed"); + const me = await meResponse.json() as { data?: { id?: unknown; username?: unknown } }; + if (typeof me.data?.id !== "string" || typeof me.data.username !== "string" || !me.data.username) throw new Error("invalid_identity_response"); + await repository.completeOAuth(verified.connectionId, { + accessToken: token.access_token, refreshToken: token.refresh_token, + expiresAt: new Date(Date.now() + token.expires_in * 1000).toISOString(), accountId: me.data.id, + accountHandle: me.data.username, grantedScopes, + }); + return fail("connected"); + } catch { + await repository.resetOAuthAttempt(verified.connectionId); + return fail("failed"); + } +} diff --git a/packages/api/test/x-connection-repository.postgres.test.ts b/packages/api/test/x-connection-repository.postgres.test.ts index 5860001a..876577da 100644 --- a/packages/api/test/x-connection-repository.postgres.test.ts +++ b/packages/api/test/x-connection-repository.postgres.test.ts @@ -22,9 +22,16 @@ describe.skipIf(!url)("encrypted X app connections (PostgreSQL)", { timeout: 60_ expect(stored).not.toContain(input.clientSecret); expect(JSON.parse(await decrypt(stored, f.env.CREDENTIAL_ENCRYPTION_KEY))).toEqual({ clientSecret: input.clientSecret }); expect(JSON.stringify(await repository.list())).not.toContain(input.clientSecret); - expect(await repository.clientCredentials(id)).toEqual({ clientId: input.clientId, clientSecret: input.clientSecret, scopes: input.scopes }); + expect(await repository.clientCredentials(id)).toMatchObject({ clientId: input.clientId, clientSecret: input.clientSecret, scopes: input.scopes }); expect(await new XConnectionRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY).get(id)).toBeNull(); expect(await new XConnectionRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY).clientCredentials(id)).toBeNull(); + const nonce = crypto.randomUUID(), verifier = "one-time-pkce-verifier"; + expect(await repository.createOAuthAttempt({ nonce, userId: f.userId, sessionVersion: 1, connectionId: id, scopes: input.scopes, verifier, expiresAt: new Date(Date.now() + 60_000) })).toBe(true); + const attempt = (await f.db.pool.query("SELECT encrypted_verifier FROM app.x_oauth_attempts WHERE tenant_id=$1 AND nonce=$2", [f.tenantId, nonce])).rows[0].encrypted_verifier; + expect(attempt).not.toContain(verifier); + expect(await new XConnectionRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY).consumeOAuthAttempt(nonce)).toBeNull(); + await expect(repository.consumeOAuthAttempt(nonce)).resolves.toMatchObject({ userId: f.userId, connectionId: id, scopes: input.scopes, verifier }); + await expect(repository.consumeOAuthAttempt(nonce)).resolves.toBeNull(); expect(await repository.delete(id)).toBe(true); expect(await repository.get(id)).toBeNull(); } finally { await f.cleanup(); } diff --git a/packages/api/test/x-oauth-flow.postgres.test.ts b/packages/api/test/x-oauth-flow.postgres.test.ts new file mode 100644 index 00000000..f94b9066 --- /dev/null +++ b/packages/api/test/x-oauth-flow.postgres.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { XConnectionRepository } from "../src/postgres/x-connection-repository"; +import worker from "../src/worker"; +import { loadingFixture } from "./helpers/loading-fixture"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); +const databaseUrl = process.env.AUTH_TEST_DATABASE_URL; +afterEach(() => vi.unstubAllGlobals()); + +describe.skipIf(!databaseUrl)("X owner OAuth callback (PostgreSQL)", { timeout: 60_000 }, () => { + it("consumes owner-bound PKCE once, exchanges the code, verifies identity/scopes, and stores tokens encrypted", async () => { + const fixture = await loadingFixture(databaseUrl!); + try { + const repository = new XConnectionRepository(fixture.db, fixture.tenantId, fixture.env.CREDENTIAL_ENCRYPTION_KEY); + const id = crypto.randomUUID(), clientSecret = "private-x-client-secret"; + await repository.create({ id, name: "X test", clientId: "client-123", clientSecret, scopes: ["tweet.read", "users.read", "offline.access"] }); + const start = await worker.fetch(new Request(`https://factorize.test/api/v1/x/connections/${id}/authorize`, { + method: "POST", headers: { Cookie: fixture.cookie, Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, body: "{}", + }), fixture.env, { waitUntil() {} } as any); + expect(start.status).toBe(200); + const { authorizationUrl } = await start.json() as { authorizationUrl: string }; + const authorize = new URL(authorizationUrl); + expect(authorize.origin + authorize.pathname).toBe("https://x.com/i/oauth2/authorize"); + expect(authorize.searchParams.get("redirect_uri")).toBe("https://factorize.test/oauth/x/callback"); + expect(authorize.searchParams.get("scope")).toBe("tweet.read users.read offline.access"); + expect(authorize.searchParams.get("code_challenge_method")).toBe("S256"); + const state = authorize.searchParams.get("state")!; + const oauthCookie = start.headers.get("Set-Cookie")!.split(";", 1)[0]!; + const calls: Array<{ url: string; init?: RequestInit }> = []; + vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); calls.push({ url, init }); + if (url === "https://api.x.com/2/oauth2/token") return Response.json({ access_token: "secret-access", refresh_token: "secret-refresh", expires_in: 3600, scope: "tweet.read users.read offline.access" }); + if (url.startsWith("https://api.x.com/2/users/me")) return Response.json({ data: { id: "12345", username: "verified_user" } }); + throw new Error("Unexpected X request"); + }); + const callbackUrl = `https://factorize.test/oauth/x/callback?code=authorization-code&state=${encodeURIComponent(state)}`; + const callback = () => worker.fetch(new Request(callbackUrl, { headers: { Cookie: `${fixture.cookie}; ${oauthCookie}` } }), fixture.env, { waitUntil() {} } as any); + const result = await callback(); + expect(result.status).toBe(303); + expect(result.headers.get("Location")).toBe("https://factorize.test/settings/integrations?x=connected"); + expect(result.headers.get("Set-Cookie")).toContain("Max-Age=0"); + expect(calls.map(call => call.url)).toEqual([ + "https://api.x.com/2/oauth2/token", "https://api.x.com/2/users/me?user.fields=id%2Cusername", + ]); + expect(calls[0]!.init?.body).toBeInstanceOf(URLSearchParams); + expect((calls[0]!.init!.body as URLSearchParams).get("code_verifier")).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(calls[0]!.init?.headers).toMatchObject({ Authorization: `Basic ${btoa(`client-123:${clientSecret}`)}` }); + expect(calls[1]!.init?.headers).toMatchObject({ Authorization: "Bearer secret-access" }); + const replay = await callback(); + expect(replay.headers.get("Location")).toContain("x=expired"); + expect(calls).toHaveLength(2); + expect(await repository.get(id)).toMatchObject({ status: "connected", accountId: "12345", accountHandle: "verified_user", grantedScopes: ["offline.access", "tweet.read", "users.read"] }); + const stored = (await fixture.db.pool.query("SELECT encrypted_secret FROM app.x_connections WHERE tenant_id=$1 AND id=$2", [fixture.tenantId, id])).rows[0].encrypted_secret; + expect(stored).not.toContain("secret-access"); + expect(stored).not.toContain("secret-refresh"); + await expect(repository.clientCredentials(id)).resolves.toMatchObject({ accessToken: "secret-access", refreshToken: "secret-refresh" }); + } finally { await fixture.cleanup(); } + }); + + it("handles X denial without exchanging a code or losing the saved connection", async () => { + const fixture = await loadingFixture(databaseUrl!); + try { + const repository = new XConnectionRepository(fixture.db, fixture.tenantId, fixture.env.CREDENTIAL_ENCRYPTION_KEY), id = crypto.randomUUID(); + await repository.create({ id, name: "Denied X app", clientId: "client-456", clientSecret: "private", scopes: ["tweet.read", "users.read", "offline.access"] }); + const start = await worker.fetch(new Request(`https://factorize.test/api/v1/x/connections/${id}/authorize`, { method: "POST", headers: { Cookie: fixture.cookie, Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, body: "{}" }), fixture.env, { waitUntil() {} } as any); + const state = new URL((await start.json() as { authorizationUrl: string }).authorizationUrl).searchParams.get("state")!; + const cookie = start.headers.get("Set-Cookie")!.split(";", 1)[0]!; + const response = await worker.fetch(new Request(`https://factorize.test/oauth/x/callback?error=access_denied&state=${encodeURIComponent(state)}`, { headers: { Cookie: `${fixture.cookie}; ${cookie}` } }), fixture.env, { waitUntil() {} } as any); + expect(response.headers.get("Location")).toContain("x=denied"); + expect(await repository.get(id)).toMatchObject({ status: "pending", accountId: null }); + } finally { await fixture.cleanup(); } + }); +}); diff --git a/packages/app/src/features/settings/integrations.tsx b/packages/app/src/features/settings/integrations.tsx index cca5401c..179d11bc 100644 --- a/packages/app/src/features/settings/integrations.tsx +++ b/packages/app/src/features/settings/integrations.tsx @@ -12,6 +12,7 @@ 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"; 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"; @@ -55,7 +56,7 @@ export function Integrations() { {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}`, )}
)} } - +

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"} diff --git a/packages/app/src/features/settings/x-connections.tsx b/packages/app/src/features/settings/x-connections.tsx new file mode 100644 index 00000000..5dabcf03 --- /dev/null +++ b/packages/app/src/features/settings/x-connections.tsx @@ -0,0 +1,95 @@ +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 { messageOf } from "../auth/session"; + +const permissions = [ + ["tweet.read", "Read posts the authorized account can view."], + ["tweet.write", "Post and delete posts for the authorized account."], + ["tweet.moderate.write", "Hide or unhide replies to the account's posts."], + ["users.read", "Read user profiles the account can view."], + ["users.email", "Read the authorized account's email address."], + ["follows.read", "Read the account's followers and following."], + ["follows.write", "Follow or unfollow accounts."], + ["offline.access", "Keep the connection active with refresh tokens."], + ["space.read", "Read Spaces the account can view."], + ["mute.read", "Read muted accounts."], ["mute.write", "Mute or unmute accounts."], + ["like.read", "Read posts liked by the account."], ["like.write", "Like or unlike posts."], + ["list.read", "Read Lists the account can access."], ["list.write", "Create and manage Lists."], + ["block.read", "Read blocked accounts."], ["block.write", "Block or unblock accounts."], + ["bookmark.read", "Read bookmarked posts."], ["bookmark.write", "Bookmark or remove bookmarks."], + ["dm.read", "Read Direct Messages."], ["dm.write", "Send and manage Direct Messages."], + ["media.write", "Upload media for posts."], ["broadcast.read", "Read live broadcasts and chat."], + ["broadcast.write", "Manage live broadcasts and send chat messages."], +] as const; +type XScope = typeof permissions[number][0]; +const suggested: XScope[] = ["tweet.read", "users.read", "offline.access"]; + +export function XConnections() { + const cache = useQueryClient(); + const [name, setName] = useState(""), [clientId, setClientId] = useState(""), [clientSecret, setClientSecret] = useState(""); + const [scopes, setScopes] = useState(suggested), [error, setError] = useState(null), [notice, setNotice] = useState(null); + const connections = useQuery({ queryKey: ["settings", "x-connections"], queryFn: async ({ signal }) => { + const result = await api.GET("/api/v1/x/connections", { signal }); + if (!result.data || result.error) throw new Error(messageOf(result.error)); + return result.data.connections; + }, staleTime: 0 }); + useEffect(() => { + const result = new URLSearchParams(location.search).get("x"); + const messages: Record = { + connected: "X account connected and verified.", denied: "X authorization was declined. You can try again when ready.", + expired: "That X authorization expired or was already used. Start a new attempt.", + scope_mismatch: "X granted fewer permissions than selected. Review the scopes and reconnect.", + session_required: "Sign in again as the workspace owner before connecting X.", failed: "X authorization could not be verified. Check the app setup and try again.", + }; + 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"] }); + } + }, [cache]); + const create = useMutation({ retry: false, mutationFn: async () => { + const response = await api.POST("/api/v1/x/connections", { body: { id: crypto.randomUUID(), name, clientId, clientSecret, scopes } }); + if (!response.data || response.error) throw new Error(messageOf(response.error)); + return response.data; + }, onSuccess: async connection => { + setClientSecret(""); setName(""); setClientId(""); + await cache.invalidateQueries({ queryKey: ["settings", "x-connections"] }); + 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); + }, onError: value => setError(value.message) }); + const authorize = useMutation({ retry: false, mutationFn: async (id: string) => { + const response = await api.POST("/api/v1/x/connections/{connectionId}/authorize", { params: { path: { connectionId: id } }, body: {} }); + if (!response.data || response.error) throw new Error(messageOf(response.error)); + location.assign(response.data.authorizationUrl); + }, 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" : "Setup incomplete"}
+ {connection.grantedScopes.length > 0 &&

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

} + {connection.status !== "connected" && } +
)} + +

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. +
  3. Enable OAuth 2.0, choose a Web App / confidential client, and add this callback URL exactly: {callback} .
  4. +
  5. Fund API credits and set spending limits in X's console. X API calls can incur charges; Factorize does not collect or estimate these charges.
  6. +
  7. Copy the OAuth 2.0 Client ID and Client Secret here. Factorize encrypts the secret and never shows it again.
  8. +
+ + + +
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}

} + +
+
; +} diff --git a/packages/app/test/x-connections.browser.test.mjs b/packages/app/test/x-connections.browser.test.mjs new file mode 100644 index 00000000..70eb6784 --- /dev/null +++ b/packages/app/test/x-connections.browser.test.mjs @@ -0,0 +1,63 @@ +import { before, after, test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { chromium } from "playwright"; + +let server, origin, browser; +before(async () => { + server = createServer(async (request, response) => { + const path = new URL(request.url, "http://local.test").pathname; + const file = (/^(\/assets\/|\/theme-init.js$|\/bee-mark-monochrome.png$|\/favicon.ico$)/.test(path)) ? path : "/index.html"; + try { const data = await readFile(new URL("../dist" + file, import.meta.url)); response.setHeader("Content-Type", file.endsWith(".js") ? "application/javascript" : file.endsWith(".css") ? "text/css" : "text/html"); response.end(data); } + catch { response.statusCode = 404; response.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)); }); + +test("X settings guides app callback setup, validated permissions, and starts owner authorization", async () => { + const context = await browser.newContext(), page = await context.newPage(); + const connectionId = "18a2410e-ea09-4fe0-af8a-719c0c91e6e2"; + let submitted, connected = false; + 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/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: [] }); + if (path === "/api/v1/model-accounts") return route.fulfill({ json: { accounts: [], revision: 0 } }); + if (path === "/api/v1/integrations/bearer") return route.fulfill({ json: { integrations: [], revision: 0 } }); + if (path === "/api/v1/integration-api-policies") return route.fulfill({ json: { integrations: [] } }); + if (path === "/api/v1/x/connections" && route.request().method() === "GET") return route.fulfill({ json: { connections: connected ? [{ id: connectionId, name: "My account", clientId: "client-123", scopes: ["tweet.read", "users.read", "offline.access", "tweet.write"], accountId: "12345", accountHandle: "verified_user", grantedScopes: ["tweet.read", "users.read", "offline.access", "tweet.write"], status: "connected", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }] : [] } }); + if (path === "/api/v1/x/connections" && route.request().method() === "POST") { + submitted = route.request().postDataJSON(); + return route.fulfill({ status: 201, json: { id: connectionId, name: submitted.name, clientId: submitted.clientId, scopes: submitted.scopes, accountId: null, accountHandle: null, grantedScopes: [], status: "pending", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() } }); + } + if (path.endsWith("/authorize")) return route.fulfill({ json: { authorizationUrl: "https://x.com/i/oauth2/authorize?response_type=code&state=one-time-state" }, headers: { "Set-Cookie": "factorize_x_oauth_state=opaque; HttpOnly; Secure; SameSite=Lax; Path=/oauth/x/callback; Max-Age=600" } }); + return route.fulfill({ json: {} }); + }); + 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(); + 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/); + await page.getByLabel("Connection name", { exact: true }).fill("My account"); + await page.getByLabel("OAuth 2.0 Client ID", { exact: true }).fill("client-123"); + await page.getByLabel("OAuth 2.0 Client Secret", { exact: true }).fill("private-client-secret"); + await page.getByRole("button", { name: "Add post write access" }).click(); + await page.getByRole("button", { name: "Save app and connect X" }).click(); + await page.waitForURL("https://x.com/i/oauth2/authorize**"); + assert.equal(submitted.clientSecret, "private-client-secret"); + assert.deepEqual(submitted.scopes, ["tweet.read", "users.read", "offline.access", "tweet.write"]); + assert.equal(submitted.name, "My account"); + connected = true; + await page.goto(origin + "/settings/integrations?x=connected"); + await page.getByRole("status").filter({ hasText: "X account connected and verified" }).waitFor(); + await page.getByText("@verified_user · 12345", { exact: true }).waitFor(); + await page.getByText(/Granted permissions:.*tweet.write/).waitFor(); + await context.close(); +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index ec4714c6..de44121d 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -2131,6 +2131,70 @@ 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)$ + /api/v1/x/connections/{connectionId}/authorize: + post: + summary: Start X OAuth authorization + description: |- + Requires an interactive owner session. Starts a short-lived PKCE authorization bound to this owner, tenant, session, connection, and selected scopes. The one-time state is set in an HttpOnly cookie. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: X authorization URL + content: + application/json: + schema: + type: object + properties: + authorizationUrl: + type: string + format: uri + required: + - authorizationUrl + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_x_connections_connectionId_authorize + tags: + - x + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + parameters: + - name: connectionId + in: path + required: true + schema: + 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)$ + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: {} + additionalProperties: false /api/v1/model-accounts: get: summary: List model accounts available to the owner From 11a2dd3f14f1e3204ca861bd277575bffad2503b Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 20:46:32 +0000 Subject: [PATCH 4/9] Fix X OAuth callback response headers --- packages/api/src/x-oauth-callback.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/api/src/x-oauth-callback.ts b/packages/api/src/x-oauth-callback.ts index 10e4ca1b..8e4c932c 100644 --- a/packages/api/src/x-oauth-callback.ts +++ b/packages/api/src/x-oauth-callback.ts @@ -10,7 +10,7 @@ const clearCookie = `${cookie}=; HttpOnly; Secure; SameSite=Lax; Path=/oauth/x/c const settings = (env: Env, result: string) => { const target = new URL("/settings/integrations", env.APP_ORIGIN); target.searchParams.set("x", result); - return Response.redirect(target.toString(), 303); + return target.toString(); }; /** X's registered redirect URI is fixed; all credentials and the PKCE verifier @@ -18,9 +18,7 @@ const settings = (env: Env, result: string) => { export async function xOAuthCallback(request: Request, env: Env): Promise { const url = new URL(request.url), clear = { "Set-Cookie": clearCookie, "Cache-Control": "no-store" }; const fail = (result: string) => { - const response = settings(env, result); - for (const [key, value] of Object.entries(clear)) response.headers.set(key, value); - return response; + return new Response(null, { status: 303, headers: { Location: settings(env, result), ...clear } }); }; const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET); if (!session) return fail("session_required"); From ddb3ec07dcccf9716a2a81f8fec534d752edfb0a Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 20:51:56 +0000 Subject: [PATCH 5/9] Test rejected X OAuth scope grants --- .../api/test/x-oauth-flow.postgres.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/api/test/x-oauth-flow.postgres.test.ts b/packages/api/test/x-oauth-flow.postgres.test.ts index f94b9066..543a3b38 100644 --- a/packages/api/test/x-oauth-flow.postgres.test.ts +++ b/packages/api/test/x-oauth-flow.postgres.test.ts @@ -71,4 +71,22 @@ describe.skipIf(!databaseUrl)("X owner OAuth callback (PostgreSQL)", { timeout: expect(await repository.get(id)).toMatchObject({ status: "pending", accountId: null }); } finally { await fixture.cleanup(); } }); + + it("rejects a token response that omits a requested permission", async () => { + const fixture = await loadingFixture(databaseUrl!); + try { + const repository = new XConnectionRepository(fixture.db, fixture.tenantId, fixture.env.CREDENTIAL_ENCRYPTION_KEY), id = crypto.randomUUID(); + await repository.create({ id, name: "Limited X app", clientId: "client-789", clientSecret: "private", scopes: ["tweet.read", "users.read", "offline.access"] }); + const start = await worker.fetch(new Request(`https://factorize.test/api/v1/x/connections/${id}/authorize`, { method: "POST", headers: { Cookie: fixture.cookie, Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, body: "{}" }), fixture.env, { waitUntil() {} } as any); + const state = new URL((await start.json() as { authorizationUrl: string }).authorizationUrl).searchParams.get("state")!; + const cookie = start.headers.get("Set-Cookie")!.split(";", 1)[0]!; + const fetcher = vi.fn(async () => Response.json({ access_token: "secret-access", refresh_token: "secret-refresh", expires_in: 3600, scope: "tweet.read users.read" })); + vi.stubGlobal("fetch", fetcher); + const response = await worker.fetch(new Request(`https://factorize.test/oauth/x/callback?code=authorization-code&state=${encodeURIComponent(state)}`, { headers: { Cookie: `${fixture.cookie}; ${cookie}` } }), fixture.env, { waitUntil() {} } as any); + expect(response.headers.get("Location")).toContain("x=scope_mismatch"); + expect(fetcher).toHaveBeenCalledOnce(); + expect(await repository.get(id)).toMatchObject({ status: "pending", accountId: null, grantedScopes: [] }); + await expect(repository.clientCredentials(id)).resolves.toMatchObject({ clientSecret: "private", accessToken: undefined, refreshToken: undefined }); + } finally { await fixture.cleanup(); } + }); }); From a99b26316454c5fdda34d7daa22c96e1adf2e4ca Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 21:17:25 +0000 Subject: [PATCH 6/9] Add selected X connections to run proxy --- packages/api-client/src/schema.d.ts | 24 +++++- .../migrations/0057_revoke_x_connections.sql | 7 ++ packages/api/migrations/README.md | 4 +- packages/api/src/agent-api.ts | 34 ++++++++ packages/api/src/agent-driver.ts | 3 +- packages/api/src/api-contract.ts | 6 +- packages/api/src/flow-schemas.ts | 1 + packages/api/src/flow-service.ts | 14 +++- packages/api/src/job-contracts.ts | 1 + packages/api/src/job-domain.ts | 2 + packages/api/src/postgres/job-repository.ts | 2 +- packages/api/src/postgres/run-scheduler.ts | 4 +- packages/api/src/postgres/schema.ts | 2 +- .../src/postgres/x-connection-repository.ts | 8 +- packages/api/src/run-identity-guest-helper.ts | 2 +- packages/api/src/run-instructions.ts | 3 +- packages/api/src/run-outbound-proxy.ts | 4 +- packages/api/src/run-read-contracts.ts | 1 + packages/api/test/agent-driver.test.ts | 4 +- packages/api/test/loading.postgres.test.ts | 28 +++++++ .../test/run-identity-guest-helper.test.ts | 7 +- .../api/test/vendor-run-auth.postgres.test.ts | 45 +++++++++++ .../x-connection-repository.postgres.test.ts | 5 +- .../app/src/features/jobs/editor-queries.ts | 5 +- .../app/src/features/jobs/editor-state.ts | 2 +- packages/app/src/features/jobs/editor.tsx | 3 + .../src/features/settings/x-connections.tsx | 4 +- packages/app/test/editor.browser.test.mjs | 15 ++++ packages/docs/openapi.yaml | 81 ++++++++++++++++++- 29 files changed, 288 insertions(+), 33 deletions(-) create mode 100644 packages/api/migrations/0057_revoke_x_connections.sql diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 892a0e47..42301786 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -44,7 +44,7 @@ export interface paths { post?: never; /** * Delete an X connection - * @description Requires an interactive owner session. Deletes the encrypted client credential and connection metadata. + * @description Requires an interactive owner session. Immediately clears the encrypted credential and revokes the connection. A secret-free tombstone prevents old run snapshots from being revived if an identifier is reused. * * Requires the integrations:write scope. * @@ -1901,7 +1901,7 @@ export interface paths { }; /** * Discover this run's selected integration endpoints - * @description Requires vendor-verified run identity. Returns only snapshotted selections and current availability, without origins or credentials. Selection authorization is independent of the run's Factorize API scopes. + * @description Requires vendor-verified run identity. Returns only snapshotted selections, safe connection metadata, X OAuth scopes, and current availability, without origins or credentials. X connections use /x/{connectionId}/ for supported API v2 resources; each resource is checked against selected and granted OAuth scopes. Selection authorization is independent of the run's Factorize API scopes. * * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ @@ -2951,6 +2951,7 @@ export interface components { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; }; ManualInvocation: { /** @default */ @@ -3099,7 +3100,7 @@ export interface operations { accountHandle: string | null; grantedScopes: string[]; /** @enum {string} */ - status: "pending" | "connected" | "reconnect_required"; + status: "pending" | "connected" | "reconnect_required" | "revoked"; createdAt: string; updatedAt: string; }[]; @@ -3152,7 +3153,7 @@ export interface operations { accountHandle: string | null; grantedScopes: string[]; /** @enum {string} */ - status: "pending" | "connected" | "reconnect_required"; + status: "pending" | "connected" | "reconnect_required" | "revoked"; createdAt: string; updatedAt: string; }; @@ -6696,6 +6697,7 @@ export interface operations { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -6995,6 +6997,7 @@ export interface operations { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -7206,6 +7209,7 @@ export interface operations { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -7817,6 +7821,15 @@ export interface operations { path: string; available: boolean; }[]; + /** @default [] */ + xConnections: { + id: string; + name: string; + accountHandle: string | null; + scopes: string[]; + path: string; + available: boolean; + }[]; providers: { githubInstallations: { installationId: number; @@ -8066,6 +8079,7 @@ export interface operations { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -8358,6 +8372,7 @@ export interface operations { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; /** Format: date-time */ expectedUpdatedAt?: string; }; @@ -8407,6 +8422,7 @@ export interface operations { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; executionConfigId: string; agentKind: string; concurrencyLimit: number; diff --git a/packages/api/migrations/0057_revoke_x_connections.sql b/packages/api/migrations/0057_revoke_x_connections.sql new file mode 100644 index 00000000..0baf5258 --- /dev/null +++ b/packages/api/migrations/0057_revoke_x_connections.sql @@ -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; diff --git a/packages/api/migrations/README.md b/packages/api/migrations/README.md index 7871c761..95926889 100644 --- a/packages/api/migrations/README.md +++ b/packages/api/migrations/README.md @@ -27,7 +27,9 @@ 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. +`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. diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index 95d1b97f..c3e493e5 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -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 } from "./postgres/x-connection-repository"; import type { z } from "zod"; export class AgentApiError extends Error { @@ -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}> = []; @@ -108,6 +127,21 @@ 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), credentials = await repository.clientCredentials(connectionId); + if (!connection || connection.status !== "connected" || !credentials?.accessToken || !credentials.expiresAt || Date.parse(credentials.expiresAt) <= Date.now()) throw forbidden(); + if (!connection.scopes.includes(required) || !connection.grantedScopes.includes(required)) throw new AgentApiError(403, "insufficient_scope", `This X connection does not grant ${required}.`); + 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: credentials.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, signal?: AbortSignal) { const parsed = requestApiInput.parse(input); // Decode and size-check before any upstream operation. diff --git a/packages/api/src/agent-driver.ts b/packages/api/src/agent-driver.ts index adf4255f..74f160dc 100644 --- a/packages/api/src/agent-driver.ts +++ b/packages/api/src/agent-driver.ts @@ -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[]; @@ -82,6 +82,7 @@ function providerEndpointEnv(config: AgentConfiguration): Record ...(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 { diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index d46b3ca6..80bd8568 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -144,7 +144,7 @@ const modelAccountCreate = z.object({ }).strict(); const modelAccountDelete = z.object({ expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid() }).strict(); const modelAccountList = z.object({ revision: z.number().int().nonnegative(), accounts: z.array(modelAccountMetadata) }); -const xConnectionMetadata = z.object({ id: z.uuid(), name: z.string(), clientId: z.string(), scopes: z.array(z.string()), accountId: z.string().nullable(), accountHandle: z.string().nullable(), grantedScopes: z.array(z.string()), status: z.enum(["pending", "connected", "reconnect_required"]), createdAt: z.string(), updatedAt: z.string() }); +const xConnectionMetadata = z.object({ id: z.uuid(), name: z.string(), clientId: z.string(), scopes: z.array(z.string()), accountId: z.string().nullable(), accountHandle: z.string().nullable(), grantedScopes: z.array(z.string()), status: z.enum(["pending", "connected", "reconnect_required", "revoked"]), createdAt: z.string(), updatedAt: z.string() }); const xConnectionCreate = z.object({ id: z.uuid(), name: z.string().trim().min(1).max(120), clientId: z.string().trim().min(1).max(256), clientSecret: z.string().min(1).max(4096).regex(/^[^\r\n]+$/).meta({ writeOnly: true }), @@ -244,7 +244,7 @@ export const API_ROUTES: RouteContract[] = [ }, (service, { body }) => service.createXConnection(body), { body: xConnectionCreate, maxBodyBytes: 8192, ownerSession: true }), route("DELETE", "/api/v1/x/connections/{connectionId}", "integrations:write", { summary: "Delete an X connection", - description: "Requires an interactive owner session. Deletes the encrypted client credential and connection metadata.", + description: "Requires an interactive owner session. Immediately clears the encrypted credential and revokes the connection. A secret-free tombstone prevents old run snapshots from being revived if an identifier is reused.", responses: { "200": { description: "X connection deleted", content: { "application/json": { schema: jsonSchema(z.object({ id: z.uuid(), deleted: z.literal(true) }), "output") } } } }, }, (service, { params }) => service.deleteXConnection(params.connectionId), { ownerSession: true, parameters: z.object({ connectionId: z.uuid() }) }), route("POST", "/api/v1/x/connections/{connectionId}/authorize", "integrations:write", { @@ -897,7 +897,7 @@ export const API_ROUTES: RouteContract[] = [ description: "Returns the verified calling identity and effective scopes without credentials. Requires a verified active identity but no application-resource scope; callers with zero scopes can inspect only their own identity. Execution provisioning uses this operation to verify the dedicated run proxy. Execution VMs must not have additional shared Factorize proxy attachments.", responses: { "200": { description: "Verified runtime identity", content: { "application/json": { schema: jsonSchema(runtimeContextResponse, "output") } } } } }, service => service.getRuntimeContext()), - route("GET", "/api/v1/runtime-integrations", "integrations:read", { summary: "Discover this run's selected integration endpoints", description: "Requires vendor-verified run identity. Returns only snapshotted selections and current availability, without origins or credentials. Selection authorization is independent of the run's Factorize API scopes.", responses: { "200": { description: "Selected run integrations", content: { "application/json": { schema: jsonSchema(runtimeIntegrationsResponse, "output") } } } } }, service => service.getRuntimeIntegrations()), + route("GET", "/api/v1/runtime-integrations", "integrations:read", { summary: "Discover this run's selected integration endpoints", description: "Requires vendor-verified run identity. Returns only snapshotted selections, safe connection metadata, X OAuth scopes, and current availability, without origins or credentials. X connections use /x/{connectionId}/ for supported API v2 resources; each resource is checked against selected and granted OAuth scopes. Selection authorization is independent of the run's Factorize API scopes.", responses: { "200": { description: "Selected run integrations", content: { "application/json": { schema: jsonSchema(runtimeIntegrationsResponse, "output") } } } } }, service => service.getRuntimeIntegrations()), route("GET", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:read", { summary: "List a source job's manual invocation destinations", responses: { "200": { description: "Configured destination jobs in the same project", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params }) => service.getInvocationPermissions(params.jobId)), route("PUT", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:write", { summary: "Replace a source job's manual invocation destinations", description: "Requires an owner session, scoped API key, or authorized OAuth client with jobs:write. Destinations must belong to the source job's project; self-invocation is allowed. A run token may invoke a configured destination only while both jobs remain in the same project. Lifecycle subscriptions do not create permissions.", responses: { "200": { description: "Saved manual invocation permissions", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params, body }) => service.setInvocationPermissions(params.jobId, body.destinationJobIds), { body: invocationPermissionsInput }), route( diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 89000687..6c230bc6 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -81,6 +81,7 @@ export const jobInputSchema = z.object({ modelAccountId: z.guid().optional(), githubInstallationIds: z.array(z.number().int().positive()).max(100).refine(ids => new Set(ids).size === ids.length, "GitHub installations must be unique").optional(), linearConnectionId: z.literal("linear").nullable().optional(), + xConnectionIds: z.array(z.guid()).max(100).refine(ids => new Set(ids).size === ids.length, "X connections must be unique").optional(), }).strict().superRefine((value, context) => { if (value.executionType !== "code" && !value.promptTemplate?.trim()) context.addIssue({ code: "custom", path: ["promptTemplate"], message: "Agent jobs require a prompt template." }); if (value.executionType === "code" && !value.script?.trim()) context.addIssue({ code: "custom", path: ["script"], message: "Code jobs require a script." }); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index a45c2415..c0d577e2 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -106,6 +106,7 @@ export class ApiService { const portableIntegrationIds = input.portableIntegrationIds ?? current?.portableIntegrationIds ?? current?.executionConfig.portableIntegrationIds ?? []; const githubInstallationIds = input.githubInstallationIds ?? current?.githubInstallationIds ?? current?.executionConfig.githubInstallationIds ?? []; const linearConnectionId = input.linearConnectionId !== undefined ? input.linearConnectionId : current?.linearConnectionId ?? current?.executionConfig.linearConnectionId; + const xConnectionIds = input.xConnectionIds ?? current?.xConnectionIds ?? current?.executionConfig.xConnectionIds ?? []; if (executionType === "code" && input.modelAccess === "portable") throw new ServiceError(400, "invalid_request", "Code jobs cannot select model access."); const modelAccess = executionType === "code" ? "native" : input.modelAccess ?? current?.modelAccess ?? current?.executionConfig.modelAccess ?? (config.executionProvider === "fly" ? "portable" : "native"); if (modelAccess === "portable" && config.agentKind !== "codex") throw new ServiceError(400,"invalid_request","Managed model accounts support Codex jobs."); @@ -120,11 +121,13 @@ export class ApiService { const activeInstallationIds = new Set(installations.filter(item => item.state === "active").map(item => Number(item.installationId))); if (new Set(githubInstallationIds).size !== githubInstallationIds.length || githubInstallationIds.some(id => !activeInstallationIds.has(id))) throw new ServiceError(400, "invalid_request", "One or more selected GitHub installations are unavailable."); if (linearConnectionId && (!await this.connections().get("linear"))) throw new ServiceError(400, "invalid_request", "The selected Linear connection is unavailable."); + const xConnections = await new XConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).list(); + if (new Set(xConnectionIds).size !== xConnectionIds.length || xConnectionIds.some(id => !xConnections.some(connection => connection.id === id && connection.status === "connected"))) throw new ServiceError(400, "invalid_request", "One or more selected X connections are unavailable. Connect them or remove the selections."); if (modelAccountId && byId.get(modelAccountId)?.kind !== "model") throw new ServiceError(400, "invalid_request", "The selected model account is unavailable."); if (modelAccountId && !modelCredentialConfigured((await this.credentials().managedCredential(modelAccountId,"model"))?.payload??"")) throw new ServiceError(400,"invalid_request","Connect the selected model account before using it in a job."); for (const id of portableIntegrationIds) if (!await this.credentials().managedCredential(id,"bearer")) throw new ServiceError(400,"invalid_request","Re-enter the selected bearer credential before using it in a job."); if (modelAccess === "portable" && executionType !== "code" && !modelAccountId) throw new ServiceError(400, "invalid_request", "Portable model access requires a model account."); - return { portableIntegrationIds, githubInstallationIds, ...(linearConnectionId ? { linearConnectionId } : {}), modelAccess, ...(modelAccountId ? { modelAccountId } : {}) }; + return { portableIntegrationIds, githubInstallationIds, ...(linearConnectionId ? { linearConnectionId } : {}), xConnectionIds, modelAccess, ...(modelAccountId ? { modelAccountId } : {}) }; } private async validateExecutionOptions(id: string, model: string, effort: string, tags: string[]) { @@ -233,17 +236,20 @@ export class ApiService { const config = active.execution_config; const ids = Array.isArray(config.portableIntegrationIds) ? config.portableIntegrationIds : []; const githubIds = Array.isArray(config.githubInstallationIds) ? config.githubInstallationIds : []; - const [records, installations, revoked, linear, model] = await Promise.all([ + const xIds = Array.isArray(config.xConnectionIds) ? config.xConnectionIds : []; + const [records, installations, revoked, linear, model, xConnections] = await Promise.all([ db.pool.query<{id: string; name: string; description: string | null}>("SELECT id,name,description FROM app.integration_records WHERE tenant_id=$1 AND id=ANY($2::uuid[]) AND kind='bearer' AND deleted_at IS NULL", [tenantId, ids]), db.pool.query<{installation_id: number; state: string}>("SELECT installation_id,state FROM app.github_installations WHERE tenant_id=$1 AND installation_id=ANY($2::bigint[])", [tenantId, githubIds]), db.pool.query<{kind: string; credential_id: string}>("SELECT kind,credential_id FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2", [tenantId, runId]), config.linearConnectionId === "linear" ? db.pool.query("SELECT 1 FROM app.connections WHERE tenant_id=$1 AND kind='linear'", [tenantId]) : null, config.modelAccess === "portable" && typeof config.modelAccountId === "string" ? db.pool.query("SELECT 1 FROM app.integration_records WHERE tenant_id=$1 AND id=$2 AND kind='model' AND deleted_at IS NULL", [tenantId, config.modelAccountId]) : null, + db.pool.query<{id: string; name: string; account_handle: string | null; granted_scopes: string[]; status: string}>("SELECT id,name,account_handle,granted_scopes,status FROM app.x_connections WHERE tenant_id=$1 AND id=ANY($2::uuid[])", [tenantId, xIds]), ]); const denied = new Set(revoked.rows.map(row => `${row.kind}:${row.credential_id}`)); return publicValue(runtimeIntegrationsResponse, { kind: "factorize-run-integrations-v1", integrations: ids.map((id: string) => { const record = records.rows.find(row => row.id === id); return {id, name: record?.name ?? "Unavailable integration", description: record?.description ?? null, path: `/integrations/${id}/`, available: Boolean(record) && !denied.has(`bearer:${id}`)}; }), + xConnections: xIds.map((id: string) => { const connection = xConnections.rows.find(row => row.id === id); return { id, name: connection?.name ?? "Unavailable X connection", accountHandle: connection?.account_handle ?? null, scopes: connection?.granted_scopes ?? [], path: `/x/${id}/`, available: connection?.status === "connected" }; }), providers: { githubInstallations: githubIds.map((installationId: number) => ({installationId, path: `/providers/github/${installationId}/`, available: installations.rows.some(row => Number(row.installation_id) === installationId && row.state === "active") && !denied.has(`github:${installationId}`)})), linear: config.linearConnectionId === "linear" ? {path: "/providers/linear/", available: Boolean(linear?.rowCount) && !denied.has("linear:linear")} : null, @@ -631,7 +637,9 @@ export class ApiService { } async authorizeXConnection(id: string) { await this.authorizeOwnerSession("integrations:write"); - const repository = this.xConnections(), connection = await repository.get(id), credentials = await repository.clientCredentials(id); + const repository = this.xConnections(), connection = await repository.get(id); + if (connection?.status === "revoked") throw new ServiceError(404, "not_found", "X connection not found."); + const credentials = await repository.clientCredentials(id); if (!connection || !credentials) throw new ServiceError(404, "not_found", "X connection not found."); const scopes = validateXOAuthScopes(connection.scopes); const pkce = await createXPKCE(), nonce = crypto.randomUUID(), expires = Math.floor(Date.now() / 1000) + 600; diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index 27d47ca6..5282f836 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -47,6 +47,7 @@ export const jobResponse = z.object({ runScopes: z.array(scopeSchema), portableIntegrationIds: z.array(z.guid()).optional(), modelAccess: z.enum(["native", "portable"]).optional(), modelAccountId: z.guid().optional(), githubInstallationIds: z.array(z.number().int().positive()).optional(), linearConnectionId: z.literal("linear").nullable().optional(), + xConnectionIds: z.array(z.guid()).optional(), executionConfigId: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(), runningCount: z.number().int(), currentRuns: z.number().int(), maxConcurrency: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), triggers: z.array(triggerResponse), diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 0e5ec5fb..8ced6e81 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -20,6 +20,7 @@ export interface ExecutionConfig { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; executionProvider?: "exe" | "fly" | "docker"; region?: string; size?: string; @@ -62,6 +63,7 @@ export interface Job { modelAccountId?: string; githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; } export interface InvocationRequest { diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index b6625812..09af8e99 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -34,7 +34,7 @@ export class PostgresJobRepository implements JobRepository { triggerRows = loadedTriggers ?? await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,js.position FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.job_id=${row.id}::uuid ORDER BY js.position`)).rows; } - return { id: row.id, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, description: row.description ?? "", slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, githubInstallationIds: row.executionConfig.githubInstallationIds ?? [], linearConnectionId: row.executionConfig.linearConnectionId, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; + return { id: row.id, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, description: row.description ?? "", slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, githubInstallationIds: row.executionConfig.githubInstallationIds ?? [], linearConnectionId: row.executionConfig.linearConnectionId, xConnectionIds: row.executionConfig.xConnectionIds ?? [], concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } async getJob(id: string): Promise { diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 37bd2468..9ad604c1 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -193,7 +193,7 @@ export class RunScheduler { if (run.executionConfig.agentKind === "Amp") throw new Error("Amp execution is unavailable for new runs because it cannot deliver the required structured result file. Choose an exe.dev agent integration."); const backend = await this.backend(run), driver = agentDriver(run.executionConfig.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionConfig.model, effort: run.executionConfig.effort, - providerEndpoints: { githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId) }, + providerEndpoints: { githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId), xConnectionIds: run.executionConfig.xConnectionIds ?? [] }, ...(driver.kind === "codex" ? { codexModel: { baseUrl: run.executionConfig.modelAccess === "portable" && run.executionConfig.modelAccountId ? "http://127.0.0.1:18180/providers/model/v1" : this.env.CODEX_MODEL_BASE_URL ?? "https://llm.int.exe.xyz/v1" } } : {}), }); const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env); @@ -201,7 +201,7 @@ export class RunScheduler { const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await this.launchBackend(run, backend, { runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runAccessInstructions({ githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId) })}`, runIdentity: { backendOrigin: this.env.APP_ORIGIN }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); + const launched = await this.launchBackend(run, backend, { runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runAccessInstructions({ githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId), xConnectionIds: run.executionConfig.xConnectionIds ?? [] })}`, runIdentity: { backendOrigin: this.env.APP_ORIGIN }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index f735bb32..a161e3cc 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -55,7 +55,7 @@ export const xConnections = app.table("x_connections", { accountId: text("account_id"), accountHandle: text("account_handle"), grantedScopes: text("granted_scopes").array().notNull().default(sql`'{}'::text[]`), status: text("status").$type<"pending" | "connected" | "reconnect_required">().notNull().default("pending"), createdAt: createdAt(), updatedAt: updatedAt(), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("x_connections_tenant_name").on(t.tenantId, sql`lower(${t.name})`), check("x_connections_status_check", sql`${t.status} IN ('pending','connected','reconnect_required')`)]); +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("x_connections_tenant_name").on(t.tenantId, sql`lower(${t.name})`).where(sql`${t.status} <> 'revoked'`), check("x_connections_status_check", sql`${t.status} IN ('pending','connected','reconnect_required','revoked')`)]); export const xOAuthAttempts = app.table("x_oauth_attempts", { tenantId: uuid("tenant_id").notNull(), nonce: text("nonce").notNull(), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), connectionId: uuid("connection_id").notNull(), scopes: text("scopes").array().notNull(), encryptedVerifier: text("encrypted_verifier").notNull(), diff --git a/packages/api/src/postgres/x-connection-repository.ts b/packages/api/src/postgres/x-connection-repository.ts index 42758e85..67c9f7f7 100644 --- a/packages/api/src/postgres/x-connection-repository.ts +++ b/packages/api/src/postgres/x-connection-repository.ts @@ -9,7 +9,7 @@ export type XConnectionMetadata = { accountId: string | null; accountHandle: string | null; grantedScopes: string[]; - status: "pending" | "connected" | "reconnect_required"; + status: "pending" | "connected" | "reconnect_required" | "revoked"; createdAt: string; updatedAt: string; }; @@ -72,6 +72,7 @@ export class XConnectionRepository { async consumeOAuthAttempt(nonce: string): Promise<{ userId: string; sessionVersion: number; connectionId: string; scopes: string[]; verifier: string } | null> { const { rows } = await this.database.pool.query<{ user_id: string; session_version: number; connection_id: string; scopes: string[]; encrypted_verifier: string }>( `UPDATE app.x_oauth_attempts SET consumed_at=now() WHERE tenant_id=$1 AND nonce=$2 AND consumed_at IS NULL AND expires_at>now() + AND EXISTS (SELECT 1 FROM app.x_connections c WHERE c.tenant_id=app.x_oauth_attempts.tenant_id AND c.id=app.x_oauth_attempts.connection_id AND c.status<>'revoked') RETURNING user_id,session_version,connection_id,scopes,encrypted_verifier`, [this.tenantId, nonce]); const row = rows[0]; if (!row) return null; @@ -82,7 +83,7 @@ export class XConnectionRepository { const credentials = await this.clientCredentials(id); if (!credentials) throw new Error("X connection not found"); const encrypted = await encrypt(JSON.stringify({ clientSecret: credentials.clientSecret, accessToken: input.accessToken, refreshToken: input.refreshToken, expiresAt: input.expiresAt }), this.encryptionKey); - const result = await this.database.pool.query(`UPDATE app.x_connections SET encrypted_secret=$3,account_id=$4,account_handle=$5,granted_scopes=$6,status='connected',updated_at=now() WHERE tenant_id=$1 AND id=$2`, + const result = await this.database.pool.query(`UPDATE app.x_connections SET encrypted_secret=$3,account_id=$4,account_handle=$5,granted_scopes=$6,status='connected',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status<>'revoked'`, [this.tenantId, id, encrypted, input.accountId, input.accountHandle, input.grantedScopes]); if (!result.rowCount) throw new Error("X connection not found"); } @@ -92,7 +93,8 @@ export class XConnectionRepository { } async delete(id: string): Promise { - const { rowCount } = await this.database.pool.query("DELETE FROM app.x_connections WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); + const tombstone = await encrypt(JSON.stringify({}), this.encryptionKey); + const { rowCount } = await this.database.pool.query("UPDATE app.x_connections SET status='revoked',encrypted_secret=$3,account_id=NULL,account_handle=NULL,granted_scopes='{}',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status<>'revoked'", [this.tenantId, id, tombstone]); return (rowCount ?? 0) > 0; } } diff --git a/packages/api/src/run-identity-guest-helper.ts b/packages/api/src/run-identity-guest-helper.ts index a416a6af..0663111a 100644 --- a/packages/api/src/run-identity-guest-helper.ts +++ b/packages/api/src/run-identity-guest-helper.ts @@ -54,7 +54,7 @@ export function createRunIdentityProxy(config, {getToken = () => vendorToken(con if (url.pathname === "/api/v1" || url.pathname.startsWith("/api/v1/") || url.pathname === "/mcp") path = url.pathname; else if (/^\/internal\/run-(?:artifacts|trace-chunks)\/[^/]+$/.test(url.pathname)) path = url.pathname; else if (url.pathname === "/integrations") path = "/api/v1/runtime-integrations"; - else if (url.pathname.startsWith("/integrations/") || url.pathname.startsWith("/providers/")) path = "/internal/run-proxy/" + config.runId + url.pathname; + else if (url.pathname.startsWith("/integrations/") || url.pathname.startsWith("/providers/") || url.pathname.startsWith("/x/")) path = "/internal/run-proxy/" + config.runId + url.pathname; else { outgoing.writeHead(404).end(); return; } const token = requireToken(await getToken()); const headers = new Headers(); diff --git a/packages/api/src/run-instructions.ts b/packages/api/src/run-instructions.ts index 474a4cc3..03afb3b2 100644 --- a/packages/api/src/run-instructions.ts +++ b/packages/api/src/run-instructions.ts @@ -1,8 +1,9 @@ /** Public guest instructions. No run token, upstream token, shared proxy URL, * pairing, or unlock operation is part of the run access protocol. */ -export function runAccessInstructions(providers: {githubInstallationIds?: number[]; linear?: boolean; model?: boolean} = {}): string { +export function runAccessInstructions(providers: {githubInstallationIds?: number[]; linear?: boolean; model?: boolean; xConnectionIds?: string[]} = {}): string { const selected = (providers.githubInstallationIds ?? []).map(id => `GitHub installation ${id}: http://127.0.0.1:18180/providers/github/${id}/ (REST/GraphQL and Git smart HTTP)`); if (providers.linear) selected.push("Linear: http://127.0.0.1:18180/providers/linear/graphql"); if (providers.model) selected.push("Model: http://127.0.0.1:18180/providers/model/v1 (already configured for Codex)"); + for (const id of providers.xConnectionIds ?? []) selected.push(`X connection ${id}: http://127.0.0.1:18180/x/${id}/ (X API v2; only granted OAuth scopes are available)`); return `\n\n## Factorize run access\nUse FACTORIZE_PROXY_URL (http://127.0.0.1:18180) for all Factorize /api/v1 and /mcp requests. The local helper obtains fresh vendor identity and Factorize authorizes only this active run's tenant, selected connections and configured API scopes. Do not supply Authorization headers or look for Factorize/upstream tokens. GET $FACTORIZE_PROXY_URL/api/v1/runtime-context to discover your effective scopes and GET $FACTORIZE_PROXY_URL/integrations for selected integration paths and current availability. Job edits affect future runs. Use only the selected endpoints for upstream requests. Unavailable selections require owner repair; do not substitute another credential. Job-to-job invocation also requires explicit destination authorization. A granted jobs:write permits editing job configuration and future run scopes, but cannot expand this run's scopes or invocation destinations. If optional bookkeeping is outside the scopes, continue the authorized implementation and report that limitation. Use FACTORIZE_RESULT_PATH to report the final outcome.${selected.length ? `\n\n## Selected provider clients\n${selected.join("\n")}` : ""}\n`; } diff --git a/packages/api/src/run-outbound-proxy.ts b/packages/api/src/run-outbound-proxy.ts index d103df9b..5dbb9ab2 100644 --- a/packages/api/src/run-outbound-proxy.ts +++ b/packages/api/src/run-outbound-proxy.ts @@ -18,9 +18,11 @@ export async function runOutboundProxyFetch(request: Request, env: Env): Promise const github = /^\/providers\/github\/([1-9][0-9]*)(\/.*)?$/.exec(path); const linear = /^\/providers\/linear(\/.*)?$/.exec(path); const model = /^\/providers\/model\/v1(\/.*)?$/.exec(path); - const kind = bearer ? "bearer" : github ? "github" : linear ? "linear" : model ? "model" : null; + const x = /^\/x\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(\/.*)$/i.exec(path); + const kind = bearer ? "bearer" : github ? "github" : linear ? "linear" : model ? "model" : x ? "x" : null; if (!kind) return unavailable(); try { + if (x) return await new AgentApiService(env, auth).forwardX(x[1]!, `${x[2]}${url.search}`, request); let id = bearer?.[1] ?? github?.[1] ?? "linear"; if (model) { const row = (await databaseFor(env).pool.query<{execution_config: {modelAccountId?: string}}>("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [auth.tenantId,auth.runId])).rows[0]; diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index 923ac443..c176eed9 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -7,6 +7,7 @@ const runIntegration = z.object({ id: z.string(), name: z.string(), description: export const runtimeIntegrationsResponse = z.object({ kind: z.literal("factorize-run-integrations-v1"), integrations: z.array(runIntegration), + xConnections: z.array(z.object({ id: z.string(), name: z.string(), accountHandle: z.string().nullable(), scopes: z.array(z.string()), path: z.string(), available: z.boolean() })).default([]), providers: z.object({ githubInstallations: z.array(z.object({installationId: z.number().int(), path: z.string(), available: z.boolean()})), linear: z.object({path: z.string(), available: z.boolean()}).nullable(), diff --git a/packages/api/test/agent-driver.test.ts b/packages/api/test/agent-driver.test.ts index ec59930f..a818aaef 100644 --- a/packages/api/test/agent-driver.test.ts +++ b/packages/api/test/agent-driver.test.ts @@ -11,13 +11,15 @@ describe("agent drivers", () => { for (const kind of ["codex", "claude", "pi"] as const) expect(JSON.stringify(agentDriver(kind).launch("run-1", {}))).not.toContain("ssh"); }); it("passes only selected listener endpoints to provider clients", () => { - const launch = agentDriver("codex").launch("run-1", { providerEndpoints: { githubInstallationIds: [42, 43, 42], linear: true, model: true } }); + const xId = "00000000-0000-4000-8000-000000000099"; + const launch = agentDriver("codex").launch("run-1", { providerEndpoints: { githubInstallationIds: [42, 43, 42], linear: true, model: true, xConnectionIds: [xId, xId] } }); expect(JSON.parse(launch.env.FACTORIZE_GITHUB_INSTALLATIONS!)).toEqual([ { installationId: 42, apiUrl: "http://127.0.0.1:18180/providers/github/42/", gitUrl: "http://127.0.0.1:18180/providers/github/42/" }, { installationId: 43, apiUrl: "http://127.0.0.1:18180/providers/github/43/", gitUrl: "http://127.0.0.1:18180/providers/github/43/" }, ]); expect(launch.env.FACTORIZE_LINEAR_API_URL).toBe("http://127.0.0.1:18180/providers/linear/"); expect(launch.env.FACTORIZE_MODEL_API_URL).toBe("http://127.0.0.1:18180/providers/model/v1"); + expect(JSON.parse(launch.env.FACTORIZE_X_CONNECTIONS!)).toEqual([{ id: xId, apiUrl: `http://127.0.0.1:18180/x/${xId}/` }]); expect(JSON.stringify(launch.env)).not.toMatch(/token|secret|credential/i); }); }); diff --git a/packages/api/test/loading.postgres.test.ts b/packages/api/test/loading.postgres.test.ts index 42b68040..56fae3c0 100644 --- a/packages/api/test/loading.postgres.test.ts +++ b/packages/api/test/loading.postgres.test.ts @@ -9,6 +9,7 @@ import { CredentialRepository } from "../src/postgres/credential-repository"; import { FlyConnectionRepository } from "../src/postgres/fly-connection-repository"; import { FlyExecutionConfigurationRepository } from "../src/postgres/fly-execution-configuration-repository"; import { GitHubRepository } from "../src/postgres/github-repository"; +import { XConnectionRepository } from "../src/postgres/x-connection-repository"; import { encrypt } from "../src/crypto"; import { ApiService } from "../src/flow-service"; import worker from "../src/worker"; @@ -183,6 +184,33 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => { if (priorLinear) await connections.put("linear", priorLinear); else await connections.delete("linear"); } }); + it("validates tenant-owned X selections and keeps each run's X connection snapshot immutable", async () => { + const service = new ApiService(env, auth), x = new XConnectionRepository(db, tenantId, env.CREDENTIAL_ENCRYPTION_KEY), foreign = new XConnectionRepository(db, otherTenant, env.CREDENTIAL_ENCRYPTION_KEY); + const firstId = crypto.randomUUID(), nextId = crypto.randomUUID(), foreignId = crypto.randomUUID(), slug = `x-provider-${crypto.randomUUID().slice(0, 8)}`; + const scopes = ["tweet.read", "users.read", "offline.access"]; + const createConnected = async (repository: XConnectionRepository, id: string, name: string) => { + await repository.create({ id, name, clientId: "public-client", clientSecret: "private", scopes }); + await repository.completeOAuth(id, { accessToken: "access", refreshToken: "refresh", expiresAt: new Date(Date.now()+3_600_000).toISOString(), accountId: id, accountHandle: name.toLowerCase().replaceAll(" ", "_"), grantedScopes: scopes }); + }; + const base = { name: "X provider selections", slug, promptTemplate: "Do work", executionConfigId: "local", concurrencyLimit: 1, triggers: [{ kind: "manual" as const, enabled: true, config: {} }] }; + try { + await createConnected(x, firstId, "First X"); await createConnected(x, nextId, "Next X"); await createConnected(foreign, foreignId, "Foreign X"); + await expect(service.createJob({ ...base, xConnectionIds: [foreignId] })).rejects.toMatchObject({ status: 400 }); + const job = await service.createJob({ ...base, xConnectionIds: [firstId] }); + expect(job).toMatchObject({ xConnectionIds: [firstId], executionConfig: { xConnectionIds: [firstId] } }); + const run = await service.invokeJob(job.id, { prompt: "run", data: {} }); + const readSnapshot = async () => (await db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [tenantId, run.runId])).rows[0].execution_config; + const snapshot = await readSnapshot(); expect(snapshot.xConnectionIds).toEqual([firstId]); + await service.updateJob(job.id, { ...base, xConnectionIds: [nextId] }); + expect(await readSnapshot()).toEqual(snapshot); + await x.delete(firstId); + await expect(service.updateJob(job.id, { ...base, xConnectionIds: [firstId] })).rejects.toMatchObject({ status: 400 }); + await expect(service.createJob({ ...base, slug: `${slug}-foreign`, xConnectionIds: [foreignId] })).rejects.toMatchObject({ status: 400 }); + } finally { + await db.pool.query("DELETE FROM app.jobs WHERE tenant_id=$1 AND slug LIKE $2", [tenantId, `${slug}%`]); + await db.pool.query("DELETE FROM app.x_connections WHERE (tenant_id=$1 AND id=ANY($2::uuid[])) OR (tenant_id=$3 AND id=$4)", [tenantId, [firstId, nextId], otherTenant, foreignId]); + } + }); it("enforces tenant and scope boundaries, email verification, cookie expiry and session revocation", async () => { await expect(new ApiService(env, { ...auth, tenantId: otherTenant }).listJobs()).rejects.toMatchObject({ status: 401 }); await expect(new ApiService(env, { ...auth, scopes: ["runs:read"] }).listJobs()).rejects.toMatchObject({ status: 403 }); diff --git a/packages/api/test/run-identity-guest-helper.test.ts b/packages/api/test/run-identity-guest-helper.test.ts index 345978fb..a54141d7 100644 --- a/packages/api/test/run-identity-guest-helper.test.ts +++ b/packages/api/test/run-identity-guest-helper.test.ts @@ -32,12 +32,15 @@ describe("run-owned vendor identity guest helper", () => { const response = await fetch(`${origin}/providers/github/17/owner/repo.git/git-upload-pack`, {method: "POST", body: "pack-request", headers: {Authorization: "Bearer guest-supplied", Cookie: "factorize_session=private", "X-Factorize-Run-Id": "other-run", "Git-Protocol": "version=2"}}); expect(await response.text()).toBe("data: streamed\n\n"); expect(response.headers.has("Set-Cookie")).toBe(false); + const xId = "22222222-2222-4222-8222-222222222222"; + await (await fetch(`${origin}/x/${xId}/2/users/me?user.fields=id`, {headers: {Authorization: "Bearer guest-supplied"}})).body?.cancel(); await (await fetch(`${origin}/api/v1/runtime-context`)).body?.cancel(); await (await fetch(`${origin}/integrations`)).body?.cancel(); expect(forwarded).toMatchObject([ {url: `https://factorize.example.com/internal/run-proxy/${runId}/providers/github/17/owner/repo.git/git-upload-pack`, token: "Bearer header.claims.signature1", body: "pack-request", protocol: "version=2"}, - {url: "https://factorize.example.com/api/v1/runtime-context", token: "Bearer header.claims.signature2"}, - {url: "https://factorize.example.com/api/v1/runtime-integrations", token: "Bearer header.claims.signature3"}, + {url: `https://factorize.example.com/internal/run-proxy/${runId}/x/${xId}/2/users/me?user.fields=id`, token: "Bearer header.claims.signature2"}, + {url: "https://factorize.example.com/api/v1/runtime-context", token: "Bearer header.claims.signature3"}, + {url: "https://factorize.example.com/api/v1/runtime-integrations", token: "Bearer header.claims.signature4"}, ]); }); diff --git a/packages/api/test/vendor-run-auth.postgres.test.ts b/packages/api/test/vendor-run-auth.postgres.test.ts index 589bf141..065918d7 100644 --- a/packages/api/test/vendor-run-auth.postgres.test.ts +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -9,6 +9,7 @@ import { exeWifIntegrationNameFor, vmNameFor } from "../src/exe-vm-backend"; import { CredentialRepository } from "../src/postgres/credential-repository"; import { GitHubRepository } from "../src/postgres/github-repository"; import { ConnectionRepository } from "../src/postgres/connection-repository"; +import { XConnectionRepository } from "../src/postgres/x-connection-repository"; import worker from "../src/worker"; import { RunRepository } from "../src/postgres/run-repository"; import { decrypt, encrypt } from "../src/crypto"; @@ -217,6 +218,50 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker expect(outbound).toHaveLength(1); }); + it("forwards only the selected tenant X connection to fixed API v2 paths under its granted scopes", async () => { + const id = crypto.randomUUID(), foreignId = crypto.randomUUID(); + const selected = new XConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await selected.create({ id, name: "Selected X", clientId: "public-client", clientSecret: "private-client-secret", scopes: ["tweet.read", "users.read", "tweet.write", "offline.access"] }); + await selected.completeOAuth(id, { accessToken: "selected-x-access", refreshToken: "selected-x-refresh", expiresAt: new Date(Date.now()+3_600_000).toISOString(), accountId: "123", accountHandle: "selected_user", grantedScopes: ["tweet.read", "users.read", "tweet.write", "offline.access"] }); + const foreign = new XConnectionRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY); + await foreign.create({ id: foreignId, name: "Foreign X", clientId: "foreign-client", clientSecret: "foreign-secret", scopes: ["tweet.read", "users.read", "offline.access"] }); + await foreign.completeOAuth(foreignId, { accessToken: "foreign-x-access", refreshToken: "foreign-x-refresh", expiresAt: new Date(Date.now()+3_600_000).toISOString(), accountId: "456", accountHandle: "foreign_user", grantedScopes: ["tweet.read", "users.read", "offline.access"] }); + await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({xConnectionIds: [id]})]); + const vendorFetch = globalThis.fetch; + const sent: Array<{url: string; method: string; auth: string | null; body: string; guestHeader: string | null}> = []; let redirect = false; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const address = String(input); + if (address.startsWith(issuer)) return vendorFetch(input, init); + sent.push({url: address, method: init?.method ?? "GET", auth: (init!.headers as Headers).get("Authorization"), body: await new Response(init!.body).text(), guestHeader: (init!.headers as Headers).get("X-Guest-Marker")}); + return redirect ? new Response(null, {status: 302, headers: {Location: "https://untrusted.example/escape"}}) : new Response("upstream response", {status: 201, headers: {"X-Rate-Limit-Remaining": "7", "Retry-After": "2", "Set-Cookie": "private=secret"}}); + })); + const call = (connectionId = id, path = "/2/users/me?user.fields=id%2Cusername", method = "GET", body?: string) => worker.fetch(new Request(request(jwt, f.runId, `/internal/run-proxy/${f.runId}/x/${connectionId}${path}`), {method, body, headers: {"X-Guest-Marker": "preserved", Authorization: `Bearer ${jwt}`, "X-Factorize-Run-Id": f.runId}}), f.env, {waitUntil() {}} as any); + const read = await call(); + expect(read.status).toBe(201); expect(await read.text()).toBe("upstream response"); + expect(read.headers.get("X-Rate-Limit-Remaining")).toBe("7"); expect(read.headers.get("Retry-After")).toBe("2"); expect(read.headers.get("Set-Cookie")).toBeNull(); + expect(sent[0]).toEqual({url: "https://api.x.com/2/users/me?user.fields=id%2Cusername", method: "GET", auth: "Bearer selected-x-access", body: "", guestHeader: "preserved"}); + expect((await call(id, "/2/tweets", "POST", "{\"text\":\"hello\"}")).status).toBe(201); + expect(sent[1]).toMatchObject({url: "https://api.x.com/2/tweets", method: "POST", body: "{\"text\":\"hello\"}"}); + await f.db.pool.query("UPDATE app.x_connections SET granted_scopes=array_remove(granted_scopes,'tweet.write') WHERE tenant_id=$1 AND id=$2", [f.tenantId, id]); + expect((await call(id, "/2/tweets", "POST", "{\"text\":\"denied\"}")).status).toBe(403); + await f.db.pool.query("UPDATE app.x_connections SET granted_scopes=array_append(granted_scopes,'tweet.write') WHERE tenant_id=$1 AND id=$2", [f.tenantId, id]); + redirect = true; expect((await call()).status).toBe(502); redirect = false; + expect((await call(id, "/2/oauth2/token", "POST", "grant_type=refresh_token")).status).toBe(403); + expect((await call(foreignId)).status).toBe(403); + await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({xConnectionIds: [foreignId]})]); + expect((await call(foreignId)).status).toBe(403); // A corrupt cross-tenant snapshot still cannot resolve the other tenant's secret. + await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({xConnectionIds: [id]})]); + await selected.delete(id); + expect((await call()).status).toBe(403); + const discovery = await worker.fetch(request(jwt, f.runId, "/api/v1/runtime-integrations"), f.env, {waitUntil() {}} as any); + const metadata = await discovery.json() as any; + expect(metadata.xConnections).toEqual([{id, name: "Selected X", accountHandle: null, scopes: [], path: `/x/${id}/`, available: false}]); + expect(JSON.stringify(metadata)).not.toMatch(/selected-x-access|selected-x-refresh|private-client-secret|api\.x\.com/); + await f.db.pool.query("UPDATE app.job_runs SET state='stopping' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + expect((await call()).status).toBe(403); + expect(sent).toHaveLength(3); + }); + it("reuses selected GitHub and Linear connections for API and Git protocol requests", async () => { const installationId = 424242; const github = new GitHubRepository(f.db, f.tenantId); diff --git a/packages/api/test/x-connection-repository.postgres.test.ts b/packages/api/test/x-connection-repository.postgres.test.ts index 876577da..6c3c0c83 100644 --- a/packages/api/test/x-connection-repository.postgres.test.ts +++ b/packages/api/test/x-connection-repository.postgres.test.ts @@ -33,7 +33,10 @@ describe.skipIf(!url)("encrypted X app connections (PostgreSQL)", { timeout: 60_ await expect(repository.consumeOAuthAttempt(nonce)).resolves.toMatchObject({ userId: f.userId, connectionId: id, scopes: input.scopes, verifier }); await expect(repository.consumeOAuthAttempt(nonce)).resolves.toBeNull(); expect(await repository.delete(id)).toBe(true); - expect(await repository.get(id)).toBeNull(); + expect(await repository.get(id)).toMatchObject({ id, status: "revoked", accountId: null, accountHandle: null, grantedScopes: [] }); + await expect(repository.clientCredentials(id)).rejects.toThrow(); + expect(await repository.delete(id)).toBe(false); + await expect(repository.create({ ...input, name: "My X app" })).rejects.toMatchObject({ code: "23505" }); } finally { await f.cleanup(); } }); }); diff --git a/packages/app/src/features/jobs/editor-queries.ts b/packages/app/src/features/jobs/editor-queries.ts index 368f8533..28d7d537 100644 --- a/packages/app/src/features/jobs/editor-queries.ts +++ b/packages/app/src/features/jobs/editor-queries.ts @@ -2,10 +2,11 @@ import { queryOptions } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { messageOf } from "../auth/session"; export const providerConnectionsQuery = queryOptions({ queryKey: ["editor", "provider-connections"], queryFn: async ({ signal }) => { - const [github, integrations] = await Promise.all([api.GET("/api/v1/github-installations", { signal }), api.GET("/api/v1/integrations", { signal })]); + const [github, integrations, x] = await Promise.all([api.GET("/api/v1/github-installations", { signal }), api.GET("/api/v1/integrations", { signal }), api.GET("/api/v1/x/connections", { signal })]); if (!github.data || github.error) throw new Error(messageOf(github.error)); if (!integrations.data || integrations.error) throw new Error(messageOf(integrations.error)); - return { githubInstallations: github.data, linear: integrations.data.linear }; + if (!x.data || x.error) throw new Error(messageOf(x.error)); + return { githubInstallations: github.data, linear: integrations.data.linear, xConnections: x.data.connections }; }, staleTime: 60_000 }); export const targetsQuery = queryOptions({ queryKey: ["editor", "integrations"], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/integrations", { signal }); diff --git a/packages/app/src/features/jobs/editor-state.ts b/packages/app/src/features/jobs/editor-state.ts index c192e8ad..7595f49f 100644 --- a/packages/app/src/features/jobs/editor-state.ts +++ b/packages/app/src/features/jobs/editor-state.ts @@ -10,7 +10,7 @@ export function canonicalizeVmImage(value: string): string { return `${name.toLowerCase()}${tag}${digest}`; } export function editableJob(job: Job): JobInput { - return { modelAccountId: job.modelAccountId, modelAccess: job.modelAccess, portableIntegrationIds: job.portableIntegrationIds, githubInstallationIds: job.githubInstallationIds, linearConnectionId: job.linearConnectionId, runScopes: job.runScopes ?? [...defaultRunScopes], executionType: job.executionType ?? "agent", projectId: job.projectId, name: job.name, description: job.description ?? "", slug: job.slug, promptTemplate: job.promptTemplate, script: job.script ?? "", runNameTemplate: job.runNameTemplate, executionConfigId: job.executionConfigId, concurrencyLimit: job.concurrencyLimit, tags: job.tags ?? [], vmImage: job.executionConfig?.image ?? "", model: job.model, effort: job.effort ?? "", skillIds: job.skills?.map(skill => skill.id) ?? [], triggers: job.triggers.map(trigger => { + return { modelAccountId: job.modelAccountId, modelAccess: job.modelAccess, portableIntegrationIds: job.portableIntegrationIds, githubInstallationIds: job.githubInstallationIds, linearConnectionId: job.linearConnectionId, xConnectionIds: job.xConnectionIds ?? [], runScopes: job.runScopes ?? [...defaultRunScopes], executionType: job.executionType ?? "agent", projectId: job.projectId, name: job.name, description: job.description ?? "", slug: job.slug, promptTemplate: job.promptTemplate, script: job.script ?? "", runNameTemplate: job.runNameTemplate, executionConfigId: job.executionConfigId, concurrencyLimit: job.concurrencyLimit, tags: job.tags ?? [], vmImage: job.executionConfig?.image ?? "", model: job.model, effort: job.effort ?? "", skillIds: job.skills?.map(skill => skill.id) ?? [], triggers: job.triggers.map(trigger => { const { id, slug, kind, enabled } = trigger; const config = trigger.kind === "webhook" ? Object.fromEntries(Object.entries(trigger.config).filter(([key]) => !["destination", "secretConfigured"].includes(key))) : trigger.config; return { id, slug, kind, enabled, config } as Trigger; diff --git a/packages/app/src/features/jobs/editor.tsx b/packages/app/src/features/jobs/editor.tsx index e01cadf6..ebeb75ca 100644 --- a/packages/app/src/features/jobs/editor.tsx +++ b/packages/app/src/features/jobs/editor.tsx @@ -131,6 +131,9 @@ function EditorForm({ initial, section }: { initial?: Job; section?: string }) { {!providerConnections.isPending && providerConnections.data?.githubInstallations.filter(item => item.state === "active").length === 0 &&

No active GitHub installations are connected.

} {providerConnections.data?.linear ? :

No Linear connection is connected.

} {!providerConnections.isPending&&!providerConnections.data?.linear&&draft.linearConnectionId==="linear"&&} + {providerConnections.data?.xConnections.filter(item => item.status === "connected").map(item => )} + {!providerConnections.isPending&&(draft.xConnectionIds ?? []).filter(id => !providerConnections.data?.xConnections.some(item => item.id === id && item.status === "connected")).map(id => )} + {!providerConnections.isPending && providerConnections.data?.xConnections.length === 0 &&

No X connections are configured. Add one in Settings → Integrations.

} {target?.kind !== "amp" && !isFly &&
{draft.vmImage &&

{verification.data?.status === "succeeded" && activeVerificationId ? `Verified: ${verification.data?.phase}` : verification.data?.status === "failed" && activeVerificationId ? `${verification.data?.errorKind}: ${verification.data?.error}` : verification.data?.status === "cleanup_failed" && activeVerificationId ? `Cleanup unresolved: ${verification.data?.error}` : activeVerificationId ? `Verification ${verification.data?.status}: ${verification.data?.phase}` : "Not verified"}

}{draft.vmImage && }{verifyImage.error &&

{verifyImage.error.message}

}
} {(draft.executionType ?? "agent") === "agent" && <> diff --git a/packages/app/src/features/settings/x-connections.tsx b/packages/app/src/features/settings/x-connections.tsx index 5dabcf03..c668e95f 100644 --- a/packages/app/src/features/settings/x-connections.tsx +++ b/packages/app/src/features/settings/x-connections.tsx @@ -73,9 +73,9 @@ export function XConnections() { {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" : "Setup incomplete"}
+

{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 !== "connected" && } + {connection.status === "revoked" ?

Disconnected. Create a new connection to use X again.

: connection.status !== "connected" && }
)}

Set up your X developer app

    diff --git a/packages/app/test/editor.browser.test.mjs b/packages/app/test/editor.browser.test.mjs index 5fe771f9..b1b26913 100644 --- a/packages/app/test/editor.browser.test.mjs +++ b/packages/app/test/editor.browser.test.mjs @@ -16,6 +16,8 @@ async function setup(options) { await page.route("**/api/v1/runs?**", route => route.fulfill({ json: { items: [], nextCursor: null } })); page.setDefaultTimeout(30000); 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" } })); await page.route("**/api/v1/integrations", route => route.fulfill({ json: { linear: null, clickup: null, exe: null, exeConnections: [{ connectionId: "vm", agentKind: "codex", tags: [], models: ["gpt-6"] }], ampConnections: [], cloudflareTail: { count: 0, installations: [] } } })); + await page.route("**/api/v1/github-installations", route => route.fulfill({ json: [] })); + await page.route("**/api/v1/x/connections", route => route.fulfill({ json: { connections: [] } })); await page.route("**/api/v1/trigger-contexts", route => route.fulfill({ json: { manual: [{ path: "prompt", type: "string", description: "Manual prompt" }] } })); await page.route("**/api/v1/job-trigger-availability", route => route.fulfill({ json: { manual: true, schedule: true, jobLifecycle: true, linear: true, clickup: true, github: true, cloudflareTail: true } })); return { context, page }; @@ -92,6 +94,19 @@ test("run permission scopes autosave and survive reload", async () => { assert.deepEqual(saved.runScopes, ["jobs:read", "runs:read"]); await context.close(); }); +test("job editor selects a connected X account and preserves its safe scopes in the job write", async () => { + const { context, page } = await setup(); + const xId = "00000000-0000-4000-8000-000000000099"; let current = structuredClone(initial), saved; + await page.route(`**/api/v1/jobs/${id}`, route => { if (route.request().method() === "GET") return route.fulfill({ json: current }); saved = route.request().postDataJSON(); current = { ...current, ...saved }; return route.fulfill({ json: current }); }); + await page.route("**/api/v1/x/connections", route => route.fulfill({ json: { connections: [{ id: xId, name: "Release account", clientId: "public-client", scopes: ["tweet.read", "users.read", "offline.access"], accountId: "123", accountHandle: "release_bot", grantedScopes: ["tweet.read", "users.read", "offline.access"], status: "connected", createdAt: "2026-11-01T00:00:00.000Z", updatedAt: "2026-11-01T00:00:00.000Z" }] } })); + await page.goto(origin + `/jobs/${id}/settings/execution`); + await page.getByLabel(/X · Release account \(@release_bot\)/).check(); + await page.getByRole("status").filter({ hasText: "Job settings saved." }).waitFor(); + assert.deepEqual(saved.xConnectionIds, [xId]); + await page.reload(); + assert.equal(await page.getByLabel(/X · Release account \(@release_bot\)/).isChecked(), true); + await context.close(); +}); test("manual invocation permissions include the current job and jobs in the same project", async () => { const { context, page } = await setup(); const projectA = "00000000-0000-4000-8000-000000000020", destination = "00000000-0000-4000-8000-000000000024"; diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index de44121d..963a07e9 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1711,6 +1711,13 @@ components: - type: string const: linear - type: "null" + xConnectionIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ required: - name - slug @@ -1880,6 +1887,7 @@ paths: - pending - connected - reconnect_required + - revoked createdAt: type: string updatedAt: @@ -1968,6 +1976,7 @@ paths: - pending - connected - reconnect_required + - revoked createdAt: type: string updatedAt: @@ -2076,7 +2085,7 @@ paths: delete: summary: Delete an X connection description: |- - Requires an interactive owner session. Deletes the encrypted client credential and connection metadata. + Requires an interactive owner session. Immediately clears the encrypted credential and revokes the connection. A secret-free tombstone prevents old run snapshots from being revived if an identifier is reused. Requires the integrations:write scope. @@ -8837,6 +8846,12 @@ paths: - type: string const: linear - type: "null" + xConnectionIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -9680,6 +9695,12 @@ paths: - type: string const: linear - type: "null" + xConnectionIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -10286,6 +10307,12 @@ paths: - type: string const: linear - type: "null" + xConnectionIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -11653,7 +11680,7 @@ paths: get: summary: Discover this run's selected integration endpoints description: |- - Requires vendor-verified run identity. Returns only snapshotted selections and current availability, without origins or credentials. Selection authorization is independent of the run's Factorize API scopes. + Requires vendor-verified run identity. Returns only snapshotted selections, safe connection metadata, X OAuth scopes, and current availability, without origins or credentials. X connections use /x/{connectionId}/ for supported API v2 resources; each resource is checked against selected and granted OAuth scopes. Selection authorization is independent of the run's Factorize API scopes. Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: @@ -11691,6 +11718,36 @@ paths: - path - available additionalProperties: false + xConnections: + default: [] + type: array + items: + type: object + properties: + id: + type: string + name: + type: string + accountHandle: + type: + - string + - "null" + scopes: + type: array + items: + type: string + path: + type: string + available: + type: boolean + required: + - id + - name + - accountHandle + - scopes + - path + - available + additionalProperties: false providers: type: object properties: @@ -11746,6 +11803,7 @@ paths: required: - kind - integrations + - xConnections - providers additionalProperties: false "400": @@ -12186,6 +12244,12 @@ paths: - type: string const: linear - type: "null" + xConnectionIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -12805,6 +12869,12 @@ paths: - type: string const: linear - type: "null" + xConnectionIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -13707,6 +13777,13 @@ paths: - type: string const: linear - type: "null" + xConnectionIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ expectedUpdatedAt: type: string format: date-time From 085e0771cb6839c6f12d5166e572900f8034eaa7 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 21:20:39 +0000 Subject: [PATCH 7/9] Handle revoked X run credentials safely --- packages/api/src/agent-api.ts | 6 ++++-- packages/api/test/loading.postgres.test.ts | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index c3e493e5..d93dffa8 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -133,8 +133,10 @@ export class AgentApiService { 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), credentials = await repository.clientCredentials(connectionId); - if (!connection || connection.status !== "connected" || !credentials?.accessToken || !credentials.expiresAt || Date.parse(credentials.expiresAt) <= Date.now()) throw forbidden(); + const connection = await repository.get(connectionId); + if (!connection || connection.status !== "connected") throw forbidden(); + const credentials = await repository.clientCredentials(connectionId); + if (!credentials?.accessToken || !credentials.expiresAt || Date.parse(credentials.expiresAt) <= Date.now()) throw forbidden(); if (!connection.scopes.includes(required) || !connection.grantedScopes.includes(required)) throw new AgentApiError(403, "insufficient_scope", `This X connection does not grant ${required}.`); const currentIdentity = await this.identity(); const current = await repository.get(connectionId); diff --git a/packages/api/test/loading.postgres.test.ts b/packages/api/test/loading.postgres.test.ts index 56fae3c0..ab382bc8 100644 --- a/packages/api/test/loading.postgres.test.ts +++ b/packages/api/test/loading.postgres.test.ts @@ -197,7 +197,7 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => { await createConnected(x, firstId, "First X"); await createConnected(x, nextId, "Next X"); await createConnected(foreign, foreignId, "Foreign X"); await expect(service.createJob({ ...base, xConnectionIds: [foreignId] })).rejects.toMatchObject({ status: 400 }); const job = await service.createJob({ ...base, xConnectionIds: [firstId] }); - expect(job).toMatchObject({ xConnectionIds: [firstId], executionConfig: { xConnectionIds: [firstId] } }); + expect(job).toMatchObject({ xConnectionIds: [firstId] }); const run = await service.invokeJob(job.id, { prompt: "run", data: {} }); const readSnapshot = async () => (await db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [tenantId, run.runId])).rows[0].execution_config; const snapshot = await readSnapshot(); expect(snapshot.xConnectionIds).toEqual([firstId]); From b4fba745e3c75e10855e7d3de382417cbd0bad83 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 21:49:59 +0000 Subject: [PATCH 8/9] Serialize X refresh token rotation --- packages/api/src/agent-api.ts | 27 ++++++++-- packages/api/src/flow-service.ts | 14 ++++- .../src/postgres/x-connection-repository.ts | 54 +++++++++++++++++-- .../x-connection-repository.postgres.test.ts | 48 ++++++++++++++++- .../app/test/x-connections.browser.test.mjs | 26 +++++++++ 5 files changed, 160 insertions(+), 9 deletions(-) diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index d93dffa8..50de865e 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -6,7 +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 } from "./postgres/x-connection-repository"; +import { XConnectionRepository, XReconnectRequiredError } from "./postgres/x-connection-repository"; import type { z } from "zod"; export class AgentApiError extends Error { @@ -135,13 +135,32 @@ export class AgentApiService { 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(); - const credentials = await repository.clientCredentials(connectionId); - if (!credentials?.accessToken || !credentials.expiresAt || Date.parse(credentials.expiresAt) <= Date.now()) 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: credentials.accessToken }); } + 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, signal?: AbortSignal) { diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index c0d577e2..afd54dc0 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -632,7 +632,19 @@ export class ApiService { } async deleteXConnection(id: string) { await this.authorizeOwnerSession("integrations:write"); - if (!await this.xConnections().delete(id)) throw new ServiceError(404, "not_found", "X connection not found."); + const credentials = await this.xConnections().disconnect(id); + if (!credentials) throw new ServiceError(404, "not_found", "X connection not found."); + // Local revocation is committed before contacting X. Upstream availability + // must never keep a disconnected run grant usable. + for (const token of [credentials.refreshToken, credentials.accessToken].filter((value): value is string => Boolean(value))) { + try { + await fetch("https://api.x.com/2/oauth2/revoke", { + method: "POST", redirect: "error", signal: AbortSignal.timeout(5_000), + headers: { Authorization: `Basic ${btoa(`${credentials.clientId}:${credentials.clientSecret}`)}`, "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ token, token_type_hint: token === credentials.refreshToken ? "refresh_token" : "access_token" }), + }); + } catch { /* Best effort after local run access has already been revoked. */ } + } return { id, deleted: true as const }; } async authorizeXConnection(id: string) { diff --git a/packages/api/src/postgres/x-connection-repository.ts b/packages/api/src/postgres/x-connection-repository.ts index 67c9f7f7..5179a1a8 100644 --- a/packages/api/src/postgres/x-connection-repository.ts +++ b/packages/api/src/postgres/x-connection-repository.ts @@ -14,6 +14,10 @@ export type XConnectionMetadata = { updatedAt: string; }; +export class XReconnectRequiredError extends Error { + constructor() { super("X authorization requires reconnection"); } +} + type XConnectionRow = XConnectionMetadata & { encrypted_secret: string }; /** Tenant-scoped X app credentials. Client secrets and later OAuth tokens share @@ -61,6 +65,52 @@ export class XConnectionRepository { return { clientId: row.client_id, clientSecret: secret.clientSecret, scopes: row.scopes, accessToken: typeof secret.accessToken === "string" ? secret.accessToken : undefined, refreshToken: typeof secret.refreshToken === "string" ? secret.refreshToken : undefined, expiresAt: typeof secret.expiresAt === "string" ? secret.expiresAt : undefined }; } + /** Refresh under the connection row lock so concurrent requests share one + * rotated refresh token. Disconnect and OAuth completion use the same row, + * so neither can be overwritten by a late refresh. */ + async accessToken(id: string, refresh: (input: { clientId: string; clientSecret: string; refreshToken: string }) => Promise<{ accessToken: string; refreshToken: string; expiresAt: string }>): Promise { + const result = await this.database.transaction(async client => { + const { rows } = await client.query<{ client_id: string; encrypted_secret: string; status: string }>( + "SELECT client_id,encrypted_secret,status FROM app.x_connections WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id]); + const row = rows[0]; + if (!row || row.status !== "connected") return { accessToken: null }; + const stored = JSON.parse(await decrypt(row.encrypted_secret, this.encryptionKey)) as { clientSecret?: string; accessToken?: string; refreshToken?: string; expiresAt?: string }; + if (stored.accessToken && stored.expiresAt && Date.parse(stored.expiresAt) > Date.now() + 60_000) return { accessToken: stored.accessToken }; + if (!stored.clientSecret || !stored.refreshToken) { + await client.query("UPDATE app.x_connections SET status='reconnect_required',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status='connected'", [this.tenantId, id]); + return { reconnectRequired: true as const }; + } + let rotated: { accessToken: string; refreshToken: string; expiresAt: string }; + try { rotated = await refresh({ clientId: row.client_id, clientSecret: stored.clientSecret, refreshToken: stored.refreshToken }); } + catch (error) { + if (!(error instanceof XReconnectRequiredError)) throw error; + await client.query("UPDATE app.x_connections SET status='reconnect_required',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status='connected'", [this.tenantId, id]); + return { reconnectRequired: true as const }; + } + const encrypted = await encrypt(JSON.stringify({ clientSecret: stored.clientSecret, ...rotated }), this.encryptionKey); + const updated = await client.query("UPDATE app.x_connections SET encrypted_secret=$3,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status='connected'", [this.tenantId, id, encrypted]); + if (!updated.rowCount) return { accessToken: null }; + return { accessToken: rotated.accessToken }; + }); + if (result?.reconnectRequired) throw new XReconnectRequiredError(); + return result.accessToken; + } + + /** Revoke locally first and return the old upstream credentials for a + * best-effort X revocation request after the transaction commits. */ + async disconnect(id: string): Promise<{ clientId: string; clientSecret: string; accessToken?: string; refreshToken?: string } | null> { + return this.database.transaction(async client => { + const { rows } = await client.query<{ encrypted_secret: string; client_id: string; status: string }>( + "SELECT encrypted_secret,client_id,status FROM app.x_connections WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id]); + const row = rows[0]; + if (!row || row.status === "revoked") return null; + const stored = JSON.parse(await decrypt(row.encrypted_secret, this.encryptionKey)) as { clientSecret?: string; accessToken?: string; refreshToken?: string }; + const tombstone = await encrypt(JSON.stringify({}), this.encryptionKey); + await client.query("UPDATE app.x_connections SET status='revoked',encrypted_secret=$3,account_id=NULL,account_handle=NULL,granted_scopes='{}',updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, id, tombstone]); + return stored.clientSecret ? { clientId: row.client_id, clientSecret: stored.clientSecret, accessToken: stored.accessToken, refreshToken: stored.refreshToken } : null; + }); + } + async createOAuthAttempt(input: { nonce: string; userId: string; sessionVersion: number; connectionId: string; scopes: string[]; verifier: string; expiresAt: Date }): Promise { const encryptedVerifier = await encrypt(input.verifier, this.encryptionKey); const result = await this.database.pool.query(`INSERT INTO app.x_oauth_attempts(tenant_id,nonce,user_id,session_version,connection_id,scopes,encrypted_verifier,expires_at) @@ -93,9 +143,7 @@ export class XConnectionRepository { } async delete(id: string): Promise { - const tombstone = await encrypt(JSON.stringify({}), this.encryptionKey); - const { rowCount } = await this.database.pool.query("UPDATE app.x_connections SET status='revoked',encrypted_secret=$3,account_id=NULL,account_handle=NULL,granted_scopes='{}',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status<>'revoked'", [this.tenantId, id, tombstone]); - return (rowCount ?? 0) > 0; + return Boolean(await this.disconnect(id)); } } diff --git a/packages/api/test/x-connection-repository.postgres.test.ts b/packages/api/test/x-connection-repository.postgres.test.ts index 6c3c0c83..80193d3d 100644 --- a/packages/api/test/x-connection-repository.postgres.test.ts +++ b/packages/api/test/x-connection-repository.postgres.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; import { decrypt } from "../src/crypto"; -import { XConnectionRepository } from "../src/postgres/x-connection-repository"; +import { XConnectionRepository, XReconnectRequiredError } from "../src/postgres/x-connection-repository"; import { loadingFixture } from "./helpers/loading-fixture"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); @@ -39,4 +39,50 @@ describe.skipIf(!url)("encrypted X app connections (PostgreSQL)", { timeout: 60_ await expect(repository.create({ ...input, name: "My X app" })).rejects.toMatchObject({ code: "23505" }); } finally { await f.cleanup(); } }); + + it("serializes concurrent refresh rotation and persists only the newest encrypted token pair", async () => { + const f = await loadingFixture(url!); + try { + const id = crypto.randomUUID(), repository = new XConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await repository.create({ id, name: "Rotating X", clientId: "client", clientSecret: "private", scopes: ["tweet.read", "users.read", "offline.access"] }); + await repository.completeOAuth(id, { accessToken: "expired-access", refreshToken: "refresh-v1", expiresAt: new Date(Date.now() - 1_000).toISOString(), accountId: "123", accountHandle: "user", grantedScopes: ["tweet.read", "users.read", "offline.access"] }); + let release!: () => void, started!: () => void; + const waiting = new Promise(resolve => { release = resolve; }), began = new Promise(resolve => { started = resolve; }); + const refresh = vi.fn(async () => { started(); await waiting; return { accessToken: "access-v2", refreshToken: "refresh-v2", expiresAt: new Date(Date.now() + 3_600_000).toISOString() }; }); + const first = repository.accessToken(id, refresh), second = repository.accessToken(id, refresh); + await began; + await new Promise(resolve => setTimeout(resolve, 20)); + expect(refresh).toHaveBeenCalledOnce(); + release(); + await expect(Promise.all([first, second])).resolves.toEqual(["access-v2", "access-v2"]); + expect(refresh).toHaveBeenCalledOnce(); + await expect(repository.clientCredentials(id)).resolves.toMatchObject({ accessToken: "access-v2", refreshToken: "refresh-v2" }); + } finally { await f.cleanup(); } + }); + + it("marks invalid_grant terminal, preserves transient failures, and disconnect wins over an in-flight refresh", async () => { + const f = await loadingFixture(url!); + try { + const id = crypto.randomUUID(), repository = new XConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await repository.create({ id, name: "Race X", clientId: "client", clientSecret: "private", scopes: ["tweet.read", "users.read", "offline.access"] }); + await repository.completeOAuth(id, { accessToken: "expired-access", refreshToken: "refresh-v1", expiresAt: new Date(Date.now() - 1_000).toISOString(), accountId: "123", accountHandle: "user", grantedScopes: ["tweet.read", "users.read", "offline.access"] }); + await expect(repository.accessToken(id, async () => { throw new Error("temporary 503"); })).rejects.toThrow("temporary 503"); + expect(await repository.get(id)).toMatchObject({ status: "connected" }); + await expect(repository.accessToken(id, async () => { throw new XReconnectRequiredError(); })).rejects.toBeInstanceOf(XReconnectRequiredError); + expect(await repository.get(id)).toMatchObject({ status: "reconnect_required" }); + + await repository.completeOAuth(id, { accessToken: "expired-access", refreshToken: "refresh-v1", expiresAt: new Date(Date.now() - 1_000).toISOString(), accountId: "123", accountHandle: "user", grantedScopes: ["tweet.read", "users.read", "offline.access"] }); + let release!: () => void, started!: () => void; + const waiting = new Promise(resolve => { release = resolve; }), began = new Promise(resolve => { started = resolve; }); + const refresh = repository.accessToken(id, async () => { started(); await waiting; return { accessToken: "late-access", refreshToken: "late-refresh", expiresAt: new Date(Date.now() + 3_600_000).toISOString() }; }); + await began; + const disconnect = repository.disconnect(id); + release(); + expect(await refresh).toBe("late-access"); + expect(await disconnect).toMatchObject({ accessToken: "late-access", refreshToken: "late-refresh" }); + expect(await repository.get(id)).toMatchObject({ status: "revoked", accountId: null, grantedScopes: [] }); + expect(await repository.accessToken(id, async () => { throw new Error("must not refresh revoked connection"); })).toBeNull(); + await expect(repository.clientCredentials(id)).rejects.toThrow(); + } finally { await f.cleanup(); } + }); }); diff --git a/packages/app/test/x-connections.browser.test.mjs b/packages/app/test/x-connections.browser.test.mjs index 70eb6784..dc8dd809 100644 --- a/packages/app/test/x-connections.browser.test.mjs +++ b/packages/app/test/x-connections.browser.test.mjs @@ -61,3 +61,29 @@ test("X settings guides app callback setup, validated permissions, and starts ow await page.getByText(/Granted permissions:.*tweet.write/).waitFor(); await context.close(); }); + +test("X settings explains terminal authorization failures and offers an explicit reconnect", async () => { + const context = await browser.newContext(), page = await context.newPage(); + const connectionId = "7d2edbbf-aac8-4f20-9b70-818bc5c03294"; + let authorizeCalls = 0; + 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/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: [] }); + if (path === "/api/v1/model-accounts") return route.fulfill({ json: { accounts: [], revision: 0 } }); + if (path === "/api/v1/integrations/bearer") return route.fulfill({ json: { integrations: [], revision: 0 } }); + if (path === "/api/v1/integration-api-policies") return route.fulfill({ json: { integrations: [] } }); + if (path === "/api/v1/x/connections") return route.fulfill({ json: { connections: [{ id: connectionId, name: "Work account", clientId: "client-123", scopes: ["tweet.read", "users.read", "offline.access"], accountId: "123", accountHandle: "work_user", grantedScopes: ["tweet.read", "users.read", "offline.access"], status: "reconnect_required", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }] } }); + if (path.endsWith("/authorize")) { authorizeCalls++; return route.fulfill({ json: { authorizationUrl: "https://x.com/i/oauth2/authorize?state=fresh" } }); } + return route.fulfill({ json: {} }); + }); + 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.getByRole("button", { name: "Connect X", exact: true }).click(); + await page.waitForURL("https://x.com/i/oauth2/authorize**"); + assert.equal(authorizeCalls, 1); + await context.close(); +}); From 97bf3e56bae1c5329df36531a11717498e7ca2fc Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 22:05:41 +0000 Subject: [PATCH 9/9] GEN-2923 test and replace X connection credentials --- packages/api-client/src/schema.d.ts | 139 +++++++++++++ .../migrations/0058_x_credential_versions.sql | 5 + packages/api/src/api-contract.ts | 12 ++ packages/api/src/flow-service.ts | 31 +++ packages/api/src/postgres/schema.ts | 2 + .../src/postgres/x-connection-repository.ts | 61 ++++-- packages/api/src/x-oauth-callback.ts | 9 +- .../api/test/x-oauth-flow.postgres.test.ts | 68 ++++++ .../src/features/settings/x-connections.tsx | 27 +++ .../app/test/x-connections.browser.test.mjs | 34 +++ packages/docs/openapi.yaml | 193 ++++++++++++++++++ 11 files changed, 564 insertions(+), 17 deletions(-) create mode 100644 packages/api/migrations/0058_x_credential_versions.sql diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 42301786..21842e3d 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -80,6 +80,54 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/x/connections/{connectionId}/test": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Test an X connection + * @description Requires an interactive owner session. Performs a non-mutating GET to X /2/users/me using the saved access token. Returns only a safe status and the already stored account handle; it never returns tokens, credentials, or upstream error bodies. The verification read may incur X API usage charges. + * + * Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_x_connections_connectionId_test"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/x/connections/{connectionId}/credentials": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Replace X app credentials + * @description Requires an interactive owner session. Replaces the encrypted client credentials, invalidates saved access and refresh tokens and pending OAuth attempts, preserves the existing account identity binding, and requires reauthorization. Reauthorization cannot switch the connection to a different X account; create a new connection for another account. Existing run selections remain unavailable until authorization succeeds. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_x_connections_connectionId_credentials"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/model-accounts": { parameters: { query?: never; @@ -3243,6 +3291,97 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + post_api_v1_x_connections_connectionId_test: { + parameters: { + query?: never; + header?: never; + path: { + connectionId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": Record; + }; + }; + responses: { + /** @description Safe connection test result */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @enum {string} */ + status: "connected" | "failed" | "reconnect_required"; + accountHandle: string | null; + message: 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"]; + }; + }; + put_api_v1_x_connections_connectionId_credentials: { + parameters: { + query?: never; + header?: never; + path: { + connectionId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + clientId: string; + clientSecret: string; + }; + }; + }; + responses: { + /** @description Updated safe connection metadata */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + clientId: string; + scopes: string[]; + accountId: string | null; + accountHandle: string | null; + grantedScopes: string[]; + /** @enum {string} */ + status: "pending" | "connected" | "reconnect_required" | "revoked"; + createdAt: string; + updatedAt: 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"]; + }; + }; get_api_v1_model_accounts: { parameters: { query?: never; diff --git a/packages/api/migrations/0058_x_credential_versions.sql b/packages/api/migrations/0058_x_credential_versions.sql new file mode 100644 index 00000000..7c260707 --- /dev/null +++ b/packages/api/migrations/0058_x_credential_versions.sql @@ -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; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 80bd8568..b962a44e 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -152,6 +152,8 @@ const xConnectionCreate = z.object({ }).strict(); const xConnectionList = z.object({ connections: z.array(xConnectionMetadata) }); const xAuthorizationStart = z.object({ authorizationUrl: z.url() }); +const xConnectionTest = z.object({ status: z.enum(["connected", "failed", "reconnect_required"]), accountHandle: z.string().nullable(), message: z.string() }); +const xConnectionCredentialReplacement = z.object({ clientId: z.string().trim().min(1).max(256), clientSecret: z.string().min(1).max(4096).regex(/^[^\r\n]+$/).meta({ writeOnly: true }) }).strict(); const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonnegative(), duplicate: z.boolean() }); const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() }); @@ -255,6 +257,16 @@ export const API_ROUTES: RouteContract[] = [ const started = await service.authorizeXConnection(params.connectionId); return Response.json({ authorizationUrl: started.authorizationUrl }, { headers: { "Set-Cookie": `factorize_x_oauth_state=${started.stateCookie}; HttpOnly; Secure; SameSite=Lax; Path=/oauth/x/callback; Max-Age=600` } }); }, { body: z.object({}).strict(), maxBodyBytes: 1024, ownerSession: true, parameters: z.object({ connectionId: z.uuid() }) }), + route("POST", "/api/v1/x/connections/{connectionId}/test", "integrations:read", { + summary: "Test an X connection", + description: "Requires an interactive owner session. Performs a non-mutating GET to X /2/users/me using the saved access token. Returns only a safe status and the already stored account handle; it never returns tokens, credentials, or upstream error bodies. The verification read may incur X API usage charges.", + responses: { "200": { description: "Safe connection test result", content: { "application/json": { schema: jsonSchema(xConnectionTest, "output") } } } }, + }, (service, { params }) => service.testXConnection(params.connectionId), { body: z.object({}).strict(), maxBodyBytes: 1024, ownerSession: true, parameters: z.object({ connectionId: z.uuid() }) }), + route("PUT", "/api/v1/x/connections/{connectionId}/credentials", "integrations:write", { + summary: "Replace X app credentials", + description: "Requires an interactive owner session. Replaces the encrypted client credentials, invalidates saved access and refresh tokens and pending OAuth attempts, preserves the existing account identity binding, and requires reauthorization. Reauthorization cannot switch the connection to a different X account; create a new connection for another account. Existing run selections remain unavailable until authorization succeeds.", + responses: { "200": { description: "Updated safe connection metadata", content: { "application/json": { schema: jsonSchema(xConnectionMetadata, "output") } } } }, + }, (service, { params, body }) => service.replaceXConnectionCredentials(params.connectionId, body), { body: xConnectionCredentialReplacement, maxBodyBytes: 8192, ownerSession: true, parameters: z.object({ connectionId: z.uuid() }) }), route("GET", "/api/v1/model-accounts", "integrations:read", { summary: "List model accounts available to the owner", description: "Requires an interactive owner browser session. Returns account metadata and the collection revision only; encrypted account caches and credentials are never returned.", diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index afd54dc0..84f59956 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -647,6 +647,37 @@ export class ApiService { } return { id, deleted: true as const }; } + async testXConnection(id: string) { + await this.authorizeOwnerSession("integrations:read"); + const repository = this.xConnections(), connection = await repository.get(id); + if (!connection || connection.status === "revoked") throw new ServiceError(404, "not_found", "X connection not found."); + if (connection.status !== "connected") return { status: "reconnect_required" as const, accountHandle: connection.accountHandle, message: "Reconnect this X connection before testing it." }; + const credentials = await repository.clientCredentials(id); + if (!credentials?.accessToken || !credentials.expiresAt || Date.parse(credentials.expiresAt) <= Date.now()) + return { status: "reconnect_required" as const, accountHandle: connection.accountHandle, message: "Reconnect this X connection before testing it." }; + try { + const response = await fetch("https://api.x.com/2/users/me?user.fields=id%2Cusername", { + method: "GET", redirect: "error", signal: AbortSignal.timeout(10_000), + headers: { Authorization: `Bearer ${credentials.accessToken}`, Accept: "application/json" }, + }); + if (response.status === 401) return { status: "reconnect_required" as const, accountHandle: connection.accountHandle, message: "X rejected this authorization. Reconnect the connection." }; + if (!response.ok) return { status: "failed" as const, accountHandle: connection.accountHandle, message: "X could not verify the connection. Try again later." }; + const me = await response.json() as { data?: { id?: unknown; username?: unknown } }; + if (me.data?.id !== connection.accountId || me.data?.username !== connection.accountHandle) + return { status: "failed" as const, accountHandle: connection.accountHandle, message: "X returned an account that does not match this connection." }; + return { status: "connected" as const, accountHandle: connection.accountHandle, message: "X connection verified." }; + } catch { + return { status: "failed" as const, accountHandle: connection.accountHandle, message: "X could not verify the connection. Try again later." }; + } + } + async replaceXConnectionCredentials(id: string, input: { clientId: string; clientSecret: string }) { + await this.authorizeOwnerSession("integrations:write"); + if (!/^[A-Za-z0-9_-]{1,256}$/.test(input.clientId)) throw new ServiceError(400, "invalid_request", "Enter a valid X OAuth 2.0 client ID."); + if (!input.clientSecret.trim() || input.clientSecret.length > 4096 || /[\r\n]/.test(input.clientSecret)) throw new ServiceError(400, "invalid_request", "Enter a valid X OAuth client secret."); + const updated = await this.xConnections().replaceClientCredentials(id, { clientId: input.clientId.trim(), clientSecret: input.clientSecret }); + if (!updated) throw new ServiceError(404, "not_found", "X connection not found."); + return updated; + } async authorizeXConnection(id: string) { await this.authorizeOwnerSession("integrations:write"); const repository = this.xConnections(), connection = await repository.get(id); diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index a161e3cc..f45f0f48 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -52,6 +52,7 @@ export const xConnections = app.table("x_connections", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), name: text("name").notNull(), clientId: text("client_id").notNull(), scopes: text("scopes").array().notNull(), encryptedSecret: text("encrypted_secret").notNull(), + credentialVersion: integer("credential_version").notNull().default(1), accountId: text("account_id"), accountHandle: text("account_handle"), grantedScopes: text("granted_scopes").array().notNull().default(sql`'{}'::text[]`), status: text("status").$type<"pending" | "connected" | "reconnect_required">().notNull().default("pending"), createdAt: createdAt(), updatedAt: updatedAt(), @@ -59,6 +60,7 @@ export const xConnections = app.table("x_connections", { export const xOAuthAttempts = app.table("x_oauth_attempts", { tenantId: uuid("tenant_id").notNull(), nonce: text("nonce").notNull(), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), connectionId: uuid("connection_id").notNull(), scopes: text("scopes").array().notNull(), encryptedVerifier: text("encrypted_verifier").notNull(), + credentialVersion: integer("credential_version").notNull().default(1), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), consumedAt: timestamp("consumed_at", { withTimezone: true }), }, 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", { diff --git a/packages/api/src/postgres/x-connection-repository.ts b/packages/api/src/postgres/x-connection-repository.ts index 5179a1a8..6609b58b 100644 --- a/packages/api/src/postgres/x-connection-repository.ts +++ b/packages/api/src/postgres/x-connection-repository.ts @@ -17,6 +17,9 @@ export type XConnectionMetadata = { export class XReconnectRequiredError extends Error { constructor() { super("X authorization requires reconnection"); } } +export class XAccountMismatchError extends Error { + constructor() { super("X authorization resolved to a different account"); } +} type XConnectionRow = XConnectionMetadata & { encrypted_secret: string }; @@ -65,6 +68,26 @@ export class XConnectionRepository { return { clientId: row.client_id, clientSecret: secret.clientSecret, scopes: row.scopes, accessToken: typeof secret.accessToken === "string" ? secret.accessToken : undefined, refreshToken: typeof secret.refreshToken === "string" ? secret.refreshToken : undefined, expiresAt: typeof secret.expiresAt === "string" ? secret.expiresAt : undefined }; } + /** Replace only the app credentials. Existing account identity remains bound, + * while old tokens and in-flight OAuth attempts are invalidated atomically. */ + async replaceClientCredentials(id: string, input: { clientId: string; clientSecret: string }): Promise { + const encrypted = await encrypt(JSON.stringify({ clientSecret: input.clientSecret }), this.encryptionKey); + return this.database.transaction(async client => { + const { rows } = await client.query( + `UPDATE app.x_connections SET client_id=$3,encrypted_secret=$4, + credential_version=credential_version+1, + status=CASE WHEN account_id IS NULL THEN 'pending' ELSE 'reconnect_required' END, + granted_scopes='{}',updated_at=now() + WHERE tenant_id=$1 AND id=$2 AND status<>'revoked' + RETURNING id,name,client_id AS "clientId",scopes,account_id AS "accountId",account_handle AS "accountHandle", + granted_scopes AS "grantedScopes",status,created_at AS "createdAt",updated_at AS "updatedAt",encrypted_secret`, + [this.tenantId, id, input.clientId, encrypted]); + if (!rows[0]) return null; + await client.query("UPDATE app.x_oauth_attempts SET consumed_at=now() WHERE tenant_id=$1 AND connection_id=$2 AND consumed_at IS NULL", [this.tenantId, id]); + return metadata(rows[0]); + }); + } + /** Refresh under the connection row lock so concurrent requests share one * rotated refresh token. Disconnect and OAuth completion use the same row, * so neither can be overwritten by a late refresh. */ @@ -113,33 +136,45 @@ export class XConnectionRepository { async createOAuthAttempt(input: { nonce: string; userId: string; sessionVersion: number; connectionId: string; scopes: string[]; verifier: string; expiresAt: Date }): Promise { const encryptedVerifier = await encrypt(input.verifier, this.encryptionKey); - const result = await this.database.pool.query(`INSERT INTO app.x_oauth_attempts(tenant_id,nonce,user_id,session_version,connection_id,scopes,encrypted_verifier,expires_at) - SELECT $1,$2,$3,$4,$5,$6,$7,$8 WHERE EXISTS (SELECT 1 FROM app.x_connections WHERE tenant_id=$1 AND id=$5)`, + const result = await this.database.pool.query(`INSERT INTO app.x_oauth_attempts(tenant_id,nonce,user_id,session_version,connection_id,scopes,encrypted_verifier,expires_at,credential_version) + SELECT $1,$2,$3,$4,$5,$6,$7,$8,credential_version FROM app.x_connections WHERE tenant_id=$1 AND id=$5 AND status<>'revoked'`, [this.tenantId, input.nonce, input.userId, input.sessionVersion, input.connectionId, input.scopes, encryptedVerifier, input.expiresAt]); return Boolean(result.rowCount); } - async consumeOAuthAttempt(nonce: string): Promise<{ userId: string; sessionVersion: number; connectionId: string; scopes: string[]; verifier: string } | null> { - const { rows } = await this.database.pool.query<{ user_id: string; session_version: number; connection_id: string; scopes: string[]; encrypted_verifier: string }>( + async consumeOAuthAttempt(nonce: string): Promise<{ userId: string; sessionVersion: number; connectionId: string; scopes: string[]; verifier: string; credentialVersion: number } | null> { + const { rows } = await this.database.pool.query<{ user_id: string; session_version: number; connection_id: string; scopes: string[]; encrypted_verifier: string; credential_version: number }>( `UPDATE app.x_oauth_attempts SET consumed_at=now() WHERE tenant_id=$1 AND nonce=$2 AND consumed_at IS NULL AND expires_at>now() - AND EXISTS (SELECT 1 FROM app.x_connections c WHERE c.tenant_id=app.x_oauth_attempts.tenant_id AND c.id=app.x_oauth_attempts.connection_id AND c.status<>'revoked') - RETURNING user_id,session_version,connection_id,scopes,encrypted_verifier`, [this.tenantId, nonce]); + AND EXISTS (SELECT 1 FROM app.x_connections c WHERE c.tenant_id=app.x_oauth_attempts.tenant_id AND c.id=app.x_oauth_attempts.connection_id AND c.status<>'revoked' AND c.credential_version=app.x_oauth_attempts.credential_version) + RETURNING user_id,session_version,connection_id,scopes,encrypted_verifier,credential_version`, [this.tenantId, nonce]); const row = rows[0]; if (!row) return null; - return { userId: row.user_id, sessionVersion: row.session_version, connectionId: row.connection_id, scopes: row.scopes, verifier: await decrypt(row.encrypted_verifier, this.encryptionKey) }; + return { userId: row.user_id, sessionVersion: row.session_version, connectionId: row.connection_id, scopes: row.scopes, verifier: await decrypt(row.encrypted_verifier, this.encryptionKey), credentialVersion: row.credential_version }; } - async completeOAuth(id: string, input: { accessToken: string; refreshToken: string; expiresAt: string; accountId: string; accountHandle: string; grantedScopes: string[] }): Promise { - const credentials = await this.clientCredentials(id); + async clientCredentialsForVersion(id: string, credentialVersion: number): Promise<{ clientId: string; clientSecret: string; scopes: string[] } | null> { + const { rows } = await this.database.pool.query<{ client_id: string; encrypted_secret: string; scopes: string[] }>("SELECT client_id,encrypted_secret,scopes FROM app.x_connections WHERE tenant_id=$1 AND id=$2 AND credential_version=$3 AND status<>'revoked'", [this.tenantId, id, credentialVersion]); + const row = rows[0]; + if (!row) return null; + const secret = JSON.parse(await decrypt(row.encrypted_secret, this.encryptionKey)) as { clientSecret?: unknown }; + return typeof secret.clientSecret === "string" ? { clientId: row.client_id, clientSecret: secret.clientSecret, scopes: row.scopes } : null; + } + + async completeOAuth(id: string, input: { accessToken: string; refreshToken: string; expiresAt: string; accountId: string; accountHandle: string; grantedScopes: string[] }, credentialVersion = 1): Promise { + const credentials = await this.clientCredentialsForVersion(id, credentialVersion); if (!credentials) throw new Error("X connection not found"); const encrypted = await encrypt(JSON.stringify({ clientSecret: credentials.clientSecret, accessToken: input.accessToken, refreshToken: input.refreshToken, expiresAt: input.expiresAt }), this.encryptionKey); - const result = await this.database.pool.query(`UPDATE app.x_connections SET encrypted_secret=$3,account_id=$4,account_handle=$5,granted_scopes=$6,status='connected',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status<>'revoked'`, - [this.tenantId, id, encrypted, input.accountId, input.accountHandle, input.grantedScopes]); - if (!result.rowCount) throw new Error("X connection not found"); + const result = await this.database.transaction(async client => { + const current = await client.query<{ account_id: string | null }>("SELECT account_id FROM app.x_connections WHERE tenant_id=$1 AND id=$2 AND credential_version=$3 AND status<>'revoked' FOR UPDATE", [this.tenantId, id, credentialVersion]); + if (!current.rows[0]) throw new Error("X connection not found"); + if (current.rows[0].account_id && current.rows[0].account_id !== input.accountId) throw new XAccountMismatchError(); + const updated = await client.query("UPDATE app.x_connections SET encrypted_secret=$4,account_id=$5,account_handle=$6,granted_scopes=$7,status='connected',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND credential_version=$3 AND status<>'revoked'", [this.tenantId, id, credentialVersion, encrypted, input.accountId, input.accountHandle, input.grantedScopes]); + if (!updated.rowCount) throw new Error("X connection not found"); + }); } async resetOAuthAttempt(id: string): Promise { - await this.database.pool.query("UPDATE app.x_connections SET status='pending',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status<>'connected'", [this.tenantId, id]); + await this.database.pool.query("UPDATE app.x_connections SET status=CASE WHEN account_id IS NULL THEN 'pending' ELSE 'reconnect_required' END,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND status<>'connected' AND status<>'revoked'", [this.tenantId, id]); } async delete(id: string): Promise { diff --git a/packages/api/src/x-oauth-callback.ts b/packages/api/src/x-oauth-callback.ts index 8e4c932c..a66a27f3 100644 --- a/packages/api/src/x-oauth-callback.ts +++ b/packages/api/src/x-oauth-callback.ts @@ -1,7 +1,7 @@ import { requestCookie, readSession } from "./session"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; -import { XConnectionRepository } from "./postgres/x-connection-repository"; +import { XAccountMismatchError, XConnectionRepository } from "./postgres/x-connection-repository"; import { readXOAuthState } from "./x-oauth"; import type { Env } from "./types"; @@ -36,7 +36,7 @@ export async function xOAuthCallback(request: Request, env: Env): Promise { + const fixture = await loadingFixture(databaseUrl!); + try { + const repository = new XConnectionRepository(fixture.db, fixture.tenantId, fixture.env.CREDENTIAL_ENCRYPTION_KEY), id = crypto.randomUUID(); + await repository.create({ id, name: "Testable X", clientId: "public-client", clientSecret: "never-return-this", scopes: ["tweet.read", "users.read", "offline.access"] }); + await repository.completeOAuth(id, { accessToken: "private-access-token", refreshToken: "private-refresh-token", expiresAt: new Date(Date.now() + 3_600_000).toISOString(), accountId: "123", accountHandle: "safe_user", grantedScopes: ["tweet.read", "users.read", "offline.access"] }); + const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + expect(String(input)).toBe("https://api.x.com/2/users/me?user.fields=id%2Cusername"); + expect(init?.method).toBe("GET"); + expect(init?.headers).toMatchObject({ Authorization: "Bearer private-access-token" }); + return Response.json({ data: { id: "123", username: "safe_user" } }); + }); + vi.stubGlobal("fetch", fetcher); + const result = await worker.fetch(new Request(`https://factorize.test/api/v1/x/connections/${id}/test`, { method: "POST", headers: { Cookie: fixture.cookie, Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, body: "{}" }), fixture.env, { waitUntil() {} } as any); + expect(result.status).toBe(200); + const body = await result.text(); + expect(body).toContain('"status":"connected"'); + expect(body).not.toContain("private-access-token"); + expect(body).not.toContain("private-refresh-token"); + expect(body).not.toContain("never-return-this"); + expect(fetcher).toHaveBeenCalledOnce(); + expect(await repository.get(id)).toMatchObject({ status: "connected", accountId: "123", accountHandle: "safe_user" }); + vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ error: "sensitive upstream detail" }), { status: 503 }))); + const failed = await worker.fetch(new Request(`https://factorize.test/api/v1/x/connections/${id}/test`, { method: "POST", headers: { Cookie: fixture.cookie, Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, body: "{}" }), fixture.env, { waitUntil() {} } as any); + const failedBody = await failed.text(); + expect(failedBody).toContain('"status":"failed"'); + expect(failedBody).not.toContain("sensitive upstream detail"); + expect(await repository.get(id)).toMatchObject({ status: "connected", accountId: "123", accountHandle: "safe_user" }); + } finally { await fixture.cleanup(); } + }); + + it("replaces credentials without changing account identity and rejects stale or different-account reauthorization", async () => { + const fixture = await loadingFixture(databaseUrl!); + try { + const repository = new XConnectionRepository(fixture.db, fixture.tenantId, fixture.env.CREDENTIAL_ENCRYPTION_KEY), id = crypto.randomUUID(); + await repository.create({ id, name: "Replace X", clientId: "old-client", clientSecret: "old-secret", scopes: ["tweet.read", "users.read", "offline.access"] }); + await repository.completeOAuth(id, { accessToken: "old-access", refreshToken: "old-refresh", expiresAt: new Date(Date.now() + 3_600_000).toISOString(), accountId: "123", accountHandle: "bound_user", grantedScopes: ["tweet.read", "users.read", "offline.access"] }); + const firstStart = await worker.fetch(new Request(`https://factorize.test/api/v1/x/connections/${id}/authorize`, { method: "POST", headers: { Cookie: fixture.cookie, Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, body: "{}" }), fixture.env, { waitUntil() {} } as any); + const staleState = new URL((await firstStart.json() as { authorizationUrl: string }).authorizationUrl).searchParams.get("state")!; + const staleCookie = firstStart.headers.get("Set-Cookie")!.split(";", 1)[0]!; + const replacement = await worker.fetch(new Request(`https://factorize.test/api/v1/x/connections/${id}/credentials`, { method: "PUT", headers: { Cookie: fixture.cookie, Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify({ clientId: "new-client", clientSecret: "new-private-secret" }) }), fixture.env, { waitUntil() {} } as any); + expect(replacement.status).toBe(200); + const safeBody = await replacement.text(); + expect(safeBody).not.toContain("new-private-secret"); + expect(safeBody).toContain('"accountId":"123"'); + expect(safeBody).toContain('"status":"reconnect_required"'); + await expect(repository.clientCredentials(id)).resolves.toMatchObject({ clientId: "new-client", clientSecret: "new-private-secret", accessToken: undefined, refreshToken: undefined }); + const calls = vi.fn(async () => Response.json({ access_token: "must-not-store", refresh_token: "must-not-store", expires_in: 3600, scope: "tweet.read users.read offline.access" })); + vi.stubGlobal("fetch", calls); + const stale = await worker.fetch(new Request(`https://factorize.test/oauth/x/callback?code=stale-code&state=${encodeURIComponent(staleState)}`, { headers: { Cookie: `${fixture.cookie}; ${staleCookie}` } }), fixture.env, { waitUntil() {} } as any); + expect(stale.headers.get("Location")).toContain("x=expired"); + expect(calls).not.toHaveBeenCalled(); + + const start = await worker.fetch(new Request(`https://factorize.test/api/v1/x/connections/${id}/authorize`, { method: "POST", headers: { Cookie: fixture.cookie, Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, body: "{}" }), fixture.env, { waitUntil() {} } as any); + const state = new URL((await start.json() as { authorizationUrl: string }).authorizationUrl).searchParams.get("state")!; + const cookie = start.headers.get("Set-Cookie")!.split(";", 1)[0]!; + vi.stubGlobal("fetch", async (input: RequestInfo | URL) => { + if (String(input) === "https://api.x.com/2/oauth2/token") return Response.json({ access_token: "new-access", refresh_token: "new-refresh", expires_in: 3600, scope: "tweet.read users.read offline.access" }); + if (String(input).startsWith("https://api.x.com/2/users/me")) return Response.json({ data: { id: "999", username: "different_user" } }); + throw new Error("Unexpected request"); + }); + const mismatch = await worker.fetch(new Request(`https://factorize.test/oauth/x/callback?code=new-code&state=${encodeURIComponent(state)}`, { headers: { Cookie: `${fixture.cookie}; ${cookie}` } }), fixture.env, { waitUntil() {} } as any); + expect(mismatch.headers.get("Location")).toContain("x=account_mismatch"); + expect(await repository.get(id)).toMatchObject({ status: "reconnect_required", accountId: "123", accountHandle: "bound_user", grantedScopes: [] }); + await expect(repository.accessToken(id, async () => { throw new Error("must not access paused connection"); })).resolves.toBeNull(); + } finally { await fixture.cleanup(); } + }); }); diff --git a/packages/app/src/features/settings/x-connections.tsx b/packages/app/src/features/settings/x-connections.tsx index c668e95f..68959d26 100644 --- a/packages/app/src/features/settings/x-connections.tsx +++ b/packages/app/src/features/settings/x-connections.tsx @@ -29,6 +29,7 @@ const suggested: XScope[] = ["tweet.read", "users.read", "offline.access"]; export function XConnections() { const cache = useQueryClient(); 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); const connections = useQuery({ queryKey: ["settings", "x-connections"], queryFn: async ({ signal }) => { const result = await api.GET("/api/v1/x/connections", { signal }); @@ -41,6 +42,7 @@ export function XConnections() { connected: "X account connected and verified.", denied: "X authorization was declined. You can try again when ready.", expired: "That X authorization expired or was already used. Start a new attempt.", scope_mismatch: "X granted fewer permissions than selected. Review the scopes and reconnect.", + account_mismatch: "X authorized a different account. This connection remains bound to its original account; create a new connection to use another account.", session_required: "Sign in again as the workspace owner before connecting X.", failed: "X authorization could not be verified. Check the app setup and try again.", }; if (result && messages[result]) { @@ -65,6 +67,21 @@ export function XConnections() { if (!response.data || response.error) throw new Error(messageOf(response.error)); location.assign(response.data.authorizationUrl); }, onError: value => setError(value.message) }); + const testConnection = useMutation({ retry: false, mutationFn: async (id: string) => { + const response = await api.POST("/api/v1/x/connections/{connectionId}/test", { params: { path: { connectionId: id } }, body: {} }); + if (!response.data || response.error) throw new Error(messageOf(response.error)); + return response.data; + }, onSuccess: result => setNotice(result.message), onError: value => setError(value.message) }); + const replaceCredentials = useMutation({ retry: false, mutationFn: async (id: string) => { + const response = await api.PUT("/api/v1/x/connections/{connectionId}/credentials", { params: { path: { connectionId: id } }, body: { clientId: replacementClientId, clientSecret: replacementSecret } }); + if (!response.data || response.error) throw new Error(messageOf(response.error)); + return response.data; + }, onSuccess: async connection => { + setReplacementSecret(""); setReplacementClientId(""); setReplaceId(null); + await cache.invalidateQueries({ queryKey: ["settings", "x-connections"] }); + 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`; @@ -76,6 +93,16 @@ export function XConnections() {

    {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.

    + + + +
    } )}

    Set up your X developer app

      diff --git a/packages/app/test/x-connections.browser.test.mjs b/packages/app/test/x-connections.browser.test.mjs index dc8dd809..e178a0ab 100644 --- a/packages/app/test/x-connections.browser.test.mjs +++ b/packages/app/test/x-connections.browser.test.mjs @@ -87,3 +87,37 @@ test("X settings explains terminal authorization failures and offers an explicit assert.equal(authorizeCalls, 1); await context.close(); }); + +test("X owner can test safely and replace app credentials before same-account reauthorization", async () => { + const context = await browser.newContext(), page = await context.newPage(); + const connectionId = "47d2f592-0f70-40a9-8cea-37b34d2a1573"; + let replacement, tested = 0; + 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/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: [] }); + if (path === "/api/v1/model-accounts") return route.fulfill({ json: { accounts: [], revision: 0 } }); + if (path === "/api/v1/integrations/bearer") return route.fulfill({ json: { integrations: [], revision: 0 } }); + if (path === "/api/v1/integration-api-policies") return route.fulfill({ json: { integrations: [] } }); + if (path === `/api/v1/x/connections/${connectionId}/test`) { tested++; return route.fulfill({ json: { status: "failed", accountHandle: "work_user", message: "X could not verify the connection. Try again later." } }); } + if (path === `/api/v1/x/connections/${connectionId}/credentials` && route.request().method() === "PUT") { replacement = route.request().postDataJSON(); return route.fulfill({ json: { id: connectionId, name: "Work account", clientId: replacement.clientId, scopes: ["tweet.read", "users.read", "offline.access"], accountId: "123", accountHandle: "work_user", grantedScopes: [], status: "reconnect_required", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() } }); } + if (path === `/api/v1/x/connections/${connectionId}/authorize`) return route.fulfill({ json: { authorizationUrl: "https://x.com/i/oauth2/authorize?state=replacement" } }); + if (path === "/api/v1/x/connections") return route.fulfill({ json: { connections: [{ id: connectionId, name: "Work account", clientId: "client-123", scopes: ["tweet.read", "users.read", "offline.access"], accountId: "123", accountHandle: "work_user", grantedScopes: ["tweet.read", "users.read", "offline.access"], status: "connected", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }] } }); + return route.fulfill({ json: {} }); + }); + 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.getByRole("status").filter({ hasText: "X could not verify the connection" }).waitFor(); + assert.equal(tested, 1); + await page.getByRole("button", { name: "Replace app credentials" }).click(); + 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(); + await page.waitForURL("https://x.com/i/oauth2/authorize**"); + assert.deepEqual(replacement, { clientId: "replacement-client", clientSecret: "replacement-secret" }); + assert.equal(await page.getByText("replacement-secret", { exact: true }).count(), 0); + await context.close(); +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 963a07e9..9321f6a8 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -2204,6 +2204,199 @@ paths: type: object properties: {} additionalProperties: false + /api/v1/x/connections/{connectionId}/test: + post: + summary: Test an X connection + description: |- + Requires an interactive owner session. Performs a non-mutating GET to X /2/users/me using the saved access token. Returns only a safe status and the already stored account handle; it never returns tokens, credentials, or upstream error bodies. The verification read may incur X API usage charges. + + Requires the integrations:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Safe connection test result + content: + application/json: + schema: + type: object + properties: + status: + type: string + enum: + - connected + - failed + - reconnect_required + accountHandle: + type: + - string + - "null" + message: + type: string + required: + - status + - accountHandle + - message + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_x_connections_connectionId_test + tags: + - x + security: + - cookieAuth: [] + x-required-scope: integrations:read + x-owner-session-required: true + parameters: + - name: connectionId + in: path + required: true + schema: + 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)$ + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: {} + additionalProperties: false + /api/v1/x/connections/{connectionId}/credentials: + put: + summary: Replace X app credentials + description: |- + Requires an interactive owner session. Replaces the encrypted client credentials, invalidates saved access and refresh tokens and pending OAuth attempts, preserves the existing account identity binding, and requires reauthorization. Reauthorization cannot switch the connection to a different X account; create a new connection for another account. Existing run selections remain unavailable until authorization succeeds. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Updated safe connection metadata + content: + application/json: + schema: + type: object + properties: + id: + 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)$ + name: + type: string + clientId: + type: string + scopes: + type: array + items: + type: string + accountId: + type: + - string + - "null" + accountHandle: + type: + - string + - "null" + grantedScopes: + type: array + items: + type: string + status: + type: string + enum: + - pending + - connected + - reconnect_required + - revoked + createdAt: + type: string + updatedAt: + type: string + required: + - id + - name + - clientId + - scopes + - accountId + - accountHandle + - grantedScopes + - status + - createdAt + - updatedAt + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: put_api_v1_x_connections_connectionId_credentials + tags: + - x + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + parameters: + - name: connectionId + in: path + required: true + schema: + 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)$ + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + clientId: + type: string + minLength: 1 + maxLength: 256 + clientSecret: + type: string + minLength: 1 + maxLength: 4096 + pattern: ^[^\r\n]+$ + writeOnly: true + required: + - clientId + - clientSecret + additionalProperties: false /api/v1/model-accounts: get: summary: List model accounts available to the owner