Composable, dependency-free protection for user-generated content in TypeScript and Node.js.
Quick start · Rules · Framework adapters · Security model · Testing · Contributing
UGC Guard is a small policy engine for comments, posts, profiles, chat messages, marketplace listings, and other user-generated text. It normalizes input, runs composable inspection rules, produces structured findings, and returns an allow, review, or block decision.
It was extracted as an independent open-source component for Zooplio, but it does not contain Zooplio application code, infrastructure, authentication logic, recommendation systems, private schemas, or production secrets.
Important
UGC Guard is a defensive layer, not a complete moderation or security system. It does not sanitize HTML, verify that a remote URL is safe, replace authorization, or replace edge-level rate limiting and human review.
Content pipelines usually grow into scattered regular expressions, duplicated middleware, and inconsistent error responses. UGC Guard keeps those policies explicit and testable:
- one normalized input shared by every rule;
- predictable risk scoring and decisions;
- strict TypeScript contracts for custom rules;
- timeouts and failure handling for third-party rules;
- privacy-conscious duplicate detection;
- safe-by-default Express and Fastify adapters;
- no runtime dependencies and no outbound network requests.
Until an npm release is published:
npm install github:Getris/ugc-guardAfter publication:
npm install @getris/ugc-guardimport { createCommunityGuard } from "@getris/ugc-guard/community";
const guard = createCommunityGuard({
maxLength: 2_000,
blockedHosts: ["known-abuse.example"],
blockedPhrases: ["configured policy phrase"],
enableDuplicateDetection: true,
enableRateLimit: true,
maxSubmissionsPerMinute: 20
});
const result = await guard.inspect({
text: userComment,
userId: currentUser.id,
ip: request.ip
});
switch (result.decision) {
case "allow":
await saveComment(result.normalizedText);
break;
case "review":
await sendToModerationQueue(result);
break;
case "block":
throw new Error("Content rejected");
}import {
createGuard,
DuplicateRule,
HtmlRule,
LengthRule,
LinkRule,
PhraseRule,
SecretRule,
SpamRule,
UnicodeRule
} from "@getris/ugc-guard";
const guard = createGuard({
reviewThreshold: 30,
blockThreshold: 60,
maxInputBytes: 64 * 1024,
ruleTimeoutMs: 1_000,
onRuleError: "finding",
rules: [
new LengthRule({ maxLength: 5_000 }),
new HtmlRule(),
new LinkRule({
allowedHosts: ["zooplio.com"],
blockedHosts: ["known-abuse.example"],
maxLinks: 5
}),
new PhraseRule({
phrases: ["configured policy phrase"],
matchMode: "word",
revealMatches: false
}),
new SecretRule(),
new SpamRule(),
new UnicodeRule(),
new DuplicateRule({ windowMs: 60_000 })
]
});Each rule returns one or more findings. The guard validates every finding, clamps its score to 0–100, sums the scores, and applies the configured thresholds.
| Decision | Default condition | Typical action |
|---|---|---|
allow |
Score below 30 |
Accept automatically |
review |
Score from 30 to 59 |
Queue for moderation |
block |
Score at least 60, or a critical finding |
Reject |
interface GuardResult {
allowed: boolean;
decision: "allow" | "review" | "block";
score: number;
riskLevel: "none" | "low" | "medium" | "high" | "critical";
normalizedText: string;
findings: GuardFinding[];
normalizations: NormalizationChange[];
rulesEvaluated: number;
durationMs: number;
}allowed is true for allow and review, and false only for block. Applications can choose to treat review more strictly.
| Rule | Detects | Notable safeguards |
|---|---|---|
LengthRule |
Too-short or too-long content | Grapheme-aware counting for emoji and combined characters |
HtmlRule |
HTML-like markup and active payload patterns | Detects event handlers, dangerous tags, encoded markup, script schemes, and SVG/HTML data URLs |
LinkRule |
Risky links and URL policy violations | Allowlists, blocklists, private IPs, local hosts, credentials, shorteners, Punycode, link-count limits |
PhraseRule |
Configured policy phrases | Whole-word or substring matching; matched text hidden by default |
SpamRule |
Repeated characters/tokens, uppercase abuse, symbol flooding | Validated thresholds and linear scans |
UnicodeRule |
Bidi controls, zero-width characters, malformed UTF-16, mixed-script look-alikes | Reports normalization separately from dangerous controls |
SecretRule |
Common private-key and token shapes | Reports only the credential type, never the suspected secret |
DuplicateRule |
Repeated content per identity | SHA-256 keys; raw content is not retained; pluggable storage |
RateLimitRule |
Excessive submissions per identity | Bounded in-memory sliding window for single-process deployments |
The adapter uses structural types, so Express is not a runtime dependency.
import express from "express";
import { createCommunityGuard } from "@getris/ugc-guard/community";
import { createExpressMiddleware } from "@getris/ugc-guard/express";
const app = express();
const guard = createCommunityGuard();
app.use(express.json());
app.post(
"/comments",
createExpressMiddleware(guard, {
field: "text",
exposeFindings: false,
replaceWithNormalized: true
}),
async (request, response) => {
await saveComment(request.body.text);
response.status(201).json({ ok: true });
}
);The complete server-side result is attached to request.ugcGuard. Findings are not returned to untrusted clients unless exposeFindings: true is explicitly enabled.
import { createCommunityGuard } from "@getris/ugc-guard/community";
import { createFastifyPreHandler } from "@getris/ugc-guard/fastify";
const guard = createCommunityGuard();
fastify.post("/comments", {
preHandler: createFastifyPreHandler(guard)
}, async (request) => {
return { text: request.body.text };
});import type { GuardRule } from "@getris/ugc-guard";
const noEmptyContent: GuardRule = {
name: "no-empty-content",
inspect(_input, context) {
if (context.normalizedText.length > 0) return null;
return {
rule: this.name,
code: "EMPTY_CONTENT",
message: "Content must not be empty.",
severity: "medium",
score: 40,
category: "content"
};
}
};Custom rules receive an AbortSignal. The guard can convert thrown errors and timeouts into non-sensitive system findings, ignore them, or rethrow them depending on onRuleError.
The project is designed around conservative boundaries:
- Input size is checked before rule execution.
- Each rule can be time-limited.
- Invalid scores from custom rules are clamped and sanitized.
- Middleware hides internal findings by default.
- Duplicate detection stores SHA-256 digests instead of raw content.
- URL inspection performs no DNS lookup and makes no outbound request.
- In-memory stores are bounded to reduce accidental memory growth.
Read the threat model, architecture notes, and maintainer security review before production use.
- Regex-based detection can produce false positives and false negatives.
HtmlRuledetects suspicious markup; it does not sanitize HTML.LinkRuleevaluates URL structure and local policy; it does not establish reputation or fetch the destination.SecretRulerecognizes selected token shapes; it is not a full secret-scanning engine.DuplicateRuleandRateLimitRuleuse in-memory defaults and are process-local.- Moderation decisions still require product policy, observability, appeals, and human review.
src/
├── adapters/ # Express and Fastify integration
├── core/ # Guard engine, types, normalization, validation
├── presets/ # Opinionated community preset
└── rules/ # Independent inspection rules
tests/ # Node.js test runner suites
docs/ # Architecture, configuration, and threat model
.github/ # CI, CodeQL, Dependabot, templates, ownership
Requirements: Node.js 22 or newer and npm.
npm ci
npm test
npm run test:coverage
npm run checkThe project currently has 34 automated tests covering the decision engine, failure isolation, rule timeouts, normalization, security rules, stateful rules, and framework adapters.
The package is pre-1.0. Minor releases may refine defaults while public type changes are documented in CHANGELOG.md. Security fixes target the latest release line.
Bug reports, focused pull requests, new test cases, and additional storage adapters are welcome. Start with CONTRIBUTING.md and the issue templates.
Source code is available under the MIT License.
“Zooplio” and associated branding may be trademarks of their respective owner. The MIT License covers the source code and does not grant permission to use Zooplio branding to imply endorsement.