API Reference

API Reference

Complete reference for integrating Yaan bot protection into your application.

Client-Side API

Installation

Include the Yaan script in your HTML:

<script
  src="https://cdn.yaan.com/apricot.js"
  data-sitekey="YOUR_SITEKEY"
  async
></script>

window.Apricot.requestToken()

Requests a verification token from Yaan after analyzing user behavior.

Returns: Promise<string>

Usage:

const token = await window.Apricot.requestToken();

Behavior:

  • Collects final telemetry data
  • Sends behavioral analysis to Yaan backend
  • Returns a one-time verification token (10-second validity)
  • Token expires after use or 10 seconds

Error Handling:

try {
  const token = await window.Apricot.requestToken();
  // Use token for form submission
} catch (error) {
  console.error("Yaan verification failed:", error);
  // Handle error (show message to user, etc.)
}

Common Errors:

ErrorCauseSolution
"Apricot not initialized"Script not loadedWait for script load or check sitekey
"Request failed: 401"Invalid sitekeyVerify sitekey in dashboard
"Request failed: 418"Session errorSession expired, reload page
"no global window"Not in browser contextOnly call in browser environment

Server-Side API

/sus - Token Verification Endpoint

Verifies a Yaan token and determines if the request should be blocked.

Endpoint: POST https://api.yaan.com/sus

Content-Type: application/json

Request Body

{
  diamond: string;        // The token from window.Apricot.requestToken()
  clientsecret: string;   // Your client secret (from dashboard)
  ip_addr: string;        // User's IP address
  email_domain?: string;  // Optional: email domain for additional filtering
}

Example Request:

{
  "diamond": "abc123def456...",
  "clientsecret": "cs_live_1234567890abcdef",
  "ip_addr": "192.168.1.100",
  "email_domain": "gmail.com"
}

Response

{
  block: boolean; // true = block user (bot), false = allow (human)
}

Example Response (Human):

{
  "block": false
}

Example Response (Bot):

{
  "block": true
}

Response Codes

CodeMeaning
200 OKToken verified successfully (check block field)
500 Internal Server ErrorServer error (retry with exponential backoff)

Important: The /sus endpoint returns 200 OK even for invalid/expired tokens. Always check the block field in the response. If block: true, deny the request.

Implementation Examples

async function verifyYaanToken(
  token,
  clientSecret,
  ipAddress,
  emailDomain = null,
) {
  try {
    const response = await fetch("https://api.yaan.com/sus", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        diamond: token,
        clientsecret: clientSecret,
        ip_addr: ipAddress,
        email_domain: emailDomain,
      }),
    });

    if (!response.ok) {
      throw new Error(`Yaan API error: ${response.status}`);
    }

    const result = await response.json();
    return !result.block;
  } catch (error) {
    console.error("Yaan verification error:", error);
    // Fail closed: if verification fails, block the request
    return false;
  }
}

Behavioral Telemetry

Yaan automatically collects behavioral telemetry every 10 seconds while the user is on your page. This happens transparently without any additional code.

What's Collected

Browser Fingerprinting:

  • Navigator properties (userAgent, language, platform, etc.)
  • Window dimensions and positioning
  • Device capabilities (touch support, memory, CPU cores)
  • Connection information (RTT, network type)

User Interactions:

  • Mouse movements (coordinates and timestamps)
  • Keyboard events (key presses and timestamps)
  • Click events

Document State:

  • Page focus and visibility
  • Scroll position
  • Referrer and current URL

All data is used exclusively for bot detection and is not shared with third parties. See our Privacy Policy for details.


Rate Limiting

Token Generation

  • Tokens can be requested once per session every ~10 seconds
  • Excessive requests may trigger bot detection
  • Tokens expire after 10 seconds or first use

Token Verification

  • No hard rate limit on /sus endpoint
  • Implement your own rate limiting on your backend
  • Recommended: 10 requests/second per IP

Example Rate Limiting (Node.js with express-rate-limit):

const rateLimit = require("express-rate-limit");

const yaanLimiter = rateLimit({
  windowMs: 1000, // 1 second
  max: 10, // 10 requests per second
  message: "Too many verification requests",
});

app.post("/api/submit", yaanLimiter, async (req, res) => {
  // Your verification logic...
});

Error Handling

Best Practices

  1. Fail Closed: If Yaan verification fails (network error, timeout, etc.), block the request by default
  2. Timeout: Set reasonable timeouts (5 seconds recommended)
  3. Retry Logic: Don't retry on client-side errors (400-499)
  4. Logging: Log all verification failures for monitoring

Example:

async function verifyWithFallback(token, clientSecret, ipAddress) {
  try {
    const isHuman = await verifyYaanToken(token, clientSecret, ipAddress);
    return isHuman;
  } catch (error) {
    console.error("Yaan verification failed:", error);
    // Log to your monitoring service
    logError("yaan-verification-failed", error);
    // Fail closed
    return false;
  }
}

Testing

Test Sitekeys

Use these special sitekeys for testing:

SitekeyBehavior
test_always_passAlways returns block: false
test_always_blockAlways returns block: true
test_randomRandomly blocks 50% of requests

Test sitekeys only work in development/staging environments, not production.

Example Test

describe("Yaan Integration", () => {
  it("should block bots", async () => {
    const token = "test-bot-token";
    const result = await verifyYaanToken(
      token,
      "test_always_block",
      "127.0.0.1",
    );
    expect(result).toBe(false);
  });

  it("should allow humans", async () => {
    const token = "test-human-token";
    const result = await verifyYaanToken(
      token,
      "test_always_pass",
      "127.0.0.1",
    );
    expect(result).toBe(true);
  });
});

Additional Resources