[{"data":1,"prerenderedAt":7},["ShallowReactive",2],{"docs-partner-connect\u002Fai-in-app":3,"docs-tabs-partner-connect\u002Fai-in-app":6},{"content":4,"lastmod":5},"# Connecting AI from an application inside Bitrix24\n\nAn application that opens in a frame of a Bitrix24 account cannot show the consent page inside itself: the consent page forbids embedding in other sites with the `X-Frame-Options: SAMEORIGIN` and `Content-Security-Policy: frame-ancestors 'self'` headers. This way it cannot be spoofed or hidden under someone else's interface. So the \"Connect AI\" button opens consent in a separate browser window, and the frame waits for the result from your server.\n\n## How it works\n\n1. The button in the frame opens a window at your server's address and passes a one-time attempt identifier, `ticket`, in the URL.\n2. The server remembers the attempt and redirects the window to `\u002Fv1\u002Fconnect\u002Fauthorize` with the `vibe:ai` scope.\n3. The user selects a Bitrix24 account and confirms access. Vibecode returns the window to your `redirect_uri`.\n4. The server exchanges the code for a key, marks the attempt as finished and closes the window.\n5. The frame polls the server by `ticket` and shows the result.\n\n## Code in the application frame\n\n```html\n\u003Cbutton id=\"connect-ai\" type=\"button\">Connect AI\u003C\u002Fbutton>\n\u003Cp id=\"connect-ai-status\" role=\"status\">\u003C\u002Fp>\n\n\u003Cscript>\n  const button = document.getElementById('connect-ai')\n  const statusLine = document.getElementById('connect-ai-status')\n\n  button.addEventListener('click', () => {\n    \u002F\u002F The window opens right in the click handler: the browser blocks a window opened after await\n    const ticket = crypto.randomUUID()\n    const popup = window.open(\n      `\u002Fconnect\u002Fai\u002Fstart?ticket=${ticket}`,\n      'vibe-connect-ai',\n      'popup,width=640,height=760',\n    )\n    if (!popup) {\n      statusLine.textContent = 'Allow pop-up windows for this application and click the button again'\n      return\n    }\n    statusLine.textContent = 'Confirm access in the window that opened'\n    waitForResult(ticket)\n  })\n\n  async function waitForResult(ticket) {\n    const deadline = Date.now() + 10 * 60 * 1000 \u002F\u002F 10 minutes for consent\n    while (Date.now() \u003C deadline) {\n      await new Promise((resolve) => setTimeout(resolve, 2000))\n      const res = await fetch(`\u002Fconnect\u002Fai\u002Fstatus?ticket=${ticket}`)\n      const result = await res.json()\n      if (result.status === 'ok') {\n        statusLine.textContent = 'AI connected'\n        return\n      }\n      if (result.status === 'denied') {\n        statusLine.textContent = `AI not connected: ${result.reason}`\n        return\n      }\n    }\n    statusLine.textContent = 'Connection not finished. Click the button again'\n  }\n\u003C\u002Fscript>\n```\n\n## Server code\n\nThe application server performs the same code exchange as in the [full example](\u002Fdocs\u002Fpartner-connect#full-example) and keeps the attempt state for the frame. `db` and `encrypt` are your storage and encryption. Register the address `https:\u002F\u002Fyourapp.com\u002Fconnect\u002Fai\u002Fcallback` with the client as a `redirect_uri`, and the `vibe:ai` scope must be among the client's scopes — see [Platform scopes](\u002Fdocs\u002Fpartner-connect\u002Fregistration#platform-scopes).\n\n```javascript\nimport express from 'express'\nimport crypto from 'node:crypto'\n\nconst app = express()\nconst attempts = new Map() \u002F\u002F ticket → attempt result; in production, Redis or a database\nconst states = new Map() \u002F\u002F state → ticket\n\nconst CLIENT_ID = process.env.PARTNER_CLIENT_ID\nconst CLIENT_SECRET = process.env.PARTNER_CLIENT_SECRET\nconst REDIRECT_URI = 'https:\u002F\u002Fyourapp.com\u002Fconnect\u002Fai\u002Fcallback'\nconst TICKET_RE = \u002F^[0-9a-f-]{36}$\u002F\n\n\u002F\u002F 1. The window opened by the button comes here and goes on to the consent page\napp.get('\u002Fconnect\u002Fai\u002Fstart', (req, res) => {\n  const { ticket } = req.query\n  if (typeof ticket !== 'string' || !TICKET_RE.test(ticket) || attempts.has(ticket)) {\n    return res.status(400).send('Invalid connection attempt')\n  }\n  attempts.set(ticket, { status: 'pending' })\n\n  const state = crypto.randomBytes(16).toString('hex')\n  states.set(state, ticket)\n\n  const params = new URLSearchParams({\n    client_id: CLIENT_ID,\n    redirect_uri: REDIRECT_URI,\n    scope: 'vibe:ai',\n    state,\n  })\n  res.redirect(`https:\u002F\u002Fvibecode.bitrix24.com\u002Fv1\u002Fconnect\u002Fauthorize?${params}`)\n})\n\n\u002F\u002F 2. Vibecode returns the window here after consent or refusal\napp.get('\u002Fconnect\u002Fai\u002Fcallback', async (req, res) => {\n  const { code, state, error, error_description: reason } = req.query\n  const ticket = states.get(state)\n  if (!ticket) return res.status(400).send('Unknown state')\n  states.delete(state)\n\n  if (error) {\n    \u002F\u002F error_description carries the machine-readable reason code — see \"Denial after the consent screen\"\n    attempts.set(ticket, { status: 'denied', reason: reason ?? error })\n    return res.send(closeWindowPage('Access was not granted. You can close this window'))\n  }\n\n  const tokenRes = await fetch('https:\u002F\u002Fvibecode.bitrix24.com\u002Fv1\u002Fconnect\u002Ftoken', {\n    method: 'POST',\n    headers: { 'Content-Type': 'application\u002Fjson' },\n    body: JSON.stringify({\n      grant_type: 'authorization_code',\n      client_id: CLIENT_ID,\n      client_secret: CLIENT_SECRET,\n      code,\n      redirect_uri: REDIRECT_URI,\n    }),\n  })\n  const data = await tokenRes.json()\n  if (!tokenRes.ok) {\n    attempts.set(ticket, { status: 'denied', reason: data.error })\n    return res.send(closeWindowPage('The key was not received. You can close this window'))\n  }\n\n  await db.connections.upsert({\n    portalDomain: data.portal.domain,\n    apiKey: encrypt(data.api_key), \u002F\u002F a secret, encrypt it before storing\n    scopes: data.granted_scopes ?? data.scopes,\n  })\n  attempts.set(ticket, { status: 'ok' })\n  res.send(closeWindowPage('AI connected. You can close this window'))\n})\n\n\u002F\u002F 3. The frame asks for the attempt result\napp.get('\u002Fconnect\u002Fai\u002Fstatus', (req, res) => {\n  res.json(attempts.get(req.query.ticket) ?? { status: 'unknown' })\n})\n\nfunction closeWindowPage(text) {\n  return `\u003C!doctype html>\u003Cmeta charset=\"utf-8\">\u003Cp>${text}\u003C\u002Fp>\u003Cscript>window.close()\u003C\u002Fscript>`\n}\n```\n\n## Key points\n\n- The window opens synchronously in the click handler. The browser blocks a window opened after `await` as a pop-up.\n- The frame gets the result from its own server by `ticket`, not from the window: the window goes to other sites, and polling your own server does not depend on what happens to the window along the way.\n- `ticket` is not a secret: it reveals only the attempt state. The key stays on the server and never reaches the frame.\n- Polling is time-limited: the user may close the window without answering, and then nothing arrives at `redirect_uri`.\n- A refusal arrives in `error` and `error_description`, and the frame shows the reason code as is. The codes are covered in [Denial after the consent screen](\u002Fdocs\u002Fpartner-connect\u002Fauthorize#denial-after-the-consent-screen).\n\n## See also\n\n- [Start user authorization](\u002Fdocs\u002Fpartner-connect\u002Fauthorize)\n- [Exchange the code for an API key](\u002Fdocs\u002Fpartner-connect\u002Ftoken)\n- [App registration and scopes](\u002Fdocs\u002Fpartner-connect\u002Fregistration)\n- [Partner Connect](\u002Fdocs\u002Fpartner-connect)\n","2026-11-19",{},1795415493548]