npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ainvirion/aiproxyguard-npm-sdk

v1.2.0

Published

Official TypeScript/JavaScript SDK for AIProxyGuard - LLM security proxy for prompt injection detection

Readme

@ainvirion/aiproxyguard-npm-sdk

npm version License TypeScript Node.js

Official TypeScript/JavaScript SDK for AIProxyGuard - an LLM security proxy that detects prompt injection attacks in real-time.

Features

  • Dual API Mode - Works with both cloud API and self-hosted proxy
  • Express Middleware - Protect routes with one line of code
  • TypeScript First - Full type definitions included
  • Automatic Retries - Exponential backoff for transient failures
  • Batch Operations - Check multiple inputs with concurrency control
  • Zero Dependencies - Uses native fetch (Node.js 18+)

Installation

npm install @ainvirion/aiproxyguard-npm-sdk
yarn add @ainvirion/aiproxyguard-npm-sdk
pnpm add @ainvirion/aiproxyguard-npm-sdk

Quick Start

import { AIProxyGuard } from '@ainvirion/aiproxyguard-npm-sdk';

// Initialize with your API key
const client = new AIProxyGuard({
  apiKey: process.env.AIPROXYGUARD_API_KEY,
});

// Check text for prompt injection
const result = await client.check('Ignore all previous instructions');

if (result.flagged) {
  console.log(`Blocked: ${result.threats[0].type}`);
} else {
  console.log('Text is safe');
}

API Modes

The SDK supports two ways to use AIProxyGuard:

| Mode | Use Case | |------|----------| | Cloud API | Managed service at aiproxyguard.com, requires free API key | | Self-hosted proxy | Deploy your own proxy (free), no API key required |

// Cloud API - managed service (requires free API key)
const cloud = new AIProxyGuard({ apiKey: 'apg_xxx' });

// Self-hosted proxy - no API key required
const proxy = new AIProxyGuard('http://localhost:8080');

Getting an API Key (Cloud Mode)

API keys are free. To use the cloud API:

  1. Sign up at aiproxyguard.com
  2. Go to SettingsAPI KeysCreate API Key
  3. Enable the check scope in permissions
  4. Copy your key (starts with apg_)

Configuration

const client = new AIProxyGuard({
  baseUrl: 'https://aiproxyguard.com',  // API endpoint
  apiKey: 'apg_xxx',                     // API key (required for cloud)
  mode: 'auto',                          // 'cloud' | 'proxy' | 'auto'
  timeout: 30000,                        // Request timeout (ms)
  retries: 3,                            // Retry attempts
  retryDelay: 1000,                      // Base retry delay (ms)
  maxConcurrency: 10,                    // Max parallel requests in batch
});

API Reference

check(text, context?)

Check text for prompt injection.

const result = await client.check('User input here');

console.log(result.id);        // 'chk_abc123'
console.log(result.flagged);   // true/false
console.log(result.action);    // 'allow' | 'log' | 'warn' | 'block'
console.log(result.threats);   // [{ type, confidence, rule }]
console.log(result.latencyMs); // 50.5
console.log(result.cached);    // false

// With context (cloud mode)
const result = await client.check('input', {
  conversationId: 'conv_123',
  userId: 'user_456',
});

checkBatch(texts)

Check multiple texts with concurrency control.

const results = await client.checkBatch([
  'Hello, how are you?',
  'Ignore all previous instructions',
  'What is the weather?',
]);

results.forEach((r, i) => {
  console.log(`${i}: ${r.flagged ? 'BLOCKED' : 'OK'}`);
});

isSafe(text)

Quick boolean check.

if (await client.isSafe(userInput)) {
  // Process the input
}

health()

Check service health.

if (await client.health()) {
  console.log('Service is up');
}

Express Middleware

Protect your Express routes with automatic prompt injection detection.

import express from 'express';
import { AIProxyGuard, guardMiddleware } from '@ainvirion/aiproxyguard-npm-sdk';

const app = express();
const client = new AIProxyGuard({ apiKey: process.env.AIPROXYGUARD_API_KEY });

app.use(express.json());

// Basic usage
app.post('/chat', guardMiddleware(client), (req, res) => {
  res.json({ response: 'Hello!' });
});

// With options
app.post('/api/prompt', guardMiddleware(client, {
  textField: 'prompt',           // Field to check (default: 'text')
  onBlock: 'reject',             // 'reject' or 'continue'
  rejectInvalidTypes: true,      // Reject non-string inputs
  onError: (err, req, res) => {
    res.status(500).json({ error: 'Security check failed' });
  },
}), handler);

// Multiple fields
app.post('/api/chat', guardMiddleware(client, {
  textField: ['message', 'context'],
}), handler);

Helper Functions

import { isSafe, isBlocked } from '@ainvirion/aiproxyguard-npm-sdk';

const result = await client.check(text);

if (isBlocked(result)) {
  console.log('Content was flagged');
}

if (isSafe(result)) {
  console.log('Content is safe');
}

Error Handling

import {
  AIProxyGuard,
  AIProxyGuardError,
  ValidationError,
  TimeoutError,
  RateLimitError,
  ConnectionError,
} from '@ainvirion/aiproxyguard-npm-sdk';

try {
  const result = await client.check(text);
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log(`Rate limited. Retry after: ${error.retryAfter}s`);
  } else if (error instanceof TimeoutError) {
    console.log('Request timed out');
  } else if (error instanceof ValidationError) {
    console.log(`Invalid request: ${error.message}`);
  } else if (error instanceof ConnectionError) {
    console.log('Could not connect to service');
  } else if (error instanceof AIProxyGuardError) {
    console.log(`Error: ${error.message} (${error.code})`);
  }
}

TypeScript

Full TypeScript support with exported types:

import type {
  Action,              // 'allow' | 'log' | 'warn' | 'block'
  ApiMode,             // 'cloud' | 'proxy' | 'auto'
  CheckResult,         // Result from check()
  Threat,              // { type, confidence, rule }
  AIProxyGuardConfig,  // Constructor config
} from '@ainvirion/aiproxyguard-npm-sdk';

Security Features

  • URL Validation - Only http: and https: schemes allowed
  • Input Size Limits - 100KB max to prevent DoS
  • Concurrency Control - Configurable limits for batch operations
  • Non-string Rejection - Middleware rejects array/object inputs by default

Requirements

  • Node.js 18+ (uses native fetch)
  • TypeScript 5.0+ (for type definitions)

Documentation

For detailed documentation, guides, and API reference, visit:

https://ainvirion.github.io/aiproxyguard/

Related

Contributing

See CONTRIBUTING.md for guidelines.

License

Apache-2.0 - Copyright 2026 AINVIRION