@martin_yeung/llm-up-guardrail
v0.1.2
Published
Zero-dependency guardrail library for LLM applications with built-in Anti-Scam detection
Maintainers
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-guardrailimport { 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.'); // 3That'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@hostuserinfo tricks- Brand look-alikes (
apple.com.security-verify.xyz) - Pluggable remote reputation checker (Google Safe Browsing, VirusTotal, etc.)
AntiScamGuard ⭐ (the flagship)
Three-layer detection:
- 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 + 中文). - LLM semantic analysis — escalates ambiguous / high-risk text to an LLM adapter (OpenAI, Anthropic, or mock).
- 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
