Skip to content
rajdeepratanPublic

About

Veilgate is a PII & DLP redaction firewall for LLM pipelines — a hybrid regex fast-path plus TypeSafe Jev calibrated evaluation, reversible and mock-first.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Veilgate

License: MIT Node 22+ TypeScript strict ESM 114 tests passing mock-first

A PII & DLP redaction firewall for LLM pipelines — a hybrid regex fast-path + TypeSafe Jev (System One) calibrated evaluation. Mock-first, framework-agnostic, reversible.

Veilgate sits between your application and the cloud LLM you want to protect. It strips secrets and personal data out of every outbound payload, decides per span whether to allow, redact, reroute to a local model, or block — then re-hydrates the model's reply so the end user still sees the original values. The frontier model you are protecting only ever receives placeholders.

  • No API key to try it. Everything runs in deterministic mock mode by default.
  • Fail-closed. A Jev error never becomes a silent ALLOW; a missing reroute handler and an un-inspectable stream refuse the request rather than leak.
  • Reversible. Redactions are stored in an in-memory vault keyed by typed placeholders ([REDACTED_PII_1]) and restored on the response, exactly.

Table of contents

  1. The problem
  2. Why Jev (System One)
  3. Architecture
  4. The pipeline
  5. Packages
  6. Install & quickstart
  7. Try it with no API key
  8. Core API — veilgate
  9. The policy model
  10. Framework integrations
  11. CLI
  12. Mock mode vs. live mode
  13. Documentation
  14. Project layout
  15. Development
  16. Contributing
  17. Project status & honest limits
  18. Roadmap
  19. License

The problem

Enterprises want to use frontier LLMs (GPT-4o, Claude, Gemini) for support, log analysis, RAG ingestion and agents — but GDPR, HIPAA, SOC 2 and IP-preservation policies make it risky to ship raw context across a vendor boundary. Existing sanitizers each fail in a characteristic way:

Approach Mechanic Primary failure mode
Regex / static rules Patterns + dictionaries (e.g. Presidio defaults) Misses contextual PII ("the VP of Sales who moved to Austin"); false-positives on benign IDs
Small local NER spaCy / BERT-NER Needs dedicated compute; weak on novel domain secrets and multi-sentence context
LLM-as-a-firewall Prompt GPT-4o-mini / Haiku to sanitize 1.5–5 s of autoregressive latency; doubles token cost; prompt-injectable

Veilgate combines a zero-latency local regex fast-path for high-confidence secrets with Jev, a non-autoregressive calibrated model, for everything that needs semantic judgement.

Why Jev (System One)

Jev is TypeSafe AI's specialized evaluation model. It emits calibrated probabilities (P ∈ [0,1]) over many independent checks in a single parallel pass — no token-by-token generation.

The latency and throughput figures below are TypeSafe's published figures for Jev, not measurements of this library. The cost figure ($0.042 / MTok) matches DEFAULT_JEV_CONFIG.

  • Sub-200 ms latency — 20+ compliance/privacy/secret checks evaluated at once, fast enough to live inside a synchronous API gateway.
  • Calibrated probabilities (Noul / Choice / Score) — lets you set asymmetric risk thresholds per domain (e.g. redact any span where P(health) > 0.15).
  • No schema drift — structured outputs can't hallucinate malformed JSON.
  • Asymmetric cost — input billed per MTok, structural evaluations carry no per-token generation cost, so speculative evaluation across dozens of policy dimensions is orders of magnitude cheaper than LLM guardrails.

Veilgate evaluates five detectors per span:

Detector Primitive Evaluates
direct_pii Noul Explicit names, addresses, IDs
contextual_quasi_identifier Noul Combined indirect identifiers
credentials_or_secrets Noul API keys, tokens, passwords
regulated_health_or_financial Noul HIPAA / PCI data
sensitivity_severity Score 0.0–1.0 structural-context severity

Architecture

One framework-agnostic core engine (veilgate) wrapped in thin integrations, with dependencies running one way (integrations depend on the core, never the reverse — no cycles).

The trust boundary is the thing to understand. Two external services are different:

  • Jev is the evaluator. The core sends it the post-regex spans — which still contain the PII Jev must classify — or, in mock mode, sends nothing and uses fixtures. Jev is not the model you are shielding.
  • The destination cloud model (OpenAI / Anthropic / Gemini) is what you are protecting. It only ever receives the redacted payload ([REDACTED_*] placeholders). A REROUTE_LOCAL span is sent to a trusted local model in the clear instead.

Veilgate architecture — the trust boundary

See the docs site's Architecture page (site/src/content/docs/reference/architecture.md) for the full diagrams, and docs/slashforge/constitution.md for the invariants this shape enforces.

The pipeline

Every redact() call runs a four-stage hybrid pipeline:

Veilgate pipeline — the four-stage hybrid flow

When several rules fire for one span, the highest-priority action wins: BLOCK (3) > REDACT_AND_FORWARD (2) > REROUTE_LOCAL (1) > ALLOW (0).

Packages

A pnpm workspace monorepo. Every package is TypeScript (strict, ESM), targets Node 22+, builds with tsup, tests with vitest, and lints with tsc --noEmit. 114 tests across the repo.

Package npm name What it does Tests
packages/core veilgate Chunker, regex fast-path, Jev adapter + mock, policy engine, vault, redact()/rehydrate() 49
packages/policy veilgate-policy Compliance presets + declarative YAML/JSON policy loader 19
packages/middleware-proxy veilgate-proxy Framework-agnostic gateway + dependency-free Node HTTP handler 10
packages/middleware-vercel veilgate-ai-sdk Vercel AI SDK LanguageModelV2Middleware 10
packages/middleware-langchain veilgate-langchain LangChain Runnable wrapper 11
apps/cli veilgate-cli (veilgate) redact + bench commands 15

The core depends on nothing internal (only @typesafe-ai/sdk); every other package depends on veilgate via workspace:*. The CLI additionally depends on veilgate-policy for its presets. Framework deps are peer deps (ai ^7, @langchain/core ^0.3).

Install & quickstart

# core engine
npm install veilgate

# optional: presets + loader, and whichever integration you use
npm install veilgate-policy
npm install veilgate-proxy       # Express / Fastify / raw HTTP
npm install veilgate-ai-sdk       # Vercel AI SDK
npm install veilgate-langchain    # LangChain / LangGraph
npm install veilgate-cli          # the `veilgate` CLI (or just `npx veilgate-cli`)

Each package is independent — install only what you need. npm auto-installs a package's dependencies but not its peerDependencies:

You run You get Auto-pulled (deps) You must also install (peer)
npm install veilgate core only @typesafe-ai/sdk —
npm install veilgate-policy presets + loader veilgate + yaml —
npm install veilgate-proxy HTTP gateway veilgate —
npm install veilgate-ai-sdk Vercel AI SDK middleware veilgate ai (^7)
npm install veilgate-langchain LangChain Runnable veilgate @langchain/core (^0.3)
npm install veilgate-cli redact + bench CLI veilgate + veilgate-policy —

So npm install veilgate pulls just the core engine — an integration transitively pulls the core (and policy) for you; peer deps (ai, @langchain/core) you install yourself so your framework version wins.

All six packages are published on npm at v0.1.0.

import { redact, rehydrate } from "veilgate";

const r = await redact("My name is Alice Johnson.");

r.output;                       // "My name is [REDACTED_PII_1]."  ← what the model sees
r.blocked;                      // false
rehydrate(r.output, r.vault);   // "My name is Alice Johnson."     ← restored for the user

By default this is mock mode — deterministic, no network, no API key.

Try it with no API key

Two runnable examples ship in examples/:

pnpm demo     # one-shot: 7 scenarios across core, policy, and the proxy
pnpm serve    # a persistent mock proxy on http://127.0.0.1:8787 you can curl

With pnpm serve running, in another terminal:

curl -sX POST http://127.0.0.1:8787 -d '"email Alice Johnson, ssn 123-45-6789"'

The serve terminal logs what the model actually received — [REDACTED_PII_1] — proving the name and SSN never left the boundary. A credentials payload ("the admin password is hunter2") returns HTTP 403 and the model is never called at all.

Core API — veilgate

redact(payload, options?) → Promise<RedactResult>

type Payload = string | Record<string, unknown> | ChatMessage[];

interface RedactOptions {
  policy?: Policy;                 // default: DEFAULT_POLICY ("balanced")
  mode?: "mock" | "live";          // default: "mock"
  format?: "text" | "json" | "chat";   // default: inferred from the payload
  jev?: Partial<JevConfig>;        // model, baseUrl, apiKey, budgets, pricing
  client?: JevClient;              // inject a live client or a test double
}

interface RedactResult {
  output: Payload;        // same shape as the input, redactable spans replaced
  decisions: Decision[];  // every decision, in pipeline order (regex first, then Jev)
  vault: Vault;           // reversible placeholder → original map
  blocked: boolean;       // true if any span produced a BLOCK — do not forward
  stats: RedactStats;     // spans, regexRedactions, jevSpans, jevCalls, actions{}
}

redact() never calls your destination model and never throws on a block — it sets blocked: true and leaves the refusal to the caller. The output preserves the input shape: pass a string, get a string; pass a JSON object, get the same object with only sensitive field values replaced; pass a chat array, get the array with roles intact and only message content redacted.

rehydrate(text, vault) → string

Replaces every stored placeholder with its original value. It resolves nested placeholders (when the regex fast-path redacts a substring and a policy rule then redacts the enclosing span, the stored value itself contains a placeholder), looping until stable, so round-trips are exact.

Other exports

Export Purpose
Vault The reversible token store (store, get, entries)
chunk, inferFormat Split a payload into spans; detect its format
scanText, luhnValid Run the regex fast-path; Luhn card validation
evaluateSpans, DEFAULT_JEV_CONFIG The Jev adapter + its default config
evaluate The policy engine (span detectors → decision)
DEFAULT_POLICY, ACTION_PRIORITY The built-in balanced policy; action ordering

DEFAULT_JEV_CONFIG:

{
  model: "jev-latest",
  baseUrl: "https://api.typesafe.ai",
  maxTokensPerCall: 6000,
  inputPricePerMTok: 0.042,
}

The policy model

A policy is a named list of rules. Each rule compares one detector against a threshold and, if it fires, proposes an action:

interface PolicyRule {
  detector: DetectorName;   // e.g. "direct_pii"
  op: "gt" | "gte" | "lt" | "lte";
  threshold: number;        // 0..1
  action: "ALLOW" | "REDACT_AND_FORWARD" | "REROUTE_LOCAL" | "BLOCK";
  placeholderType?: string; // label used in the placeholder, default "PII"
}

When several rules fire for one span, the highest-priority action wins (ACTION_PRIORITY).

Presets — veilgate-policy

Four ready-made, deep-frozen presets. These are tunable starting points, not certified compliance — treat them as sensible defaults you adapt, not a legal guarantee.

Preset Posture
balanced Sensible default (same as core's DEFAULT_POLICY)
gdpr-strict Aggressive PII redaction
hipaa-safe-harbor Health/financial data redaction
soc2-secrets Credentials & secrets focus
import { redact } from "veilgate";
import { PRESETS, getPreset } from "veilgate-policy";

await redact(text, { policy: PRESETS["hipaa-safe-harbor"] });
await redact(text, { policy: getPreset("gdpr-strict") });

Declarative policies

Load a policy from YAML/JSON, optionally inheriting a preset:

import { loadPolicy } from "veilgate-policy";

const policy = loadPolicy(`
name: strict-secrets
extends: soc2-secrets
rules:
  - { detector: direct_pii, op: gt, threshold: 0.5, action: REDACT_AND_FORWARD, placeholderType: PII }
`);

validatePolicy / PolicyValidationError surface malformed rules early; definePolicy builds one in code with the same validation.

Framework integrations

HTTP proxy — veilgate-proxy

runGateway is framework-agnostic: it redacts the payload, calls your forward handler with the redacted text, re-hydrates the reply, and throws GatewayBlockedError instead of forwarding a BLOCK. A missing reroute handler when a span wants REROUTE_LOCAL is fail-closed (it throws rather than leak).

createHttpHandler wraps that into a dependency-free Node http handler, with a maxBodyBytes cap (default 1 MiB → 413); statuses are 200 / 403 (block) / 413 / 500:

import { createServer } from "node:http";
import { createHttpHandler } from "veilgate-proxy";

const handler = createHttpHandler({
  forward: async (redacted) => callCloudModel(redacted),  // only ever sees placeholders
  reroute: async (original) => callLocalModel(original),  // trusted on-prem path
});
createServer(handler).listen(8787);

Vercel AI SDK — veilgate-ai-sdk

createRedactionMiddleware returns a LanguageModelV2Middleware that redacts the prompt in wrapGenerate. wrapStream is fail-closed — it throws RedactionBlockedError rather than let streamText send an unredacted prompt.

import { wrapLanguageModel } from "ai";
import { createRedactionMiddleware } from "veilgate-ai-sdk";

const model = wrapLanguageModel({
  model: openai("gpt-4o"),
  middleware: createRedactionMiddleware({ policy: PRESETS["gdpr-strict"] }),
});

LangChain — veilgate-langchain

withRedaction wraps any invokable model in a RunnableLambda that redacts chat messages on the way in and re-hydrates on the way out (redactMessages / rehydrateMessage are exported too):

import { withRedaction } from "veilgate-langchain";

const safe = withRedaction(model, { policy: PRESETS["soc2-secrets"] });
await safe.invoke(messages);

CLI

usage: veilgate <command> [options]

commands:
  redact [text]        redact TEXT (or stdin when omitted) and print the result
  bench  <file.jsonl>  benchmark a policy against a labeled dataset

options:
  --policy <name>   balanced | gdpr-strict | hipaa-safe-harbor | soc2-secrets  (default: balanced)
  --mode <mode>     mock | live  (default: mock)
  --json            emit JSON instead of a human-readable report
npx veilgate-cli redact "email Alice Johnson, ssn 123-45-6789"
echo "the admin password is hunter2" | npx veilgate-cli redact --policy soc2-secrets
npx veilgate-cli bench apps/cli/fixtures/sample.jsonl --json

bench reports Precision, Recall, F1, and p50/p95 latency against a labeled .jsonl dataset, plus an estimated cost per 10k requests.

Mock mode vs. live mode

Mock (default) Live
Network None Calls the Jev API
API key Not needed Needed only when Veilgate builds the client
Determinism Fully deterministic fixtures Model-driven
Use for CI, local dev, demos, tests Production

Which to use: mock for dev, tests and CI. For production, switch to live mode — let Veilgate build the client from TYPESAFE_API_KEY, or inject your own. The built-in path is verified against the real @typesafe-ai/sdk by an integration test; inject your own client when you want full control over how the SDK client is constructed and authenticated.

await redact(text, { mode: "live" });                      // Veilgate builds the client; reads TYPESAFE_API_KEY
await redact(text, { mode: "live", jev: { apiKey } });     // …with the key passed explicitly instead
await redact(text, { mode: "live", client: myJevClient }); // …or inject your own client (full control)

Supplying the key — only when Veilgate builds the client (an injected client carries its own, and mock mode needs none). Never hardcode it; set TYPESAFE_API_KEY in the environment: copy .env.example → .env for local dev (.env is gitignored), or use your host's secret store (Vercel, Fly, a container env var) in production. Veilgate reads process.env and does not parse .env itself — load it with node --env-file=.env or dotenv if you keep one.

The regex fast-path runs before Jev in both modes, and live mode sends Jev only the post-regex payload — a regex-stripped secret is never leaked into Jev's ambient state (covered by a regression test, packages/core/test/redact.test.ts).

Documentation

The full documentation lives in site/ — an Astro docs site (Marker + Material You design) that renders the markdown in site/src/content/docs/**. It covers the introduction, install, the pipeline, modes, one page per package, the policy model, and an architecture reference with diagrams.

cd site
npm install
npm run dev     # → http://localhost:4322/veilgate
npm run build   # → dist/veilgate/ (+ Pagefind search index)

Each package also carries its own README.md.

Project layout

veilgate/
├── packages/
│   ├── core/                  # veilgate
│   ├── policy/                # veilgate-policy
│   ├── middleware-proxy/      # veilgate-proxy
│   ├── middleware-vercel/     # veilgate-ai-sdk
│   └── middleware-langchain/  # veilgate-langchain
├── apps/
│   └── cli/                   # veilgate-cli  (bin: veilgate)
├── examples/
│   ├── demo.mjs               # pnpm demo  — 7-scenario one-shot
│   └── serve.mjs              # pnpm serve — persistent mock proxy you can curl
├── site/                      # Astro documentation site (own package.json)
├── docs/slashforge/           # spec home: constitution · architecture · status · active/
└── .claude/                   # agents, rules, skills for the SlashForge workflow

Each package carries its own README.md, package.json, tsconfig.json, tsup.config.ts, vitest.config.ts, src/, and test/.

Development

pnpm install
pnpm build       # tsup across all packages
pnpm test        # vitest across all packages (114 tests)
pnpm lint        # tsc --noEmit across all packages
pnpm demo        # build + run examples/demo.mjs
pnpm serve       # build + run examples/serve.mjs

Requires Node 22+ and pnpm. The workspace globs packages/* and apps/*. The docs site in site/ is standalone (uses npm, not the workspace).

Verifying the live Jev path

pnpm test runs fully hermetically — mock mode plus a mocked @typesafe-ai/sdk contract test, with no key and no network, so it covers the live adapter's request/answer mapping in CI. The built-in live path is additionally covered by a key-gated integration test that calls the real Jev API. It is skipped unless TYPESAFE_API_KEY is set (so CI and ordinary pnpm test stay hermetic):

TYPESAFE_API_KEY=<funded-key> pnpm --filter veilgate test:integration

It asserts the behaviour end to end against the live model — a secret is blocked or redacted, PII drives a non-ALLOW action and re-hydrates exactly, and benign text passes through untouched — not merely that the call returned. A funded key is required (the run spends credits).

Contributing

This repo is set up for the SlashForge spec-driven workflow (the .claude/ tooling and docs/slashforge/ spec home):

  • Non-negotiables live in docs/slashforge/constitution.md — the core stays pure and fail-closed, Jev only ever sees the post-regex payload, redaction is reversible and exact, ESM/Node 22+/strict TS, test-first.
  • docs/slashforge/architecture.md and status.md describe the stack and what is in flight.
  • Run the full gate before a PR: pnpm lint && pnpm test && pnpm build (or /run-checks).
  • Work is test-first (red → green); new packages/adapters use the add-package / add-middleware recipes; docs pages use add-docs-page.

Project status & honest limits

  • Shipped and green: all six packages, 114 tests passing; the Astro docs site builds and serves.
  • Live Jev path verified — the built-in adapter is type-checked against @typesafe-ai/sdk and covered by an integration test against the real API; mock mode stays the deterministic default.
  • Presets are tunable defaults, not certified compliance.
  • Jev performance figures (latency, throughput) are TypeSafe's published numbers for the model, not benchmarks of this library.
  • Published on npm — all six packages at v0.1.0.

Roadmap

Delivered: core engine, policy presets + loader, HTTP proxy, Vercel AI SDK and LangChain middlewares, CLI + benchmark, docs site, npm release, and a verified live-mode adapter.

Not yet built (from the original monorepo plan):

  • MCP interceptor middleware (middleware-mcp) — tool-call parameter redaction
  • Redis-backed vault — durable/shared re-hydration across processes
  • Python port — veilgate on PyPI

License

MIT © 2026 Rajdeep Ratan. The root LICENSE file applies to the whole repository, and each package declares "license": "MIT".

About

Veilgate is a PII & DLP redaction firewall for LLM pipelines — a hybrid regex fast-path plus TypeSafe Jev calibrated evaluation, reversible and mock-first.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages