Skip to main content
RFC v1.0 BLUEPRINTS 10 Canonical Reference Architectures · Node.js, Python, MCP Stdio & Edge Gateways
ZTDS.ai Open AI Security Standard
10 CANONICAL PRODUCTION RECIPES · ZTDS RFC v1.0

AI, Agent & RAG Zero-Trust Integration Blueprints

Drop-in architectural patterns for enforcing Invariant 1 (0.00 B Cleartext Egress) and Invariant 2 (Bijective Local Restoration) across LangChain, LlamaIndex, CrewAI, Pinecone, Qdrant, Ollama, Envoy, and Model Context Protocol (MCP) pipelines in under 50 microseconds.

Bidirectional RAM Loop Theorem 1 & 2
1. Local Pre-Flight Interception
engine.sanitize(input, { profile })
2. Outbound WAN / Vector Dispatch
[NAME_1], [IBAN_1] · 0.00 B Raw PII
3. Local Bijective Rehydration
engine.restore(output, tokenMap)
4. Ephemeral Zeroization
engine.destroy() // CSPRNG wipe
Reference Architectures

10 Canonical AI, RAG & Gateway Integration Blueprints

Filter by architectural layer or copy production-ready Node.js, TypeScript, and Python middleware patterns.

BLUEPRINT 01 · LANGCHAIN LCEL TypeScript / Python

LangChain RunnableSequence Bijective Sanitization Middleware

Wraps any LangChain Expression Language (LCEL) chain in a stateful volatile closure. Raw user variables are sanitized in local process RAM prior to ChatOpenAI or ChatAnthropic invocation and restored locally before returning to the caller.

import { PrivacyScrubberEngine } from "@privacyscrubber/sdk";
import { RunnableLambda } from "@langchain/core/runnables";

const engine = new PrivacyScrubberEngine({ profile: "finance" });

export async function invokeZeroTrustChain(chain, rawPrompt) {
  const { sanitizedText, tokenMap } = engine.sanitize(rawPrompt);
  try {
    const llmResponse = await chain.invoke({ input: sanitizedText });
    return engine.restore(llmResponse.content, tokenMap);
  } finally {
    engine.destroy(tokenMap); // Invariant 3 CSPRNG zeroization
  }
}
Latency Overhead: 42.8 µs (p50) Invariant 1, 2 & 3 Verified
BLUEPRINT 02 · LLAMAINDEX RAG Python / Node.js

LlamaIndex Ingestion Transform & Query Postprocessor

Intercepts retrieved document nodes and query strings in local volatile RAM before LLM synthesis. Prevents sensitive clinical or legal records stored in internal knowledge bases from crossing the external API boundary.

from ztds import ZtdsSession

def zero_trust_rag_query(query_engine, raw_query: str, nodes: list) -> str:
    with ZtdsSession(profile="medical") as session:
        clean_query = session.sanitize(raw_query)
        for node in nodes:
            node.text = session.sanitize(node.text)
        response = query_engine.synthesize(clean_query, nodes=nodes)
        return session.restore(str(response))
    # Ephemeral tokenMap is automatically zeroized on context exit
Statute: HIPAA Safe Harbor 45 CFR § 164.514(b) Zero BAA Exposure
BLUEPRINT 03 · MCP STDIO FIREWALL Cursor / Claude Desktop

Model Context Protocol (MCP) Local Stdio Security Gateway

Executes as an air-gapped local child process over stdin/stdout. Exposes ztds_sanitize, ztds_restore, and ztds_audit to IDE agents so production secrets and database dumps never leak into cloud LLM context windows.

{
  "mcpServers": {
    "privacyscrubber-ztds": {
      "command": "npx",
      "args": ["-y", "@privacyscrubber/mcp-server"],
      "env": {
        "ZTDS_STRICT_MODE": "1",
        "ZTDS_DEFAULT_PROFILE": "devsecops"
      }
    }
  }
}
Transport: JSON-RPC 2.0 over Local Stdio Full MCP Spec →
BLUEPRINT 04 · VECTOR DB INGESTION Pinecone / Qdrant / Weaviate

Pre-Embedding Sanitization Gate for Managed Vector Stores

Raw PII embedded into high-dimensional vectors is vulnerable to embedding inversion attacks and turns your vector DB vendor into a GDPR Article 28 subprocessor. Sanitize chunks in RAM before calling embeddings.create().

const { sanitizedText, receipt } = engine.sanitize(rawDocumentChunk, {
  profile: "legal"
});

// 1. Generate embedding strictly over sanitized surrogate text
const vector = await openai.embeddings.create({
  model: "text-embedding-3-large",
  input: sanitizedText
});

// 2. Upsert to Pinecone with SHA-256 compliance receipt
await pineconeIndex.upsert([{
  id: chunkId,
  values: vector.data[0].embedding,
  metadata: { text: sanitizedText, ztds_sha256: receipt.sha256 }
}]);
Defense: Embedding Inversion Immunity GDPR Art. 28 Exempt
BLUEPRINT 05 · MULTI-AGENT CREWS CrewAI / AutoGen / LangGraph

Deterministic Coreference Across Multi-Agent Delegation

Maintains a single session-scoped tokenMap across an entire multi-agent task graph so Agent A (Researcher) and Agent B (Legal Reviewer) reference identical surrogates ([PARTY_1]) without ever accessing cleartext.

from ztds import ZtdsSession

with ZtdsSession(profile="legal") as crew_session:
    sanitized_brief = crew_session.sanitize(client_dossier)
    # All agents in the crew operate exclusively on surrogate tokens
    crew_result = legal_crew.kickoff(inputs={"brief": sanitized_brief})
    final_memo = crew_session.restore(crew_result.raw)
# Volatile dictionary wiped from RAM upon completion
Coreference Consistency: 100.00% FRE Rule 502(b) Safe
BLUEPRINT 06 · OLLAMA & VLLM Self-Hosted / VPC GPU

Zero-Trust Sanitization Before Shared VPC GPU Clusters

Even when running self-hosted open-weights models (Llama 3, Qwen, DeepSeek) via Ollama or vLLM, internal inference logs and shared GPU KV-caches create insider threat exposure. Sanitize at the application caller boundary.

const { sanitizedText, tokenMap } = engine.sanitize(rawLogPayload, {
  profile: "security"
});

const res = await fetch("http://localhost:11434/api/generate", {
  method: "POST",
  body: JSON.stringify({ model: "llama3.3:70b", prompt: sanitizedText, stream: false })
});
const { response } = await res.json();
const restoredAnalysis = engine.restore(response, tokenMap);
engine.destroy(tokenMap);
Protection: GPU KV-Cache Isolation Air-Gapped Compatible
BLUEPRINT 07 · ENVOY / KONG GATEWAY VPC Egress Perimeter

VPC Egress Gateway In-Memory Sanitization Filter

Enforces organization-wide ZTDS Invariant 1 at the Kubernetes ingress/egress controller layer without requiring third-party SaaS cloud DLP relays. Attaches cryptographic compliance headers (X-ZTDS-Receipt-SHA256) to every outbound LLM call.

// Outbound VPC Egress Interceptor
app.use("/v1/chat/completions", (req, res, next) => {
  const { sanitizedPayload, tokenMap, receipt } = engine.sanitizeChatMessages(
    req.body.messages,
    { profile: req.headers["x-ztds-profile"] || "general" }
  );
  req.body.messages = sanitizedPayload;
  req.ztdsTokenMap = tokenMap;
  res.setHeader("X-ZTDS-Receipt-SHA256", receipt.sha256);
  next();
});
Header: X-ZTDS-Receipt-SHA256 Zero SaaS Relay
BLUEPRINT 08 · STREAMING SSE Node.js TransformStream

Real-Time Server-Sent Events (SSE) Token Stream Rehydration

Rehydrates surrogate tokens across chunked BPE token streams in real time using a lightweight Web Streams TransformStream buffer, maintaining zero perceived time-to-first-token (TTFT) penalty.

const ztdsStream = engine.createRestoreStream(tokenMap, {
  zeroizeOnClose: true
});

const upstreamResponse = await fetch("https://api.openai.com/v1/chat/completions", {
  method: "POST",
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
  body: JSON.stringify({ model: "gpt-4o", messages: sanitizedMessages, stream: true })
});

return new Response(upstreamResponse.body.pipeThrough(ztdsStream), {
  headers: { "Content-Type": "text/event-stream" }
});
TTFT Overhead: < 0.1 ms Auto-Zeroize on Stream End
BLUEPRINT 09 · MULTIMODAL VISION HTML5 Canvas / OffscreenCanvas

Multimodal OCR & 6px Safety-Padded Pixel Burn-In

Gaussian blur and pixelation filters are mathematically reversible by modern vision models. ZTDS mandates solid-fill (#000000) bounding-box pixel destruction with a 6px anti-bleed margin in local canvas memory prior to Vision LLM upload.

const { sanitizedBlob, frameReceipt } = await engine.sanitizeImageInRAM(fileBlob, {
  profile: "medical",
  paddingPx: 6,
  fillColor: "#000000",
  stripExifMetadata: true
});
// frameReceipt.sha256 attests irreversible pixel burn-in before Vision API call
Benchmark: BENCH-MM-01..05 (100% LPR) View Vision Benchmarks →
BLUEPRINT 10 · CHROME MANIFEST V3 Browser V8 Content Script

Zero-Server Browser DOM Input Interceptor for Web AI Chats

Intercepts prompt submission events directly inside the browser tab on ChatGPT, Claude, and Gemini. Scrubs sensitive entities in local V8 memory and dispatches native InputEvent updates before the web app initiates its fetch() call.

document.addEventListener("keydown", (event) => {
  if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
    const promptEl = document.querySelector("textarea, [contenteditable='true']");
    if (!promptEl) return;
    const { sanitizedText, tokenMap } = engine.sanitize(promptEl.value || promptEl.innerText);
    window.__ztdsActiveTokenMap = tokenMap;
    if (promptEl.value !== undefined) promptEl.value = sanitizedText;
    else promptEl.innerText = sanitizedText;
    promptEl.dispatchEvent(new Event("input", { bubbles: true }));
  }
}, true);
Reference App: PrivacyScrubber Extension View in Registry →
Enterprise Production Deployment

Deploy Ready-to-Run Certified Engines with 30 Industry Profiles

While the open-source @ztds/core and Python ztds packages provide the Apache 2.0 reference baseline for universal consumer PII, enterprise engineering teams deploy PrivacyScrubber (@privacyscrubber/sdk & @privacyscrubber/mcp-server) for 30 specialized vertical profiles and offline Ed25519 node licensing.

Architecture Q&A

Frequently Asked Questions on AI & RAG Sanitization Blueprints

How do you prevent PII leakage in LangChain and LlamaIndex RAG pipelines without breaking LLM context? ↓
By inserting an in-RAM ZTDS sanitization middleware step before prompt serialization or vector chunking, raw identifiers are replaced with deterministic typed surrogates ([NAME_1], [IBAN_1]) inside host process memory. The upstream LLM reasons over intact grammatical structures, and the local postprocessor restores original cleartext values from the ephemeral tokenMap before returning the response.
Should vector embeddings in Pinecone, Qdrant, or Weaviate be generated before or after ZTDS sanitization? ↓
To satisfy ZTDS Invariant 1 and GDPR Article 28 subprocessor exclusion, document chunks must be sanitized in local volatile memory prior to calling external embedding APIs (such as text-embedding-3-large) or indexing into managed vector databases. Embedding sanitized text prevents vector inversion attacks and eliminates PII storage inside third-party vector clusters.
How does ZTDS handle streaming Server-Sent Events (SSE) when restoring surrogate tokens in real time? ↓
When an LLM streams token chunks via Server-Sent Events (SSE), a bracket-aware sliding buffer holds characters locally only when an opening bracket ([) is detected until the closing bracket (]) arrives. Complete surrogate tokens ([EMAIL_1]) are resolved against the local volatile tokenMap in sub-millisecond time without delaying normal prose streaming.
How does the Model Context Protocol (MCP) stdio firewall protect Cursor, Claude Desktop, and IDE agents? ↓
The ZTDS MCP server executes locally over standard input/output (stdio) on the developer workstation. Before an IDE agent forwards database rows, log files, or code snippets to a cloud model, it invokes ztds_sanitize in RAM, transmits only surrogate tokens over HTTPS, and invokes ztds_restore locally when unmasked values are required.
What is the difference between the open-source @ztds/core reference baseline and the commercial @privacyscrubber/sdk engine? ↓
The open-source @ztds/core and ztds Python packages provide the Apache 2.0 reference implementation for universal consumer PII and RFC v1.0 invariant verification. Enterprise production workloads requiring 30 specialized industry profiles (HIPAA Safe Harbor, SWIFT/IBAN FinTech, FRE 502 Legal, Multimodal Burn-In) and air-gapped Ed25519 node licensing deploy @privacyscrubber/sdk.