# Connecting AI from an application inside Bitrix24

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

## How it works

1. The button in the frame opens a window at your server's address and passes a one-time attempt identifier, `ticket`, in the URL.
2. The server remembers the attempt and redirects the window to `/v1/connect/authorize` with the `vibe:ai` scope.
3. The user selects a Bitrix24 account and confirms access. Vibecode returns the window to your `redirect_uri`.
4. The server exchanges the code for a key, marks the attempt as finished and closes the window.
5. The frame polls the server by `ticket` and shows the result.

## Code in the application frame

```html
<button id="connect-ai" type="button">Connect AI</button>
<p id="connect-ai-status" role="status"></p>

<script>
  const button = document.getElementById('connect-ai')
  const statusLine = document.getElementById('connect-ai-status')

  button.addEventListener('click', () => {
    // The window opens right in the click handler: the browser blocks a window opened after await
    const ticket = crypto.randomUUID()
    const popup = window.open(
      `/connect/ai/start?ticket=${ticket}`,
      'vibe-connect-ai',
      'popup,width=640,height=760',
    )
    if (!popup) {
      statusLine.textContent = 'Allow pop-up windows for this application and click the button again'
      return
    }
    statusLine.textContent = 'Confirm access in the window that opened'
    waitForResult(ticket)
  })

  async function waitForResult(ticket) {
    const deadline = Date.now() + 10 * 60 * 1000 // 10 minutes for consent
    while (Date.now() < deadline) {
      await new Promise((resolve) => setTimeout(resolve, 2000))
      const res = await fetch(`/connect/ai/status?ticket=${ticket}`)
      const result = await res.json()
      if (result.status === 'ok') {
        statusLine.textContent = 'AI connected'
        return
      }
      if (result.status === 'denied') {
        statusLine.textContent = `AI not connected: ${result.reason}`
        return
      }
    }
    statusLine.textContent = 'Connection not finished. Click the button again'
  }
</script>
```

## Server code

The application server performs the same code exchange as in the [full example](/docs/partner-connect#full-example) and keeps the attempt state for the frame. `db` and `encrypt` are your storage and encryption. Register the address `https://yourapp.com/connect/ai/callback` with the client as a `redirect_uri`, and the `vibe:ai` scope must be among the client's scopes — see [Platform scopes](/docs/partner-connect/registration#platform-scopes).

```javascript
import express from 'express'
import crypto from 'node:crypto'

const app = express()
const attempts = new Map() // ticket → attempt result; in production, Redis or a database
const states = new Map() // state → ticket

const CLIENT_ID = process.env.PARTNER_CLIENT_ID
const CLIENT_SECRET = process.env.PARTNER_CLIENT_SECRET
const REDIRECT_URI = 'https://yourapp.com/connect/ai/callback'
const TICKET_RE = /^[0-9a-f-]{36}$/

// 1. The window opened by the button comes here and goes on to the consent page
app.get('/connect/ai/start', (req, res) => {
  const { ticket } = req.query
  if (typeof ticket !== 'string' || !TICKET_RE.test(ticket) || attempts.has(ticket)) {
    return res.status(400).send('Invalid connection attempt')
  }
  attempts.set(ticket, { status: 'pending' })

  const state = crypto.randomBytes(16).toString('hex')
  states.set(state, ticket)

  const params = new URLSearchParams({
    client_id: CLIENT_ID,
    redirect_uri: REDIRECT_URI,
    scope: 'vibe:ai',
    state,
  })
  res.redirect(`https://vibecode.bitrix24.com/v1/connect/authorize?${params}`)
})

// 2. Vibecode returns the window here after consent or refusal
app.get('/connect/ai/callback', async (req, res) => {
  const { code, state, error, error_description: reason } = req.query
  const ticket = states.get(state)
  if (!ticket) return res.status(400).send('Unknown state')
  states.delete(state)

  if (error) {
    // error_description carries the machine-readable reason code — see "Denial after the consent screen"
    attempts.set(ticket, { status: 'denied', reason: reason ?? error })
    return res.send(closeWindowPage('Access was not granted. You can close this window'))
  }

  const tokenRes = await fetch('https://vibecode.bitrix24.com/v1/connect/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      grant_type: 'authorization_code',
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      code,
      redirect_uri: REDIRECT_URI,
    }),
  })
  const data = await tokenRes.json()
  if (!tokenRes.ok) {
    attempts.set(ticket, { status: 'denied', reason: data.error })
    return res.send(closeWindowPage('The key was not received. You can close this window'))
  }

  await db.connections.upsert({
    portalDomain: data.portal.domain,
    apiKey: encrypt(data.api_key), // a secret, encrypt it before storing
    scopes: data.granted_scopes ?? data.scopes,
  })
  attempts.set(ticket, { status: 'ok' })
  res.send(closeWindowPage('AI connected. You can close this window'))
})

// 3. The frame asks for the attempt result
app.get('/connect/ai/status', (req, res) => {
  res.json(attempts.get(req.query.ticket) ?? { status: 'unknown' })
})

function closeWindowPage(text) {
  return `<!doctype html><meta charset="utf-8"><p>${text}</p><script>window.close()</script>`
}
```

## Key points

- The window opens synchronously in the click handler. The browser blocks a window opened after `await` as a pop-up.
- 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.
- `ticket` is not a secret: it reveals only the attempt state. The key stays on the server and never reaches the frame.
- Polling is time-limited: the user may close the window without answering, and then nothing arrives at `redirect_uri`.
- 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](/docs/partner-connect/authorize#denial-after-the-consent-screen).

## See also

- [Start user authorization](/docs/partner-connect/authorize)
- [Exchange the code for an API key](/docs/partner-connect/token)
- [App registration and scopes](/docs/partner-connect/registration)
- [Partner Connect](/docs/partner-connect)
