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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3511,6 +3511,8 @@ export interface operations {
clientName: string;
scopes: string[];
selectedScopes: string[];
unavailableSavedScopes: string[];
reconnect: boolean;
request: string;
signature: string;
expiresAt: string;
Expand Down
7 changes: 4 additions & 3 deletions packages/api/src/agent-api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { initialIntegrationOverrides } from "./oauth-reconnect";
import { activeVmAuthorization } from "./vm-auth";
import { connectionAccess, requiredIntegrationScope, type AgentIntegration, type ConnectionPolicy } from "./agent-integration-access";
export { connectionAccess, requiredIntegrationScope, type AgentIntegration } from "./agent-integration-access";
Expand Down Expand Up @@ -78,9 +79,9 @@ export class AgentApiService {
if (auth.authMethod === "oauth" && auth.oauthGrantId && auth.oauthClientId && auth.oauthExpiresAt && auth.oauthExpiresAt > Date.now()/1000) {
kind = "oauth"; subject = auth.oauthGrantId;
} else throw invalidIdentity();
const row = (await this.database.pool.query<ConnectionPolicy & {id: string; user_id: string; session_version: number; revoked_at: Date | null}>(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version)
VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET subject=excluded.subject
RETURNING id,user_id,session_version,revoked_at,integration_overrides,disabled_scopes`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion])).rows[0]!;
const row = (await this.database.pool.query<ConnectionPolicy & {id: string; user_id: string; session_version: number; revoked_at: Date | null}>(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,integration_overrides)
VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET subject=excluded.subject
RETURNING id,user_id,session_version,revoked_at,integration_overrides,disabled_scopes`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion, JSON.stringify(initialIntegrationOverrides(auth.initialIntegrationDenials))])).rows[0]!;
if (row.revoked_at || row.user_id !== auth.userId || row.session_version !== auth.sessionVersion) throw invalidIdentity();
return {id: row.id, kind, policy: row, scopes: auth.scopes};
}
Expand Down
12 changes: 9 additions & 3 deletions packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { initialIntegrationOverrides, lockOAuthPolicy } from "./oauth-reconnect";
import { lockMcpEventGrant } from "./postgres/mcp-event-outbox";
import { eventPayloadSchema, eventProtocolName, type ReadEventOccurrencesInput, type subscribeEventInput, type unsubscribeEventInput } from "./mcp-event-contracts";
import { subscribeMcpEvent, unsubscribeMcpEvent } from "./mcp-event-subscriptions";
Expand Down Expand Up @@ -620,14 +621,17 @@ export class ApiService {
if (scopes.includes(integration.requiredScope)) delete integrationOverrides[integration.id];
else if (edit.integrationOverrides?.[integration.id] === false || (integration.available && integration.policy !== "disabled")) integrationOverrides[integration.id] = false;
}
const result = await databaseFor(this.env).pool.query(`
const result = await databaseFor(this.env).transaction(async sql => {
await lockOAuthPolicy(sql, this.auth);
return sql.query(`
INSERT INTO app.agent_identities AS i(tenant_id,kind,subject,user_id,session_version,disabled_scopes,scope_overrides,integration_overrides,permissions_revision)
SELECT $1,'oauth',$2,$3,$4,'{}',$5,$6,1 WHERE coalesce($7::integer,0)=0 OR EXISTS
(SELECT 1 FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2)
ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET disabled_scopes='{}',scope_overrides=excluded.scope_overrides,
integration_overrides=excluded.integration_overrides,permissions_revision=i.permissions_revision+1
WHERE i.revoked_at IS NULL AND i.user_id=excluded.user_id AND ($7 IS NULL OR i.permissions_revision=$7)
RETURNING permissions_revision`, [this.auth.tenantId, grantId, this.auth.userId, this.auth.sessionVersion, [...new Set(scopes)], JSON.stringify(integrationOverrides), edit.expectedRevision ?? client.revision]);
});
if (!result.rowCount) throw new ServiceError(409, "conflict", "Connection permissions changed. Reload permissions.");
return { ok: true };
}
Expand All @@ -645,16 +649,17 @@ export class ApiService {
const scopeLabels = Object.fromEntries(integrations.map(row => [row.requiredScope, `${row.name} integration access`]));
return publicValue(z.array(authorizedClient), grants.map(grant => {
const row = byGrant.get(grant.id), grantedScopes = normalizeScopes(grant.scope);
const integrationOverrides = row?.integration_overrides ?? initialIntegrationOverrides(grant.metadata?.initialIntegrationDenials);
const baseScopes = row?.scope_overrides ?? grantedScopes.filter(scope => !row?.disabled_scopes.includes(scope));
const baselineScopes = integrations.filter(integration => integration.policy === "baseline" && integration.available).map(integration => integration.requiredScope);
const scopes = [...new Set([...baseScopes,...baselineScopes])].filter(scope => {
const id = scope.match(integrationScopePattern)?.[1];
return !row?.disabled_scopes.includes(scope) && (!id || row?.integration_overrides?.[id] !== false);
return !row?.disabled_scopes.includes(scope) && (!id || integrationOverrides[id] !== false);
});
const availableScopes = [...new Set([...globallyAvailable, ...scopes])];
return { grantId: grant.id, clientId: grant.clientId, clientName: row?.display_name ?? byId.get(grant.clientId)?.clientName ?? grant.clientId, appName: byId.get(grant.clientId)?.clientName ?? grant.clientId,
availableScopes, scopeLabels, scopes, revision: row?.permissions_revision ?? 0,
integrationOverrides: row?.integration_overrides ?? {}, authorizationDate: new Date(grant.createdAt * 1000).toISOString(),
integrationOverrides, authorizationDate: new Date(grant.createdAt * 1000).toISOString(),
expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null };
}));
}
Expand All @@ -665,6 +670,7 @@ export class ApiService {
do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId,{limit:100,cursor}); found ||= page.items.some(grant=>grant.id===grantId && (grant.metadata as any)?.tenantId===this.auth.tenantId); cursor=page.cursor; } while(cursor && !found);
if(!found) throw new ServiceError(404,"not_found","Authorization not found");
await databaseFor(this.env).transaction(async sql => {
await lockOAuthPolicy(sql, this.auth);
await lockMcpEventGrant(sql, this.auth.tenantId, grantId);
await sql.query(`UPDATE app.mcp_event_subscriptions SET status='stopped',previous_encrypted_secret=NULL,rotated_at=NULL
WHERE tenant_id=$1 AND user_id=$2 AND grant_id=$3 AND status='active'`, [this.auth.tenantId, this.auth.userId, grantId]);
Expand Down
9 changes: 6 additions & 3 deletions packages/api/src/auth-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { integrationConsentLabels } from "./agent-api";
import { ACCESS_SCOPES } from "./access-tokens";
import { connectionFor, originalBrowser, startConnection, connectionDestination } from "./oauth-continuation";
import { inspectDevice, decideDevice, deviceConsentSignature, safeEqual } from "./device-oauth";
import { consentPreview, consentDecision, consentPreviewInput, consentDecisionInput } from "./consent-api";
import { ConsentPreviewError, consentPreview, consentDecision, consentPreviewInput, consentDecisionInput } from "./consent-api";
import { serialize } from "hono/utils/cookie";
import { z } from "zod";
import { AuthRepository } from "./postgres/auth-repository";
Expand Down Expand Up @@ -135,8 +135,11 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env
if (!session) return failure(401, "Sign in before authorizing a client.");
try {
const data = action === "consent-preview" ? await consentPreview(env, session, consentPreviewInput.parse(input), request) : await consentDecision(env, session, consentDecisionInput.parse(input));
return data ? authJson(data) : failure(400, "This authorization request is invalid, expired, or already completed. Start a new connection from your MCP client.");
} catch { return failure(400, "This authorization request could not be validated. Return to the browser where you started connecting, or start a new connection from your MCP client."); }
return data ? authJson(data) : failure(400, "This approval is no longer current. Reload the request and review the permissions again. If the connection link has expired or was already used, start Reconnect in your MCP client.");
} catch (error) {
if (error instanceof ConsentPreviewError) return failure(400, error.message);
return failure(400, "Factorize couldn't validate this connection. Start Reconnect in your MCP client and use the fresh authorization link.");
}
}
if (action === "logout") {
if (session) await new IdentityRepository(databaseFor(env), session.tenantId).revoke(session.userId);
Expand Down
Loading
Loading