Arcjet JS

repository·main·Indexed 20 days ago

https://github.com/arcjet/arcjet-js

A runtime security platform for AI-powered applications providing real-time building blocks to detect prompt injection, authorize agent tool calls, redact sensitive data, and block bots or abuse. Includes SDKs for Astro (@arcjet/astro) and Bun (@arcjet/bun), as well as analysis tools for fingerprinting and email validation (@arcjet/analyze).

Tokens
99K
Snippets
329
Records
394
Agent score
71%

What's inside arcjet-js

  1. Overview of nosecone

    main
    Nosecone is a utility for easily adding and configuring security headers to protect your server. It can be used independently of Arcjet. For specific frameworks, specialized packages like @nosecone/next or @nosecone/sveltekit are available.
  2. What is Arcjet Guard and when to use it

    main

    Arcjet Guard (@arcjet/guard) is a lower-level API designed for scenarios where a standard HTTP request object is not available, such as AI agent tool calls or background tasks.

    Unlike framework-specific SDKs (like @arcjet/next) which are designed for HTTP request protection, Guard provides fine-grained, per-call control over rate limiting, prompt injection detection, and sensitive information detection without requiring a request object.

  3. Use DRY_RUN mode in Arcjet Guard

    main

    All guard rules accept a mode parameter. Setting mode: "DRY_RUN" allows you to evaluate rules and observe behavior without actually blocking requests. This is useful for tuning thresholds in production without affecting real traffic.

    const limitRule = tokenBucket({
      mode: "DRY_RUN",
      refillRate: 10,
      intervalSeconds: 60,
      maxTokens: 100,
    });
  4. Attach metadata to Arcjet decisions

    main

    The protect() method accepts a metadata object. This object allows you to attach any JSON-serializable value (including nested objects and arrays) to the decision for correlation and analytics.

    Constraints and Limits:

    • Format: Must be a plain object. Non-plain objects are ignored. Values like undefined, functions, BigInt, or circular references are dropped.
    • Server Limits: Up to 128 top-level keys, 4 KiB per serialized value, and 10 levels of nesting. Key names must be letters, digits, -, ., or _.
    • SDK Limits: The SDK drops keys if the total metadata for one request exceeds 768 KiB to prevent exceeding the 1 MiB protocol limit.
    • Security: Metadata is untrusted and not redacted. Do not put secrets or PII in it.
    • Precision: For integers above Number.MAX_SAFE_INTEGER, pass them as strings to avoid precision loss.
    const decision = await aj.protect(request, {
      metadata: {
        requestId,
        user: { id: userId, plan: "pro" },
        flags: { beta: true },
      },
    });
  5. Use @arcjet/guard for AI tool call protection

    main

    The @arcjet/guard package is specifically designed for AI guardrails. Instead of protecting an HTTP request, it is used to check text flowing into and out of LLM tool calls.

    It supports the localDetectSensitiveInfo rule, which can utilize the @arcjet/sensitive-info-rampart backend to detect names, addresses, and identifiers on-device. When a violation is detected, the response includes the detectedEntityTypes (e.g., GIVEN_NAME, SURNAME, SSN).

    # Example curl request to an @arcjet/guard route
    curl http://localhost:3000/api/arcjet-guard -H "Content-Type: text/plain" -X POST --data "Hi, my name is Alex Rivera and my SSN is 472-81-0094"
  6. Understand proxy detection and NO_PROXY

    main

    The @arcjet/transport package automatically detects standard proxy environment variables: HTTP_PROXY and HTTPS_PROXY, while respecting NO_PROXY.

    Runtime Behavior:

    • Node.js: Uses the built-in HTTP agent. Supports proxyHttpVersion configuration.
    • Bun and Deno: Uses the runtime's native fetch for proxying.
    • Edge Light and workerd: These runtimes do not support outbound proxy environment variables; no proxy is used.

    NO_PROXY Semantics: NO_PROXY accepts a comma- or space-separated list of host suffixes. It supports optional leading . or *. and optional :port. It supports * to bypass all hosts. Entries are matched as host names; IP/CIDR ranges are not supported. On Bun and Deno, the runtime's fetch applies NO_PROXY semantics.

  7. Enable HTTP/2 through a proxy on Node.js

    main

    By default, proxying on Node.js downgrades the connection from HTTP/2 to HTTP/1.1 because the built-in agent proxy support only works over HTTP/1.1. This can increase latency for concurrent requests.

    To maintain HTTP/2 end-to-end, set proxyHttpVersion: "2" in your TransportOptions. This opens an HTTP CONNECT tunnel to the proxy and performs the TLS handshake directly with the origin.

    Requirements and Caveats:

    • Node.js only: Bun, Deno, and edge runtimes do not support this setting.
    • Requires a tunneling (CONNECT) proxy: A proxy that terminates TLS and re-originates an HTTP/1.1 connection (MITM proxy) cannot preserve HTTP/2.
    • Proxy must not buffer the tunnel: If the proxy buffers tunneled bytes, it can add ~40ms of latency per round trip. Ensure your proxy (like Squid) sets TCP_NODELAY on CONNECT tunnels.
    const transport = createTransport("https://decide.arcjet.com", {
      proxyHttpVersion: "2"
    });
  8. Configure bot protection and categories

    main

    The detectBot rule allows you to manage which bots can access your endpoints. If you specify an allow list, all other bots are denied. You can allow bots by CATEGORY or by specific bot name.

    Available Categories: CATEGORY:ACADEMIC, CATEGORY:ADVERTISING, CATEGORY:AI, CATEGORY:AMAZON, CATEGORY:APPLE, CATEGORY:ARCHIVE, CATEGORY:BOTNET, CATEGORY:FEEDFETCHER, CATEGORY:GOOGLE, CATEGORY:META, CATEGORY:MICROSOFT, CATEGORY:MONITOR, CATEGORY:OPTIMIZER, CATEGORY:PREVIEW, CATEGORY:PROGRAMMATIC, CATEGORY:SEARCH_ENGINE, CATEGORY:SLACK, CATEGORY:SOCIAL, CATEGORY:TOOL, CATEGORY:UNKNOWN, CATEGORY:VERCEL, CATEGORY:WEBHOOK, CATEGORY:YAHOO.

    Verifying Bots: Bots claiming to be well-known crawlers (e.g. Googlebot) are verified by checking their IP address. If a bot fails verification, it is labeled as spoofed. Use isSpoofedBot from npm:@arcjet/inspect to check the results.

    import arcjet, { detectBot } from "npm:@arcjet/deno";
    import { isSpoofedBot } from "npm:@arcjet/inspect";
    
    const aj = arcjet({
      key: Deno.env.get("ARCJET_KEY")!,
      rules: [
        detectBot({
          mode: "LIVE",
          allow: [
            "CATEGORY:SEARCH_ENGINE",
            "OPENAI_CRAWLER_SEARCH",
          ],
        }),
      ],
    });
    
    // In your request handler:
    const decision = await aj.protect(request);
    
    if (decision.isDenied() && decision.reason.isBot()) {
      return Response.json({ error: "No bots allowed" }, { status: 403 });
    }
    
    // Verifies the authenticity of common bots using IP data.
    if (decision.results.some(isSpoofedBot)) {
      return Response.json({ error: "Forbidden" }, { status: 403 });
    }
  9. Use the Rampart on-device model backend

    main

    The Rampart backend (via @arcjet/sensitive-info-rampart) allows for on-device Named Entity Recognition (NER). Unlike the default WebAssembly engine, Rampart can detect a wider range of entities such as names, addresses, and government/financial identifiers while running entirely locally.

    Detection runs locally, and only a SHA-256 hash of the text is sent to Arcjet. The model is loaded once on the first request and reused subsequently.

    # Example curl request to a Rampart-enabled route
    curl http://localhost:3000/api/arcjet-rampart -H "Content-Type: text/plain" -X POST --data "Hi, my name is Alex Rivera and my SSN is 472-81-0094"