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

@martin_yeung/llm-up-guardrail

v0.1.2

Published

Zero-dependency guardrail library for LLM applications with built-in Anti-Scam detection

Readme

@martin_yeung/llm-up-guardrail

Zero-dependency TypeScript guardrail library for LLM applications, with built-in Anti-Scam detection.

With a dedicated multi-layer Anti-Scam engine as its primary differentiator.

  • Prompt-injection & jailbreak detection (EN + 中文)
  • PII / API-key detection & redaction (regex + Shannon entropy)
  • Toxicity & self-harm filtering
  • URL safety scanner (shortener / punycode / brand look-alike / IP / userinfo)
  • Anti-Scam multi-layer: patterns → LLM semantic → behavioral (multi-turn)
  • LLM adapters for OpenAI & Anthropic (optional peer-deps)
  • Framework integrations: Express middleware & LangChain-style wrapper
  • Zero runtime dependencies, ESM + CJS, full TypeScript types
  • ✅ 100 % unit-tested

🚀 Quick Start

npm install @martin_yeung/llm-up-guardrail
import { createGuardrail } from '@martin_yeung/llm-up-guardrail';

const engine = createGuardrail();          // 1
const r = await engine.checkInput(userMsg); // 2
if (r.blocked) return respond('Sorry, suspected fraudulent content detected, unable to be processed.'); // 3

That's it. All five default guards (injection, pii, toxicity, url, antiScam) are active.


🧱 Architecture

                    ┌──────────────────────┐
   userInput ──────►│   GuardrailEngine    │
                    │  (facade / pipeline) │
                    └───────────┬──────────┘
                                │
   ┌────────────┬───────────────┼────────────────┬──────────────┐
   ▼            ▼               ▼                ▼              ▼
InjectionGuard  PIIGuard   ToxicityGuard  URLSafetyScanner  AntiScamGuard
   │                                                          │
   │                                                          ├─ L1 Patterns
   │                                                          ├─ L2 LLM Adapter
   │                                                          └─ L3 Behavioral (SessionStore)

Each Guard implements:

interface Guard {
  name: string;
  check(input: string, ctx: GuardContext): Promise<CheckResult>;
}

The engine aggregates findings, computes a severity (low | medium | high | critical), a combined score ∈ [0,1], and returns a sanitized version of the text.


🛡️ Guards

InjectionGuard

Detects ignore previous instructions, DAN/god-mode, system-prompt exfiltration, role hijacking, delimiter breaks, encoding bypass. Supports EN & 中文.

PIIGuard

  • Emails, phones, credit cards, SSN, ID card
  • API keys: OpenAI, Anthropic, AWS, GitHub, Google
  • Generic high-entropy tokens (Shannon entropy)
  • Optional auto-redaction ([REDACTED:email])

ToxicityGuard

Direct threats, self-harm, illicit weapons manufacturing. Kept conservative to avoid false positives — extend with extraRules for custom lists.

URLSafetyScanner

  • URL shorteners (bit.ly, t.co, ...)
  • Suspicious TLDs (.zip .xyz .top ...)
  • IP-address URLs
  • Punycode / homoglyph (xn--)
  • user@host userinfo tricks
  • Brand look-alikes (apple.com.security-verify.xyz)
  • Pluggable remote reputation checker (Google Safe Browsing, VirusTotal, etc.)

AntiScamGuard ⭐ (the flagship)

Three-layer detection:

  1. Pattern matching — 20+ curated rules across 10 categories: impersonation, urgency_pressure, fake_winnings, investment_fraud, romance_scam, phishing, tech_support_scam, job_scam, extortion, payment_redirection (BEC) — all bilingual (EN + 中文).
  2. LLM semantic analysis — escalates ambiguous / high-risk text to an LLM adapter (OpenAI, Anthropic, or mock).
  3. Behavioral / multi-turn — via SessionStore, detects:
    • Repeated payment-account changes
    • Escalating urgency across turns
    • Multiple distinct crypto/bank destinations

🧪 Recipes

Redact PII automatically

import { GuardrailEngine, PIIGuard } from '@martin_yeung/llm-up-guardrail';
const engine = new GuardrailEngine({ guards: [new PIIGuard({ redact: true })] });
const r = await engine.checkInput('Email me at [email protected], key sk-abc...def');
console.log(r.sanitized); // "Email me at [REDACTED:email], key [REDACTED:api_key]"

Semantic scam analysis via OpenAI

import { createGuardrail, createOpenAIAdapter } from '@martin_yeung/llm-up-guardrail';
const llm = createOpenAIAdapter({ model: 'gpt-4o-mini' });
const engine = createGuardrail({ llm });

Behavioral / multi-turn detection

import { createGuardrail, InMemorySessionStore } from '@martin_yeung/llm-up-guardrail';
const store = new InMemorySessionStore();
const engine = createGuardrail();

const history = store.recent('user-42');
const r = await engine.checkInput(msg, { sessionId: 'user-42', history });
store.append('user-42', { role: 'user', content: msg });

Express middleware

import { createGuardrail, guardrailMiddleware } from '@martin_yeung/llm-up-guardrail';
const engine = createGuardrail();
app.post('/chat', guardrailMiddleware(engine, { field: 'message' }), handler);

Wrap any chat function (LangChain-style)

import { createGuardrail, wrapChat } from '@martin_yeung/llm-up-guardrail';
const engine = createGuardrail();
const safeChat = wrapChat(engine, (input) => llm.invoke(input));
const { output, blocked } = await safeChat(userMsg);

Add your own scam patterns

import { AntiScamGuard } from '@martin_yeung/llm-up-guardrail';
const guard = new AntiScamGuard({
  extraRules: [{
    id: 'custom_utility_fee', category: 'utility_scam',
    description: 'Fake electricity bill',
    pattern: '(?:overdue|逾期).{0,20}(?:electricity|water|電費|水費)',
    severity: 'high', weight: 0.85
  }]
});

Custom URL reputation

import { URLSafetyScanner } from '@martin_yeung/llm-up-guardrail';
const scanner = new URLSafetyScanner({
  remoteChecker: async (url) => {
    const rsp = await fetch(`https://mysafeapi/lookup?u=${encodeURIComponent(url)}`);
    return rsp.json();
  }
});

📊 EngineResult

interface EngineResult {
  blocked: boolean;
  severity: 'low' | 'medium' | 'high' | 'critical';
  score: number;                 // 0..1
  findings: Finding[];
  sanitized: string;
  timings: Record<string, number>; // per-guard ms
  totalMs: number;
}

🗂️ Project Layout

src/
├── engine.ts              # GuardrailEngine (facade)
├── factory.ts             # createGuardrail(...) convenience
├── types/                 # Core interfaces
├── utils/                 # entropy, regex cache, severity, logger
├── patterns/              # Curated rule libraries
├── guards/                # InjectionGuard, PIIGuard, ToxicityGuard,
│                          # URLSafetyScanner, AntiScamGuard, PatternGuard base
├── adapters/              # OpenAI, Anthropic, Mock LLM adapters
├── context/               # SessionStore (in-memory, pluggable)
└── integrations/          # Express middleware, LangChain wrapChat
tests/                     # Vitest unit tests
examples/                  # Runnable examples

🧑‍💻 Development

npm install
npm run test         # vitest
npm run test:coverage
npm run build        # tsup -> dist/ (ESM + CJS + .d.ts)
npm run example:basic
npm run example:multi-turn

📜 License

AGPL-3.0-only © 2026