{"version":3,"file":"popupAuthorizer.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/ToolCalls/popupAuthorizer.ts"],"sourcesContent":["import type { AIToolCallPart } from '../MessageParts';\nimport type { AIToolAuthorizer } from './AIToolApprover';\n\n// The sign-in runs the router's launch page in a popup. The page asks its opener for the\n// handoff token, then leaves for the provider, clearing its opener on the way. So the page the\n// router finally sends the popup back to (the session's return_url) reports how it ended over\n// a BroadcastChannel instead. The web counterpart of `AIWebAuthentication` in StreamChatAI.\n\n/** The BroadcastChannel the return page reports the sign-in's outcome on. */\nexport const AI_CONNECTOR_SIGN_IN_CHANNEL = 'stream-chat-ai-connector-sign-in';\n\nconst READY = 'va.connector.oauth.ready';\nconst HANDOFF = 'va.connector.oauth.handoff';\nconst RESULT = 'va.connector.oauth.result';\n\n/** How the router says a consent ended, in the return page's `status` query parameter. */\nexport type ConnectorSignInStatus =\n  | 'connected'\n  | 'denied'\n  | 'failed'\n  | 'account_mismatch';\n\nconst OUTCOMES: readonly string[] = [\n  'connected',\n  'denied',\n  'failed',\n  'account_mismatch',\n] satisfies ConnectorSignInStatus[];\n\nconst CONNECTION_ID = /^[\\w-]{1,128}$/;\n\n/** The sign-in's outcome, as the return page read it from its query. */\nexport type ConnectorSignInResult = {\n  connectionId: string;\n  status: ConnectorSignInStatus;\n};\n\n/**\n * Why a sign-in could not be opened: the browser blocked the popup (`blocked`), the launch\n * page never asked for the handoff, such as when it does not take it from this origin\n * (`unreachable`), or the call carries no sign-in to open (`unavailable`).\n */\nexport class AIConnectorSignInError extends Error {\n  readonly reason: 'blocked' | 'unavailable' | 'unreachable';\n\n  constructor(reason: AIConnectorSignInError['reason']) {\n    super(`The sign-in couldn't be opened (${reason}).`);\n    this.name = 'AIConnectorSignInError';\n    this.reason = reason;\n  }\n}\n\nexport type PopupAuthorizerOptions = {\n  /**\n   * Tells your backend the person won't sign in now. Your backend ends the call. A rejection\n   * lets the person answer again.\n   */\n  decline: (call: AIToolCallPart) => Promise<void>;\n  /**\n   * The page the sign-in comes back to, which runs `completeConnectorSignIn()`. Give it to your\n   * sessions as their `return_url`: the launch page takes the handoff only from a page of its\n   * origin, so it must be this app's origin.\n   */\n  returnUrl: string;\n  /** The BroadcastChannel name, the same as the return page's. Defaults to `AI_CONNECTOR_SIGN_IN_CHANNEL`. */\n  channelName?: string;\n  /** How often to check whether the person closed the popup, in milliseconds. Defaults to 500. */\n  closedPollIntervalMs?: number;\n  /** The popup's window features. Defaults to a 520 × 720 popup. */\n  popupFeatures?: string;\n  /** The popup's window name. */\n  popupName?: string;\n  /** How long the launch page has to ask for the handoff, in milliseconds. Defaults to 15 s. */\n  readyTimeoutMs?: number;\n  /**\n   * How long to wait for the outcome once handed off, in milliseconds, when the sign-in names\n   * no expiry. Defaults to 10 minutes, the router's consent lifetime.\n   */\n  timeoutMs?: number;\n};\n\nexport type PopupAuthorizer = AIToolAuthorizer & { returnUrl: string };\n\n/**\n * An `AIToolAuthorizer` that opens a call's sign-in in a popup, from the click itself, and\n * hands the sign-in its token over `postMessage`:\n *\n * 1. the popup opens the call's `authorization.url` (the router's launch page);\n * 2. the page posts `{ type: 'va.connector.oauth.ready' }` to this window, from its origin;\n * 3. this window posts back `{ type: 'va.connector.oauth.handoff', handoff_token }`, to that\n *    origin only;\n * 4. the page goes to the provider, which sends the person back through the router to\n *    `returnUrl`, where `completeConnectorSignIn()` reports the outcome over a BroadcastChannel.\n *\n * `connect` resolves `true` when the account is connected and `false` when the popup was closed\n * or the sign-in ended otherwise. It rejects with an `AIConnectorSignInError` when the browser\n * blocked the popup or the launch page never asked for the handoff.\n */\nexport const createPopupAuthorizer = ({\n  channelName = AI_CONNECTOR_SIGN_IN_CHANNEL,\n  closedPollIntervalMs = 500,\n  decline,\n  popupFeatures = 'popup,width=520,height=720',\n  popupName = 'stream-chat-ai-sign-in',\n  readyTimeoutMs = 15_000,\n  returnUrl,\n  timeoutMs = 10 * 60_000,\n}: PopupAuthorizerOptions): PopupAuthorizer => {\n  const connect = (call: AIToolCallPart): Promise<boolean> => {\n    const authorization = call.authorization;\n    if (!authorization?.handoffToken) {\n      return Promise.reject(new AIConnectorSignInError('unavailable'));\n    }\n    const handoffToken = authorization.handoffToken;\n    const target = new URL(authorization.url);\n    // Opened before anything is awaited, so the click still counts as the user's gesture.\n    const popup = window.open(target.href, popupName, popupFeatures);\n    if (!popup) return Promise.reject(new AIConnectorSignInError('blocked'));\n\n    return new Promise<boolean>((resolve, reject) => {\n      let handedOff = false;\n      let done = false;\n      const stops: Array<() => void> = [];\n      const finish = (outcome: boolean | AIConnectorSignInError) => {\n        if (done) return;\n        done = true;\n        stops.forEach((stop) => stop());\n        if (outcome instanceof AIConnectorSignInError) reject(outcome);\n        else resolve(outcome);\n      };\n\n      const onMessage = (event: MessageEvent) => {\n        if (handedOff || event.source !== popup || event.origin !== target.origin) return;\n        const data = event.data as { type?: unknown } | null;\n        if (!data || data.type !== READY) return;\n        handedOff = true;\n        popup.postMessage({ handoff_token: handoffToken, type: HANDOFF }, target.origin);\n      };\n      window.addEventListener('message', onMessage);\n      stops.push(() => window.removeEventListener('message', onMessage));\n\n      if (typeof BroadcastChannel !== 'undefined') {\n        const channel = new BroadcastChannel(channelName);\n        channel.onmessage = (event: MessageEvent) => {\n          const data = event.data as { status?: unknown; type?: unknown } | null;\n          if (!handedOff || !data || data.type !== RESULT) return;\n          if (typeof data.status !== 'string' || !OUTCOMES.includes(data.status)) return;\n          finish(data.status === 'connected');\n        };\n        stops.push(() => channel.close());\n      }\n\n      // A launch page that never asks has refused this origin as its opener.\n      const readyTimer = setTimeout(() => {\n        if (handedOff) return;\n        popup.close();\n        finish(new AIConnectorSignInError('unreachable'));\n      }, readyTimeoutMs);\n      stops.push(() => clearTimeout(readyTimer));\n\n      const remaining =\n        authorization.expiresAt !== undefined\n          ? Math.max(0, authorization.expiresAt - Date.now())\n          : timeoutMs;\n      const expiryTimer = setTimeout(\n        () => finish(false),\n        Math.max(remaining, readyTimeoutMs),\n      );\n      stops.push(() => clearTimeout(expiryTimer));\n\n      // A provider's page can sever the popup from this window (Google's consent does), which\n      // then looks closed while the person is still deciding there. So once handed off, a closed\n      // popup ends the sign-in only when the person is back on this page; until then the outcome\n      // or the expiry does. Your backend's change to the step is the record either way.\n      const closedTimer = setInterval(() => {\n        if (popup.closed && (!handedOff || document.hasFocus())) finish(false);\n      }, closedPollIntervalMs);\n      stops.push(() => clearInterval(closedTimer));\n    });\n  };\n\n  return { connect, decline, returnUrl };\n};\n\n/** Reads the router's redirect to the return page: `?connection_id=…&status=…`. */\nexport const readConnectorSignInResult = (\n  search: string,\n): ConnectorSignInResult | null => {\n  const params = new URLSearchParams(search);\n  const connectionId = params.get('connection_id') ?? '';\n  const status = params.get('status') ?? '';\n  if (!CONNECTION_ID.test(connectionId) || !OUTCOMES.includes(status)) return null;\n  return { connectionId, status: status as ConnectorSignInStatus };\n};\n\nexport type CompleteConnectorSignInOptions = {\n  /** The BroadcastChannel name, the same as the authorizer's. Defaults to `AI_CONNECTOR_SIGN_IN_CHANNEL`. */\n  channelName?: string;\n  /** Whether to close the popup once the outcome is reported. Defaults to `true`. */\n  close?: boolean;\n  /** The query to read. Defaults to `window.location.search`. */\n  search?: string;\n};\n\n/**\n * Runs on the page a sign-in comes back to (the `returnUrl` of `createPopupAuthorizer`): reads\n * `connection_id` and `status` from its query, reports them to the page that opened the\n * sign-in over a BroadcastChannel, and closes the popup.\n *\n * ```ts\n * // connected.html\n * import { completeConnectorSignIn } from 'stream-chat-react/ai-components';\n * completeConnectorSignIn();\n * ```\n *\n * Returns what it read, or `null` when the query holds no outcome.\n */\nexport const completeConnectorSignIn = ({\n  channelName = AI_CONNECTOR_SIGN_IN_CHANNEL,\n  close = true,\n  search = typeof window === 'undefined' ? '' : window.location.search,\n}: CompleteConnectorSignInOptions = {}): ConnectorSignInResult | null => {\n  const result = readConnectorSignInResult(search);\n  if (!result) return null;\n  if (typeof BroadcastChannel !== 'undefined') {\n    const channel = new BroadcastChannel(channelName);\n    channel.postMessage({\n      connection_id: result.connectionId,\n      status: result.status,\n      type: RESULT,\n    });\n    channel.close();\n  }\n  if (close && typeof window !== 'undefined') window.close();\n  return result;\n};\n"],"mappings":";;AASA,IAAa,+BAA+B;AAE5C,IAAM,QAAQ;AACd,IAAM,UAAU;AAChB,IAAM,SAAS;AASf,IAAM,WAA8B;CAClC;CACA;CACA;CACA;AACF;AAEA,IAAM,gBAAgB;;;;;;AAatB,IAAa,yBAAb,cAA4C,MAAM;CAChD;CAEA,YAAY,QAA0C;EACpD,MAAM,mCAAmC,OAAO,GAAG;EACnD,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;;;;;;;;;;;;;;;;AAgDA,IAAa,yBAAyB,EACpC,cAAc,8BACd,uBAAuB,KACvB,SACA,gBAAgB,8BAChB,YAAY,0BACZ,iBAAiB,MACjB,WACA,YAAY,KAAK,UAC4B;CAC7C,MAAM,WAAW,SAA2C;EAC1D,MAAM,gBAAgB,KAAK;EAC3B,IAAI,CAAC,eAAe,cAClB,OAAO,QAAQ,OAAO,IAAI,uBAAuB,aAAa,CAAC;EAEjE,MAAM,eAAe,cAAc;EACnC,MAAM,SAAS,IAAI,IAAI,cAAc,GAAG;EAExC,MAAM,QAAQ,OAAO,KAAK,OAAO,MAAM,WAAW,aAAa;EAC/D,IAAI,CAAC,OAAO,OAAO,QAAQ,OAAO,IAAI,uBAAuB,SAAS,CAAC;EAEvE,OAAO,IAAI,SAAkB,SAAS,WAAW;GAC/C,IAAI,YAAY;GAChB,IAAI,OAAO;GACX,MAAM,QAA2B,CAAC;GAClC,MAAM,UAAU,YAA8C;IAC5D,IAAI,MAAM;IACV,OAAO;IACP,MAAM,SAAS,SAAS,KAAK,CAAC;IAC9B,IAAI,mBAAmB,wBAAwB,OAAO,OAAO;SACxD,QAAQ,OAAO;GACtB;GAEA,MAAM,aAAa,UAAwB;IACzC,IAAI,aAAa,MAAM,WAAW,SAAS,MAAM,WAAW,OAAO,QAAQ;IAC3E,MAAM,OAAO,MAAM;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