Skip to content

bitrix24/b24-ai-starter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Bitrix24 Application Starter Kit for AI Agents

This project helps developers build Bitrix24 applications with help from AI agents. It ships with a preconfigured code base plus a modular instruction system that explains how to extend the starter safely.

You act as the expert developer working on top of this repository: https://github.com/bitrix-tools/b24-ai-starter.

🎯 What You Get

  • Three backend options (PHP, Python, Node.js)
  • Nuxt 3 frontend with Bitrix24 UI Kit already wired up
  • Background workers for async workloads
  • Docker containers for quick bootstrap
  • SDK bundles & shared utilities for Bitrix24 API calls
  • Makefile with day-to-day commands
  • Documented API endpoints
  • πŸ“š Modular instructions for AI agents in instructions/
  • ♻️ Versioning support via scripts/create-version.sh and the extended dev-init wizard
  • πŸ” Authentication & security out of the box
  • 🎨 Bitrix24 UI Kit & JS SDK integration
  • πŸ‡ RabbitMQ service with stack-specific recipes

Need another backend stack? Create a folder under backends/ that follows the same structure and register it in Docker Compose.

πŸ€– Instruction System for AI Agents

  • πŸ“š Central knowledge hub: instructions/knowledge.md β€” language-agnostic entry point that links to specialized guides.

  • πŸ—οΈ Modular layout:

instructions/
β”œβ”€β”€ knowledge.md              # 🎯 Start here
β”œβ”€β”€ php/knowledge.md          # 🐘 PHP-specific guidance
β”œβ”€β”€ python/knowledge.md       # 🐍 Python-specific guidance
β”œβ”€β”€ node/knowledge.md         # 🟒 Node.js-specific guidance
β”œβ”€β”€ queues/                   # πŸ‡ Queues & background jobs
β”œβ”€β”€ frontend/knowledge.md     # 🎨 Frontend guidance
β”œβ”€β”€ bitrix24/                 # 🏒 Platform specifics
β”œβ”€β”€ versioning/               # ♻️ Version management
└── [stack]/[topic].md        # πŸ“‹ Deep dives
  • πŸ’‘ Reading workflow
    1. Start with knowledge.md.
    2. Pick the technology stack.
    3. Read [stack]/knowledge.md for language-specific tips.
    4. Open specialized files only when necessary.

♻️ Versioning Workflow

  • πŸ“„ Agent prompt: instructions/versioning/create-version-prompt.md β€” explains how to β€œcreate V2”, verify it, and switch versions.
  • πŸ›  Create: ./scripts/create-version.sh v2 clones the current project into versions/v2 and writes APP_VERSION=v2 to .env.
  • πŸ“Ÿ Make shortcuts: make create-version VERSION=v2 and make delete-version VERSION=v2 proxy the scripts (interactive when VERSION is omitted).
  • πŸ—‘ Delete: ./scripts/delete-version.sh v2 removes versions/v2 and clears APP_VERSION if needed.
  • πŸš€ Pick a copy: make dev-init can list versions/* and let you choose, or run DEV_INIT_VERSION=v2 make dev-init / ./scripts/dev-init.sh --version v2.
  • 🧹 Git hygiene: versions/ is tracked by default. Add it to .gitignore if a copy should stay local.

πŸ—οΈ Core Components

  • Required scopes: crm, user_brief, pull, placement, userfieldconfig
  • Tooling: Ngrok for public HTTPS tunnels, Docker for container orchestration

πŸ“ Repository Layout

b24-ai-starter/
β”œβ”€β”€ frontend/                 # Nuxt 3 + Bitrix24 UI Kit
β”œβ”€β”€ backends/
β”‚   β”œβ”€β”€ php/                  # Symfony + Bitrix24 PHP SDK
β”‚   β”œβ”€β”€ python/               # Django + b24pysdk
β”‚   └── node/                 # Express + Bitrix24 JS SDK
β”œβ”€β”€ infrastructure/
β”‚   └── database/             # PostgreSQL init scripts
β”œβ”€β”€ instructions/             # πŸ“š Modular AI guidance
β”‚   β”œβ”€β”€ knowledge.md
β”‚   β”œβ”€β”€ php/ | python/ | node/
β”‚   β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ versioning/
β”‚   β”œβ”€β”€ queues/
β”‚   └── bitrix24/
β”œβ”€β”€ logs/
β”œβ”€β”€ versions/
β”œβ”€β”€ README.md                 # πŸ€– Main AI prompt
└── docker-compose.yml

πŸš€ Quick Start

The starter already contains a working Bitrix24 app stub suitable for local development or marketplace-ready distribution.

Launch sequence

  1. Run the automatic initialization described below. It provisions an Ngrok domain, launches Docker, and configures .env. To verify the setup, open the technical domain in a regular browser β€” you’ll see an error in the browser stating that the page must be opened inside Bitrix24. That means everything is configured, but the app still needs Bitrix24 authorization tokens.

  2. Register the technical domain in your Bitrix24 portal settings or via https://vendors.bitrix24.com to continue development/testing.

    • Main URL: [technical-domain]/
    • Install URL: [technical-domain]/install
    • Scopes: crm, user_brief, pull, placement, userfieldconfig
  3. After adding the app you’ll get CLIENT_ID and CLIENT_SECRET. Put them into .env, then restart containers (make down && make dev-php, or make dev-python / make dev-node).

  4. Reinstall the app inside your portal to refresh tokens.

You can now build on top of the starter kit.

Automatic initialization (recommended)

make dev-init

The wizard will:

  • Ask for the Ngrok authtoken
  • Let you choose PHP/Python/Node backend
  • Remove unused backend folders
  • Configure environment variables
  • Request a public Ngrok domain
  • Launch Docker containers

Manual setup

cp .env.example .env

# PHP backend
make dev-php

# Python backend
make dev-python

# Node.js backend
make dev-node

# Stop everything
make down

# Production targets
make prod-php
make prod-python
make prod-node

# DB + frontend only
COMPOSE_PROFILES= docker-compose up database frontend

# Full stack
COMPOSE_PROFILES=php,worker docker-compose up -d

Production checklist

Configure these variables before going live:

  • JWT_SECRET β€” JWT encryption between frontend and backend
  • DB_USER, DB_PASSWORD, DB_NAME β€” PostgreSQL credentials
  • BUILD_TARGET=production β€” Nuxt prod build
  • DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL, DJANGO_SUPERUSER_PASSWORD β€” required for the Python backend

πŸ› οΈ Tech Stack

Frontend

  • Nuxt 3 (Vue 3, TypeScript)
  • Bitrix24 UI Kit (@bitrix24/b24ui-nuxt)
  • Bitrix24 JS SDK (@bitrix24/b24jssdk-nuxt)
  • Pinia, Vue I18n, TailwindCSS

Backend options

  • PHP: Symfony 7, Doctrine ORM, Bitrix24 PHP SDK
  • Python: Django, Bitrix24 Python SDK
  • Node.js: Express, pg, JWT, Bitrix24 JS SDK

Infrastructure

  • Docker & Docker Compose
  • PostgreSQL 17
  • Ngrok (public HTTPS tunnel)
  • Nginx (production ingress)

Backend notes

  • PHP: if api-php fails on Windows, resave backends/php/docker/php-fpm/docker-entrypoint.sh.
  • Python: Django admin lives at https://<VIRTUAL_HOST>/api/admin (DJANGO_SUPERUSER_* from .env).

πŸ›‘οΈ Dependency Security Scan

  • Run make security-scan β†’ executes scripts/security-scan.sh.
  • PHP audit: composer audit --locked --format=json in the php-cli container.
  • Frontend audit: pnpm audit --prod --json in the frontend container.
  • Reports land in reports/security/php-composer.json and reports/security/frontend-pnpm.json.
  • Non-zero exit when vulnerabilities are detected. Override via SECURITY_SCAN_ALLOW_FAILURES=1 make security-scan or ./scripts/security-scan.sh --allow-fail.
  • Nothing runs automatically; add the command to local checklists or CI manually.

πŸ›‘οΈ Security Checks

security-tests.sh orchestrator

  • make security-tests runs scripts/security-tests.sh, launching dependency audits, static analyzers and generic scanners (Semgrep OWASP Top 10, Gitleaks, Trivy) inside Docker.
  • The script auto-detects active backend (PHP/Python/Node) and the frontend, so no manual selection is required.
  • Profiles:
    • quick (default) β€” dependency audit + Semgrep.
    • full β€” quick profile plus phpstan/bandit/eslint, Gitleaks and Trivy.
    • custom β€” interactive step selection.
  • In interactive mode findings are reported as warnings so newcomers see results without stopping the flow; in --ci mode the same steps fail the run.
  • Reports are placed in reports/security/<timestamp>/.... Strict CI mode is enabled via --ci, and --allow-fail lets the script exit with 0 even if steps fail.
  • You can pass parameters via make: make security-tests SECURITY_TESTS_ARGS="--profile full --allow-fail".

Quick dependency audit

  • Run make security-scan to execute scripts/security-scan.sh.
  • The script runs composer audit --locked --format=json inside the php-cli container if backends/php exists.
  • For the frontend it executes pnpm audit --prod --json in the frontend container.
  • JSON reports go to reports/security/php-composer.json and reports/security/frontend-pnpm.json.
  • By default the script exits with a non-zero code when vulnerabilities are found; enable β€œsoft mode” with SECURITY_SCAN_ALLOW_FAILURES=1 make security-scan (or ./scripts/security-scan.sh --allow-fail) to always exit with 0.
  • The command runs on demand, so you can add it to local release checklists or call it in CI manually.

πŸ‡ Queues & RabbitMQ

  • make dev-init can automatically enable RabbitMQ and store credentials in .env.
  • Broker endpoints: AMQP 5672, management UI 15672 (profile queue).
  • Manual control: make queue-up, make queue-down.
  • Detailed guides:
    • Service & env vars β€” instructions/queues/server.md
    • PHP + Messenger β€” instructions/queues/php.md
    • Python + Celery β€” instructions/queues/python.md
    • Node.js + amqplib β€” instructions/queues/node.md

πŸ“š SDK Documentation

  • Bitrix24 JS SDK: use @bitrix24/b24jssdk-nuxt, see instructions/frontend/bitrix24-js-sdk.md.
  • Bitrix24 UI Kit: use @bitrix24/b24ui-nuxt, see instructions/frontend/bitrix24-ui-kit.md.
  • PHP SDK: see instructions/php/bitrix24-php-sdk.md.
  • Python SDK (b24pysdk): see instructions/python/bitrix24-python-sdk.md.

πŸ” Authentication & Security

JWT tokens

Every endpoint except /api/install and /api/getToken requires:

Authorization: `Bearer ${tokenJWT}`

Authentication flow

  1. App installation (/api/install)
    • Receives Bitrix24 data (DOMAIN, AUTH_ID, REFRESH_TOKEN, member_id, user_id, etc.)
    • Stores installation info
    • No JWT required
  2. Issue token (/api/getToken)
    • Accepts Bitrix24 auth payload
    • Generates a JWT (TTL = 1 hour)
    • Binds a Bitrix24 account
    • No JWT required
  3. Protected endpoints
    • Validate JWT via middleware/decorators
    • Extract bitrix24_account
    • Use SDK to call Bitrix24 API

πŸ”Œ API Endpoints

General guidelines

All protected requests must include a JWT header:

const { data, error } = await $fetch('/api/protected-route', {
  method: 'GET',
  headers: { Authorization: `Bearer ${someJWT}` }
});
  • Responses are JSON.
  • Errors use HTTP status 401, 404, or 500 and return { "error": "Internal server error" }.

/api/health

  • Method: GET
  • Response: { status: string, backend: string, timestamp: number }
  • Curl: curl http://localhost:8000/api/health

/api/enum

  • Method: GET
  • Response: string[]
  • Curl: curl http://localhost:8000/api/enum

/api/list

  • Method: GET
  • Response: string[]
  • Curl: curl http://localhost:8000/api/list

/api/install

  • Method: POST
  • Payload: DOMAIN, PROTOCOL, LANG, APP_SID, AUTH_ID, AUTH_EXPIRES, REFRESH_ID, member_id, user_id, PLACEMENT, PLACEMENT_OPTIONS
  • Response: { message: string }
curl -X POST http://localhost:8000/api/install \
  -H "Content-Type: application/json" \
  -d '{"AUTH_ID":"27exx66815","AUTH_EXPIRES":3600,"REFRESH_ID":"176xxxe","member_id":"a3xxx22","user_id":"1","PLACEMENT":"DEFAULT","PLACEMENT_OPTIONS":"{\"any\":\"6\/\"}"}'

/api/getToken

  • Method: POST
  • Payload: same as installation
  • Response: { token: string }
curl -X POST http://localhost:8000/api/getToken \
  -H "Content-Type: application/json" \
  -d '{"AUTH_ID":"27exx66815","AUTH_EXPIRES":3600,"REFRESH_ID":"176xxxe","member_id":"a3xxx22","user_id":1}'

Example: adding a new endpoint

PHP (Symfony):

#[Route('/api/my-endpoint', name: 'api_my_endpoint', methods: ['GET'])]
public function myEndpoint(Request $request): JsonResponse
{
    $jwtPayload = $request->attributes->get('jwt_payload');
    return new JsonResponse(['data' => 'value']);
}

Python (Django):

@xframe_options_exempt
@require_GET
@log_errors("my_endpoint")
@auth_required
def my_endpoint(request: AuthorizedRequest):
    client = request.bitrix24_account.client
    response = client._bitrix_token.call_method(
        api_method='method.name',
        params={'param': 'value'}
    )
    return JsonResponse({'data': 'value'})

Node.js (Express):

app.get('/api/my-endpoint', verifyToken, async (req, res) => {
  const jwtPayload = req.jwtPayload;
  res.json({ data: 'value' });
});

🎨 Frontend & Bitrix24 Integration

Key directories

  • app/pages/ β€” pages (index.client.vue, install.client.vue, other *.client.vue files)
  • app/stores/ β€” Pinia stores (api.ts, user.ts, appSettings.ts, userSettings.ts)
  • app/composables/ β€” shared logic (useAppInit.ts, useBackend.ts)
  • app/middleware/01.app.page.or.slider.global.ts β€” initializes the B24 frame for every page
  • app/layouts/ β€” default.vue, placement.vue, slider.vue, uf-placement.vue

Bitrix24 JS SDK

const { $initializeB24Frame } = useNuxtApp()
const $b24: B24Frame = await $initializeB24Frame()

const batch = await $b24.callBatch({
  appInfo: { method: 'app.info' },
  profile: { method: 'profile' }
})
const data = batch.getData()

const result = await $b24.callMethod('method.name', { param: 'value' })
const authData = $b24.auth.getAuthData()

await $b24.slider.openPath('/path/to/page')

API store

const apiStore = useApiStore()
await apiStore.init($b24)

const list = await apiStore.getList()
const enumData = await apiStore.getEnum()

const myMethod = async (): Promise<MyType> => {
  return await $api('/api/my-endpoint', {
    headers: { Authorization: `Bearer ${tokenJWT.value}` }
  })
}

Bitrix24 UI Kit

Components from @bitrix24/b24ui-nuxt are available automatically:

<template>
  <B24Card>
    <template #header>
      <h1>Title</h1>
    </template>

    <B24Button
      label="Action"
      color="air-primary"
      @click="handleClick"
    />

    <B24Input
      v-model="inputValue"
      placeholder="Type here"
    />

    <B24Badge
      label="Status"
      color="air-primary-success"
    />

    <B24Avatar
      :src="photoUrl"
      size="md"
    />
  </B24Card>
</template>

⚠️ Widgets, Events, Robots

If your feature involves widgets, events, or robots, review these docs first.

Widgets

Events

  • API reference
  • Register via event.bind during installation
  • Handle data at /api/app-events (public endpoint, no JWT)
  • Support both application/x-www-form-urlencoded and JSON

Robots

  • Instruction
  • Register via bizproc.robot.add
  • Handle data at /api/robot-handler (public endpoint, no JWT)
  • Accept every payload format Bitrix24 may send

Implementation tips

  1. Public endpoints don’t require JWT.
  2. Support both form-urlencoded and JSON payloads.
  3. Build proper OAuthPlacementData for the SDK.
  4. Register everything during installation (install.client.vue).

πŸ“š Additional Resources

Backend guides

Frontend guides

Platform guides

πŸš€ Development Recommendations

Adding new functionality

  1. Backend endpoint
    • Add a controller/view handler
    • Use middleware/decorators for authentication
    • Return JSON
  2. Frontend API method
    • Extend app/stores/api.ts
    • Use $api with a JWT header
    • Handle errors centrally
  3. Frontend page/component
    • Create .vue files under app/pages/ or app/components/
    • Use Bitrix24 UI Kit components
    • Connect to the API store

Best practices

  1. Error handling
    • Use processErrorGlobal from useAppInit
    • Log via $logger
    • Return actionable server errors
  2. Typing
    • Use TypeScript interfaces
    • Rely on AuthorizedRequest in Python and JWT payloads in PHP/Node
  3. State
    • Keep global state in Pinia
    • Use Vue 3 Composition API reactivity
    • Cache data where it makes sense
  4. Performance
    • Use batch REST calls when possible
    • Lazy-load heavy components
    • Optimize images and assets

🀝 Contributing

This starter kit exists to help AI agents build Bitrix24 apps faster. You can:

  1. Use the documentation to brief AI agents.
  2. Extend SDK samples.
  3. Add new backends under backends/.
  4. Improve documentation and instructions.

Important reminders for AI agents

  • Respect the architecture of the chosen backend (PHP/Python/Node.js).
  • Follow established project patterns.
  • Use Bitrix24 UI Kit components on the frontend.
  • Handle errors and typing properly.
  • Match the project’s coding style.

πŸ“„ License

Licensed under MIT. See LICENSE for details.

b24-ai-starter

About

Universal app starter for AI-powered development

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published