Blog

API Security: Integrating SecuriLayer Into Your InfrastructureAPI-безопасность: интеграция SecuriLayer в вашу инфраструктуру

Why API-first security mattersПочему API-first безопасность важна

Modern platforms are not monoliths. They are compositions of microservices, third-party integrations, serverless functions, and chat-based workflows. Security that lives only in a dashboard cannot protect what runs in a pipeline. API-first security means every check, every scan, every verdict is available as a programmatic call — consumable by bots, CI runners, SIEM collectors, and custom applications without human interaction.Современные платформы — это не монолиты. Это композиции микросервисов, сторонних интеграций, serverless-функций и чат-ориентированных workflow. Безопасность, которая существует только в дашборде, не может защитить то, что работает в пайплайне. API-first безопасность означает, что каждая проверка, каждый скан, каждый вердикт доступен как программный вызов — потребляемый ботами, CI-раннерами, SIEM-коллекторами и кастомными приложениями без участия человека.

SecuriLayer exposes a RESTful API that covers URL intelligence, phone number risk scoring, text content analysis, and webhook-driven event streaming. Every endpoint returns structured JSON with risk verdicts, reason codes, and confidence scores. This article is a technical deep-dive into authentication, integration patterns, code examples, webhook verification, architecture, and operational best practices.SecuriLayer предоставляет RESTful API, который охватывает URL-разведку, скоринг риска телефонных номеров, анализ текстового контента и webhook-driven event streaming. Каждый endpoint возвращает структурированный JSON с вердиктами риска, reason codes и confidence scores. Эта статья — техническое погружение в аутентификацию, паттерны интеграции, примеры кода, верификацию webhook, архитектуру и операционные best practices.

Authentication: Bearer tokensАутентификация: Bearer-токены

All API requests require a Bearer token in the Authorization header. Tokens are generated in the SecuriLayer dashboard under Settings → API Keys. Each token is scoped to a specific project and can be restricted to read-only or read-write operations. Tokens do not expire automatically, but you should rotate them on a regular schedule.Все API-запросы требуют Bearer-токен в заголовке Authorization. Токены генерируются в дашборде SecuriLayer в разделе Settings → API Keys. Каждый токен привязан к конкретному проекту и может быть ограничен правами read-only или read-write. Токены не истекают автоматически, но их следует ротировать по регулярному расписанию.

Authorization: Bearer sl_live_xxxxxxxxxxxxxxxxxxxx

Never embed tokens in client-side code. Store them in environment variables or secret managers (Vault, AWS Secrets Manager, GCP Secret Manager). If a token is compromised, revoke it immediately in the dashboard and generate a replacement.Никогда не встраивайте токены в клиентский код. Храните их в переменных окружения или менеджерах секретов (Vault, AWS Secrets Manager, GCP Secret Manager). Если токен скомпрометирован, немедленно отзовите его в дашборде и сгенерируйте замену.

Rate limitsRate limits

The API enforces per-token rate limits. Free tier: 60 requests per minute. Pro tier: 600 requests per minute. Enterprise: custom limits with burst allowance. Rate limit headers are returned with every response:API применяет rate limits на уровне токена. Free-тариф: 60 запросов в минуту. Pro-тариф: 600 запросов в минуту. Enterprise: кастомные лимиты с burst allowance. Заголовки rate limit возвращаются с каждым ответом:

X-RateLimit-Limit: 600
X-RateLimit-Remaining: 584
X-RateLimit-Reset: 1710500000

When you receive a 429 response, back off using exponential retry with jitter. Do not retry immediately — this amplifies load and may trigger temporary bans.При получении ответа 429 используйте exponential backoff с jitter. Не повторяйте запрос немедленно — это усиливает нагрузку и может вызвать временную блокировку.

Core endpointsОсновные endpoints

SecuriLayer API provides three primary analysis endpoints, each designed for a specific input type. All endpoints accept POST requests with JSON bodies and return structured verdicts.SecuriLayer API предоставляет три основных аналитических endpoint, каждый предназначен для определённого типа входных данных. Все endpoints принимают POST-запросы с JSON-телом и возвращают структурированные вердикты.

POST /v1/check/urlAnalyze a URL for phishing, malware, scam patterns, redirect chains, and domain reputation.Анализ URL на фишинг, малварь, скам-паттерны, redirect-цепочки и репутацию домена.
POST /v1/check/phoneScore a phone number for spam, fraud association, carrier anomalies, and disposable SIM risk.Скоринг телефонного номера на спам, связь с мошенничеством, аномалии оператора и риск одноразовой SIM.
POST /v1/check/textAnalyze free-form text for social engineering, urgency manipulation, drainer patterns, and scam templates.Анализ свободного текста на социальную инженерию, манипуляции срочностью, drainer-паттерны и скам-шаблоны.

Code examples: curlПримеры кода: curl

Check a URL for threats:Проверка URL на угрозы:

curl -X POST https://api.securilayer.dev/v1/check/url \
  -H "Authorization: Bearer $SL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://suspicious-example.com/claim-prize"}'

Check a phone number:Проверка телефонного номера:

curl -X POST https://api.securilayer.dev/v1/check/phone \
  -H "Authorization: Bearer $SL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"phone": "+1234567890", "context": "registration"}'

Analyze a text message:Анализ текстового сообщения:

curl -X POST https://api.securilayer.dev/v1/check/text \
  -H "Authorization: Bearer $SL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Urgent: connect your wallet now to claim airdrop before expiry!", "source": "telegram"}'

Code examples: PythonПримеры кода: Python

import os
import requests

API_KEY = os.environ["SL_API_KEY"]
BASE_URL = "https://api.securilayer.dev/v1"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}

# Check URL
resp = requests.post(f"{BASE_URL}/check/url", headers=HEADERS, json={
    "url": "https://suspicious-example.com/login"
})
verdict = resp.json()
print(f"Risk: {verdict['risk_level']}, Reasons: {verdict['reason_codes']}")

# Check phone
resp = requests.post(f"{BASE_URL}/check/phone", headers=HEADERS, json={
    "phone": "+44700000000",
    "context": "payment"
})
phone_result = resp.json()
print(f"Score: {phone_result['risk_score']}, Carrier: {phone_result['carrier']}")

# Analyze text with retry on rate limit
import time

def check_text(text, source="chat", retries=3):
    for attempt in range(retries):
        resp = requests.post(f"{BASE_URL}/check/text", headers=HEADERS, json={
            "text": text, "source": source
        })
        if resp.status_code == 429:
            wait = 2 ** attempt + random.random()
            time.sleep(wait)
            continue
        resp.raise_for_status()
        return resp.json()
    raise Exception("Rate limit exceeded after retries")

Code examples: JavaScript (Node.js)Примеры кода: JavaScript (Node.js)

const API_KEY = process.env.SL_API_KEY;
const BASE_URL = "https://api.securilayer.dev/v1";

async function checkUrl(url) {
  const resp = await fetch(`${BASE_URL}/check/url`, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ url }),
  });
  if (!resp.ok) throw new Error(`API error: ${resp.status}`);
  return resp.json();
}

async function checkPhone(phone, context = "default") {
  const resp = await fetch(`${BASE_URL}/check/phone`, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ phone, context }),
  });
  if (!resp.ok) throw new Error(`API error: ${resp.status}`);
  return resp.json();
}

async function analyzeText(text, source = "chat") {
  const resp = await fetch(`${BASE_URL}/check/text`, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ text, source }),
  });
  if (resp.status === 429) {
    const retryAfter = resp.headers.get("Retry-After") || 5;
    await new Promise(r => setTimeout(r, retryAfter * 1000));
    return analyzeText(text, source);
  }
  if (!resp.ok) throw new Error(`API error: ${resp.status}`);
  return resp.json();
}

// Usage
const result = await checkUrl("https://suspicious-example.com");
console.log(`Verdict: ${result.risk_level}`);

Integration patternsПаттерны интеграции

Real-time scanningСканирование в реальном времени

Intercept messages or user inputs at the application layer and call SecuriLayer before the content reaches other users. In Telegram bots, this means calling /v1/check/url and /v1/check/text inside the message handler before forwarding the message to the group. Latency is critical here: SecuriLayer API targets p95 latency under 200ms for URL checks and under 350ms for text analysis. Cache verdicts for repeated URLs using a TTL of 5-15 minutes to reduce redundant calls.Перехватывайте сообщения или пользовательский ввод на уровне приложения и вызывайте SecuriLayer до того, как контент достигнет других пользователей. В Telegram-ботах это означает вызов /v1/check/url и /v1/check/text внутри message handler до пересылки сообщения в группу. Латентность критична: SecuriLayer API нацелен на p95 latency менее 200ms для URL-проверок и менее 350ms для анализа текста. Кэшируйте вердикты для повторяющихся URL с TTL 5-15 минут для сокращения избыточных вызовов.

Batch processingПакетная обработка

For retroactive analysis of historical data — chat logs, CRM records, support tickets — use batch mode. Queue items and process them with controlled concurrency (10-20 parallel requests) to stay within rate limits. The batch pattern is useful for periodic audits: scan all URLs shared in a Telegram group over the past week and flag newly-detected threats against updated intelligence.Для ретроактивного анализа исторических данных — логов чатов, CRM-записей, тикетов поддержки — используйте пакетный режим. Ставьте элементы в очередь и обрабатывайте их с контролируемой конкурентностью (10-20 параллельных запросов) для соблюдения rate limits. Пакетный паттерн полезен для периодических аудитов: сканируйте все URL, расшаренные в Telegram-группе за последнюю неделю, и отмечайте новообнаруженные угрозы по обновлённой разведке.

SIEM enrichmentОбогащение SIEM

Feed SecuriLayer verdicts into your SIEM (Splunk, Elastic, Sentinel) as enrichment events. When a security alert fires on a suspicious URL or phone number, the SIEM enrichment pipeline calls SecuriLayer and appends risk_level, reason_codes, and confidence_score to the alert context. This eliminates manual triage for common threat patterns and reduces mean-time-to-respond.Передавайте вердикты SecuriLayer в вашу SIEM (Splunk, Elastic, Sentinel) как enrichment-события. Когда срабатывает алерт безопасности на подозрительный URL или телефонный номер, SIEM enrichment pipeline вызывает SecuriLayer и добавляет risk_level, reason_codes и confidence_score в контекст алерта. Это устраняет ручной triage для типовых паттернов угроз и сокращает mean-time-to-respond.

Webhook setup and HMAC-SHA256 verificationНастройка webhook и верификация HMAC-SHA256

SecuriLayer sends webhook events when threat intelligence updates, when monitored entities change risk status, or when policy-defined thresholds are breached. Webhooks are configured in the dashboard under Settings → Webhooks. Each webhook endpoint receives POST requests with a JSON payload and a signature header.SecuriLayer отправляет webhook-события при обновлении threat intelligence, при изменении статуса риска отслеживаемых сущностей или при нарушении пороговых значений, определённых политиками. Webhooks настраиваются в дашборде в разделе Settings → Webhooks. Каждый webhook endpoint получает POST-запросы с JSON payload и заголовком подписи.

Event types include:Типы событий включают:

  • threat.detected — new threat identified on a monitored URL or phone.threat.detected — новая угроза обнаружена на мониторимом URL или телефоне.
  • threat.resolved — previously flagged entity cleared after re-scan.threat.resolved — ранее отмеченная сущность очищена после повторного сканирования.
  • risk.escalated — risk level increased (e.g., SUSPICIOUS → DANGER).risk.escalated — уровень риска повышен (например, SUSPICIOUS → DANGER).
  • quota.warning — API usage approaching rate limit threshold.quota.warning — использование API приближается к порогу rate limit.

Every webhook request includes an X-SecuriLayer-Signature header containing an HMAC-SHA256 digest of the raw request body, signed with your webhook secret. Always verify this signature before processing the payload:Каждый webhook-запрос содержит заголовок X-SecuriLayer-Signature с HMAC-SHA256 дайджестом raw request body, подписанным вашим webhook secret. Всегда верифицируйте эту подпись перед обработкой payload:

import hmac
import hashlib

def verify_webhook(payload_bytes, signature, secret):
    expected = hmac.new(
        secret.encode("utf-8"),
        payload_bytes,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature)

If verification fails, respond with 401 and do not process the event. SecuriLayer retries failed deliveries (non-2xx responses) with exponential backoff: 1 minute, 5 minutes, 30 minutes, 2 hours, then hourly for up to 24 hours. After 24 hours of consecutive failures, the webhook is automatically disabled and an email notification is sent.Если верификация не прошла, ответьте 401 и не обрабатывайте событие. SecuriLayer повторяет неудачные доставки (non-2xx ответы) с exponential backoff: 1 минута, 5 минут, 30 минут, 2 часа, затем ежечасно до 24 часов. После 24 часов последовательных неудач webhook автоматически отключается и отправляется email-уведомление.

Architecture: embedding SecuriLayer in your stackАрхитектура: встраивание SecuriLayer в ваш стек

CI/CD pipeline integrationИнтеграция в CI/CD pipeline

Add a security gate stage to your CI/CD pipeline that scans URLs, domains, or configuration values before deployment. In a GitHub Actions workflow, call the SecuriLayer API in a step that checks all outbound URLs in your configuration files. If any URL returns a DANGER verdict, fail the pipeline and alert the team. This prevents deploying applications that reference compromised or malicious domains.Добавьте этап security gate в ваш CI/CD pipeline, который сканирует URL, домены или конфигурационные значения перед деплоем. В GitHub Actions workflow вызывайте SecuriLayer API на шаге, который проверяет все исходящие URL в конфигурационных файлах. Если какой-либо URL возвращает вердикт DANGER, pipeline завершается неудачей и команда получает алерт. Это предотвращает деплой приложений, которые ссылаются на скомпрометированные или вредоносные домены.

Chat platform botsБоты для чат-платформ

For Telegram, Discord, and Slack bots, the integration point is the message handler. Extract URLs, phone numbers, and suspicious text segments from incoming messages, call the appropriate SecuriLayer endpoint, and take action based on the verdict: delete the message, warn the user, restrict the sender, or escalate to moderators. The bot should handle API errors gracefully — if SecuriLayer is unreachable, queue the message for deferred analysis rather than silently passing it through.Для Telegram, Discord и Slack-ботов точка интеграции — message handler. Извлекайте URL, телефонные номера и подозрительные текстовые сегменты из входящих сообщений, вызывайте соответствующий endpoint SecuriLayer и предпринимайте действия на основе вердикта: удалите сообщение, предупредите пользователя, ограничьте отправителя или эскалируйте модераторам. Бот должен корректно обрабатывать ошибки API — если SecuriLayer недоступен, ставьте сообщение в очередь для отложенного анализа, а не пропускайте его молча.

Custom applicationsКастомные приложения

Any application that accepts user-generated content — marketplaces, forums, review platforms, dating apps — can embed SecuriLayer as a content safety layer. The typical architecture places SecuriLayer between the ingestion layer and the content store: user submits content, the application calls SecuriLayer, and only content that passes the safety threshold is stored and displayed. High-risk content is quarantined for human review.Любое приложение, принимающее пользовательский контент — маркетплейсы, форумы, платформы отзывов, дейтинг-приложения — может встроить SecuriLayer как слой безопасности контента. Типовая архитектура размещает SecuriLayer между слоем приёма данных и хранилищем контента: пользователь отправляет контент, приложение вызывает SecuriLayer, и только контент, прошедший порог безопасности, сохраняется и отображается. Контент высокого риска помещается в карантин для человеческого ревью.

Performance: latency and throughputПроизводительность: латентность и пропускная способность

SecuriLayer API is designed for inline security decisions where latency directly impacts user experience. Current benchmarks from production traffic:SecuriLayer API спроектирован для inline решений по безопасности, где латентность напрямую влияет на пользовательский опыт. Текущие бенчмарки из production-трафика:

/v1/check/urlp50: 85ms, p95: 180ms, p99: 320msp50: 85ms, p95: 180ms, p99: 320ms
/v1/check/phonep50: 60ms, p95: 140ms, p99: 250msp50: 60ms, p95: 140ms, p99: 250ms
/v1/check/textp50: 120ms, p95: 310ms, p99: 480msp50: 120ms, p95: 310ms, p99: 480ms

For throughput-sensitive workloads, use connection pooling (keep-alive), compress request/response bodies with gzip, and parallelize independent checks. A single Pro-tier token can sustain 10 requests per second continuously. For higher throughput, contact enterprise sales for dedicated capacity.Для workloads, чувствительных к пропускной способности, используйте connection pooling (keep-alive), сжимайте тела запросов/ответов с gzip и параллелизируйте независимые проверки. Один Pro-tier токен может устойчиво обрабатывать 10 запросов в секунду. Для более высокой пропускной способности свяжитесь с enterprise-продажами для выделенной мощности.

Security best practicesЛучшие практики безопасности

  • Key rotation: rotate API keys every 90 days. Maintain two active keys during rotation to avoid downtime. Revoke the old key only after confirming the new key works in all integration points.Ротация ключей: ротируйте API-ключи каждые 90 дней. Поддерживайте два активных ключа во время ротации, чтобы избежать простоев. Отзывайте старый ключ только после подтверждения работы нового во всех точках интеграции.
  • Scope limitation: create separate tokens for each service or environment. A CI/CD token should have read-only scope. A production bot token needs read-write but should be restricted to specific endpoints. Never use a single token across all environments.Ограничение scope: создавайте отдельные токены для каждого сервиса или окружения. CI/CD токен должен иметь read-only scope. Production bot токен требует read-write, но должен быть ограничен конкретными endpoints. Никогда не используйте один токен для всех окружений.
  • Audit logging: log every API call with timestamp, token ID (not the full token), endpoint, response code, and verdict. This creates an audit trail for compliance (SOC 2, ISO 27001) and helps debug integration issues. Store logs in append-only storage.Аудит-логирование: логируйте каждый API-вызов с timestamp, token ID (не полным токеном), endpoint, response code и вердиктом. Это создаёт аудит-trail для compliance (SOC 2, ISO 27001) и помогает отлаживать проблемы интеграции. Храните логи в append-only хранилище.
  • Network security: all API traffic must use TLS 1.2+. Pin the API certificate in high-security environments. Use IP allowlisting if your infrastructure has static egress IPs.Сетевая безопасность: весь API-трафик должен использовать TLS 1.2+. Закрепите сертификат API в высокозащищённых средах. Используйте IP allowlisting, если ваша инфраструктура имеет статические egress IP.
  • Error handling: never expose SecuriLayer API errors to end users. Log errors internally and return generic safety messages. Implement circuit breakers to prevent cascading failures if the API experiences degradation.Обработка ошибок: никогда не показывайте ошибки SecuriLayer API конечным пользователям. Логируйте ошибки внутренне и возвращайте общие сообщения о безопасности. Реализуйте circuit breakers для предотвращения каскадных сбоев при деградации API.
  • Webhook secret management: treat webhook secrets with the same care as API keys. Store in secret managers, rotate quarterly, and never log the raw secret value.Управление webhook secrets: относитесь к webhook secrets с такой же осторожностью, как к API-ключам. Храните в менеджерах секретов, ротируйте ежеквартально и никогда не логируйте raw значение секрета.

SummaryИтоги

API-first security transforms SecuriLayer from a tool into an infrastructure component. By integrating at the API level, you gain programmatic control over every security decision: real-time scanning in chat bots, batch analysis of historical data, SIEM enrichment for faster incident response, and CI/CD gates that prevent deploying compromised resources. The combination of low-latency endpoints, HMAC-verified webhooks, and structured verdicts makes SecuriLayer suitable for any architecture that values both security and performance.API-first безопасность превращает SecuriLayer из инструмента в инфраструктурный компонент. Интегрируясь на уровне API, вы получаете программный контроль над каждым решением безопасности: сканирование в реальном времени в чат-ботах, пакетный анализ исторических данных, обогащение SIEM для быстрого реагирования на инциденты и CI/CD-gates, предотвращающие деплой скомпрометированных ресурсов. Комбинация low-latency endpoints, HMAC-верифицированных webhooks и структурированных вердиктов делает SecuriLayer подходящим для любой архитектуры, которая ценит и безопасность, и производительность.

Get your API key and start integratingПолучите API-ключ и начните интеграцию