Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

2.2 KB
Raw Blame
import { ConnectorOAuthError } from '@/utils/connectorOAuth';

export interface OAuthCreateDeps<TPayload> {
  createConnector: (payload: TPayload) => Promise<{ id: string; isNew: boolean }>;
  deleteConnector: (id: string) => Promise<void>;
  /** Re-read the connector from the server and report whether it is connected. */
  isConnectorConnected: (id: string) => Promise<boolean>;
  startConnectorOAuth: (id: string) => Promise<string>;
  /** Settles when the callback completes; what it reports is not needed here. */
  waitForConnectorOAuth: (
    popup: Window | null | undefined,
    connectorId: string,
    authorizationUrl: string,
  ) => Promise<unknown>;
}

/**
 * Create an OAuth connector and drive its authorize flow in the popup DevModal
 * opened (or the native desktop window).
 *
 * When the flow cannot even start (discovery failed, registration rejected, …)
 * nothing can have been authorized, so the row this attempt created is rolled
 * back instead of leaving a disconnected, tool-less connector behind — the same
 * `isNew` guard as the non-OAuth path, so a pre-existing connector is never
 * deleted. Once the popup is navigated the row is kept: a "dismissed" result may
 * still hide a successful callback whose status message was lost — providers
 * whose COOP policy severs `window.opener` (e.g. Stripe) always lose it. For a
 * fresh row only the callback can mark it connected, so the server state
 * decides between success and a real cancel.
 */
export const executeOAuthCreate = async <TPayload>(
  payload: TPayload,
  popup: Window | null | undefined,
  deps: OAuthCreateDeps<TPayload>,
): Promise<void> => {
  const { id, isNew } = await deps.createConnector(payload);

  let authorizationUrl: string;
  try {
    authorizationUrl = await deps.startConnectorOAuth(id);
  } catch (error) {
    if (isNew) await deps.deleteConnector(id).catch(() => {});
    throw error;
  }

  try {
    await deps.waitForConnectorOAuth(popup, id, authorizationUrl);
  } catch (error) {
    const dismissed = error instanceof ConnectorOAuthError && error.reason === 'dismissed';
    if (!dismissed || !isNew) throw error;
    if (!(await deps.isConnectorConnected(id).catch(() => false))) throw error;
  }
};