◉ Pulse
Getris avatar
#61 today

Getris/ugc-guard

TypeScript Library

Lightweight TypeScript library for validating and protecting user-generated content in web applications.

Created Jul 22, 2026
Stars
6
Today
+6
Forks
0
Quality
95/100
Momentum
20

README

Fetched from GitHub on Nov 7, 2026, 1:05 AM UTC · README.md

View original on GitHub

Third-party content — Open Source Pulse is not the owner of this repository.

This README belongs to Getris/ugc-guard and its contributors. We fetch it directly from the project’s public GitHub repository and display it for reference only. All text, code, images and trademarks remain the property of their respective authors. See the repository for its license terms. Copyright / takedown policy.

Zooplio UGC Guard

Composable, dependency-free protection for user-generated content in TypeScript and Node.js.

CI CodeQL Node.js 22+ TypeScript License: MIT Zero runtime dependencies

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.

Why this project exists

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.

Quick start

Install from GitHub

Until an npm release is published:

npm install github:Getris/ugc-guard

After publication:

npm install @getris/ugc-guard

Use the community preset

import { 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");
}

Compose a custom policy

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 })
  ]
});

Decision model

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.

Built-in rules

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

Framework adapters

Express-compatible middleware

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.

Fastify-compatible pre-handler

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 };
});

Custom rules

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.

Security model

The project is designed around conservative boundaries:

  1. Input size is checked before rule execution.
  2. Each rule can be time-limited.
  3. Invalid scores from custom rules are clamped and sanitized.
  4. Middleware hides internal findings by default.
  5. Duplicate detection stores SHA-256 digests instead of raw content.
  6. URL inspection performs no DNS lookup and makes no outbound request.
  7. In-memory stores are bounded to reduce accidental memory growth.

Read the threat model, architecture notes, and maintainer security review before production use.

Explicit limitations

  • Regex-based detection can produce false positives and false negatives.
  • HtmlRule detects suspicious markup; it does not sanitize HTML.
  • LinkRule evaluates URL structure and local policy; it does not establish reputation or fetch the destination.
  • SecretRule recognizes selected token shapes; it is not a full secret-scanning engine.
  • DuplicateRule and RateLimitRule use in-memory defaults and are process-local.
  • Moderation decisions still require product policy, observability, appeals, and human review.

Project structure

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

Development

Requirements: Node.js 22 or newer and npm.

npm ci
npm test
npm run test:coverage
npm run check

The project currently has 34 automated tests covering the decision engine, failure isolation, rule timeouts, normalization, security rules, stateful rules, and framework adapters.

Status and versioning

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.

Contributing

Bug reports, focused pull requests, new test cases, and additional storage adapters are welcome. Start with CONTRIBUTING.md and the issue templates.

License and trademark

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.

Rendered by GitHub from the repository’s README. Scroll to read the full file.
First trending

Jul 23, 2026

first spotted on the list

Best rank

#61

highest position reached

Appearances

1

times on the trending list

Quality score

95

out of 100

Momentum

20

trend strength indicator

Star velocity

0.06

stars per day since creation

Activity — last 60 days

daily counts, collected every 6 hours
  • Stars
  • Forks
  • Merged PRs
  • Issues
  • Closed issues

Collecting activity data since launch — check back in a few days.

Star history

total stars per snapshot

Not enough snapshots yet — check back soon.

Rank history

position on trending · lower is better

Not enough snapshots yet — check back soon.

3D card for your website

Live HTML card with a glass surface and pointer tilt. Paste the iframe on any website.

<iframe src="https://www.notionpulse.cc/embed/Getris/ugc-guard" width="420" height="240" style="border:0;max-width:100%;background:transparent" loading="lazy" title="Getris/ugc-guard — trending on Open Source Pulse"></iframe>

Stars badge

Show current stars in your README or profile. Auto-updates every 6 hours.

Getris/ugc-guard stars badge
Markdown
[![Getris/ugc-guard](https://www.notionpulse.cc/api/badge/Getris/ugc-guard.svg)](https://www.notionpulse.cc/repo/Getris/ugc-guard)
HTML
<a href="https://www.notionpulse.cc/repo/Getris/ugc-guard"><img src="https://www.notionpulse.cc/api/badge/Getris/ugc-guard.svg" alt="Getris/ugc-guard stars badge" /></a>

Repository of the Day

#61 Repository of the Day

Repository of the Week

#61 Repository of the Week

Repository of the Month

#61 Repository of the Month