Skip to content
プロジェクト

概要

Prevent accidental PII leakage in LLM prompts before they hit the model.

AI・機械学習

この数値の測り方

計測したスター増加

24時間
0
7日間
+1
15日間
+3
1か月
履歴を収集中

期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。

Rehydra

PII security for AI workflows, coding agents and browser workloads.
Detects, replaces, encrypts, and rehydrates back when needed.

Documentation · Issues

npm license codecov

Sponsored by
ZWRM

npm i rehydra · npm i @rehydra/cli · npm i @rehydra/opencode

The Problem

When you send code, messages, or documents through an LLM, real names, emails, and API keys go with them. Existing anonymizers strip PII permanently but that breaks the conversation. The LLM can't reason about "John" if it never sees "John," and it can't write a file referencing [email protected] if that address was permanently removed.

You need pseudonyms that the LLM can work with, and that your tools can reverse.

How Rehydra Solves It

  1. Detect — Regex patterns catch structured PII (emails, phones, UK postcodes, IBANs, credit cards). An on-device NER model (ONNX, no cloud calls) catches soft PII (names, organizations, locations).
  2. Replace — Each PII value gets a stable placeholder: <PII type="PERSON" id="1"/>. The LLM works with these instead of real data.
  3. Persist — The same entity always gets the same ID, across every message in the session. The LLM maintains relational coherence without ever seeing real PII.
  4. Rehydrate — When a response needs to become real again (a file write, a bash command, a final answer), Rehydra restores the original values from its encrypted map.

Quick Start

Proxy — protect your AI coding tools

Run a local proxy that anonymizes PII before it reaches the LLM and rehydrates responses. Works with Claude Code and other clients that call the Anthropic Messages API or the OpenAI Chat Completions API. Codex can't use it, because it only calls the OpenAI Responses API. Neither can Cursor, which sends requests through Cursor's own servers.

npx @rehydra/cli proxy claude
  rehydra proxy

  Provider   anthropic (https://api.anthropic.com)
  Listening  http://127.0.0.1:8787
  NER        quantized

  Configure your tools:

  Claude Code
    ANTHROPIC_BASE_URL=http://127.0.0.1:8787 claude

Names, emails, phone numbers, and secrets are replaced with placeholders in transit. Tool results (file reads, bash output) are anonymized on the way out. Tool call arguments (file writes, bash commands) are rehydrated on the way back. The LLM never sees real PII — but your tools always get real values.

Note: No API key is needed for Claude Code. With only ANTHROPIC_BASE_URL set, Claude Code keeps using your claude.ai login (Pro/Max) or ANTHROPIC_API_KEY, and the proxy forwards it. Pass --api-key to send upstream requests with a different key.

Browser extension — anonymize ChatGPT and Gemini

Install the Rehydra Chrome extension to protect PII directly in your browser. It replaces names, emails, phone numbers, and secrets with placeholders before your messages reach ChatGPT or Gemini, and rehydrates the responses back to real values in the UI. Detection runs on-device — no data leaves your machine.

OpenCode plugin

npm install @rehydra/opencode
{ "plugins": ["@rehydra/opencode"] }

On OpenCode 1 use the singular "plugin" key instead. The same package ships the V2 (OpenCode 2) and V1 (OpenCode 1) plugin implementations.

Intercepts the conversation between OpenCode and the LLM. Secrets from .env files are replaced with placeholders before they leave your machine and restored before tools execute.

OpenCode 1's separate session-title request bypasses the plugin hooks and can send the first message without scrubbing; disable the title agent to prevent that call. On OpenCode 2 the plugin scrubs title requests through its own session hook.

CLI

For automation and server-side use.

Rehydra Demo

Library — embed PII anonymization in your app

Highly customizable backbone of the implementations above. Supports custom NER models, encryption key providers, session storage providers, tag formats and many more tweaks.

import { anonymize } from 'rehydra';

const { anonymizedText } = await anonymize(
  'Email [email protected] or call John at +41 79 123 45 67'
);

Works in Node.js, Bun, and browsers. No data leaves your machine.

Why Rehydra?

Reversible, not destructive

Most PII libraries mask or redact permanently. Rehydra encrypts the original values with AES-256-GCM and restores them on demand. Anonymize for the LLM, rehydrate for your tools — a full round-trip, not a one-way street.

Session-persistent identity

PERSON_1 stays PERSON_1 across every message in the conversation. When John Smith comes up in message 1, message 5, and message 20, the LLM sees the same placeholder every time. It can track relationships, reference earlier context, and produce coherent multi-turn output — without ever seeing real PII. Sessions persist to SQLite (server), IndexedDB (browser), or in-memory, so identity mappings survive restarts.

Zero-trust, on-device

NER inference runs locally via ONNX Runtime (~280 MB quantized model). No API calls to external services. Works offline. PII never leaves your machine.

LLM proxy with tool-call rehydration

The CLI proxy sits between your coding agent and the API. It anonymizes outbound messages and — critically — rehydrates tool-call arguments before they execute. When the LLM says "write <PII type="EMAIL" id="1"/> to config.yaml," the proxy restores the real email before the file is written. Your agent works normally. Your data stays private.

Secrets, not just PII

Beyond names, emails, and phone numbers, Rehydra detects API keys (OpenAI, Anthropic, Stripe, AWS, GitHub...), JWTs, private keys, database connection strings, and .env secrets.

Credentials the agent can use but not see

Configure named credentials, and the model gets placeholders instead of the values:

const anonymizer = createAnonymizer({
  credentials: {
    github: {
      username: "tj-bot",
      password: { env: "GH_BOT_PW" },        // a string, { env }, or { file }
      description: "GitHub login for the staging org",
      tools: ["Bash", "browser_*"],          // tools that may receive the real values
      hosts: ["github.com"],                 // optional: every host in the call must match
    },
  },
  onCredentialUse: (event) => console.log(event), // { credential, tool, restored, reason? }, never values
});

The system instruction lists each credential by name and description, with its placeholders: <PII type="USERNAME" id="github"/> and <PII type="PASSWORD" id="github"/>. The real values are filled in only in the arguments of tool calls the credential allows. Assistant text, rehydrate() without a tool call, and stored PII maps keep the placeholders, because credential values never enter a PII map. When a value echoes back in tool output, it is masked again, as are its base64, base64url, URL-encoded, hex and JSON-escaped forms and the Basic auth header for the username and password. A call to a tool that isn't allowed keeps the placeholder, and onCredentialUse reports it.

With the CLI proxy, put the same object in a JSON file and run rehydra proxy claude --credentials ./credentials.json. In the OpenCode plugin, use the credentials option.

Names use lowercase letters and digits and start with a letter. Values shorter than 4 characters are restored in tool calls but not masked in output, since they would match too much text.

What this protects: the LLM provider never receives the credential, so it can't leak through prompts, provider logs or the model's replies.

What it doesn't protect: a prompt-injected or misbehaving agent. Once the real value is in a Bash call, the agent can send it anywhere or transform it in ways masking doesn't catch. A tool allowlist doesn't help when the allowed tool is a shell. hosts only checks the URLs and user@host: remotes written in the call. In proxy mode the client runs the tools, so the real value ends up in the client's local transcript. Rehydra doesn't quote values for the shell: a password containing ', ", $ or a backtick can break a shell command it's restored into, so prefer tools that take structured arguments.

Server mode for sandboxed agents

When the agent runs in a sandbox (a VM or container that also handles untrusted input), run Rehydra at the sandbox edge instead of next to the agent. The PII map, the key and credential values stay with the service. The agent and the model only ever handle placeholders, so a prompt-injected agent can't leak values it never had.

rehydra serve --socket /run/rehydra.sock --token "$REHYDRA_SERVE_TOKEN" \
  --db ./pii.db --key "$REHYDRA_KEY" --secrets --credentials ./credentials.json
Route Purpose
GET /healthz 200 once the model and credentials are loaded (no token needed)
GET /v1/sessions/{id}/instruction System instruction for the sandboxed model, listing the credentials it can use
POST /v1/sessions/{id}/anonymize { "text": … } or { "json": … }, optional locale and types (for example only secret types for source code). Returns the anonymized value and counts by type
POST /v1/sessions/{id}/rehydrate { "text" | "json", "caller": "display" } restores ordinary PII for showing to the person allowed to see it. { …, "caller": "tool", "tool": "send_email", "target": "https://…" } also fills in the credentials that tool and target may use
PUT /v1/sessions/{id}/credentials/{name} Adds a credential for one session (username, password, tools, hosts, description). Inline values only, write-only, never stored in the PII map
DELETE /v1/sessions/{id} Drops the session's PII map and credentials

Every /v1 route needs Authorization: Bearer <token>. Without --token or REHYDRA_SERVE_TOKEN, serve generates one and prints it. It listens on 127.0.0.1:8788 or on --socket. JSON payloads round-trip without string-escaping problems. Tools listed in --redact-tools get their arguments back with placeholders. Logs and the onRequest hook carry types and counts, never values.

To embed the service, use createRehydraServer from rehydra/server. It takes and returns web-standard Request and Response objects. Calls for one session run one at a time within the process, so run one server process per PII store. Images, screenshots and PDFs are not scrubbed; callers should treat them as unscrubbed.

Streaming-aware

Purpose-built for LLM token streams. A sentence-buffered chunking system with NER overlap preservation ensures accurate detection even when PII spans chunk boundaries — with a low-latency mode for real-time streaming.

Streaming server-side tool loops

createRehydraFetch supports onToolCall for OpenAI Chat Completions and Anthropic Messages requests with stream: true. The first response is buffered and its complete tool calls are validated before callbacks run. Interleaved calls retain their IDs and arguments. Tool arguments are rehydrated locally, and tool results are anonymized before the next request.

Continuation requests use stream: false. The final response is returned as provider-compatible SSE, including completion events and usage. This buffers the initial response and final JSON response, so it does not preserve token-by-token generation latency. Streams without tool calls retain their original events.

Set maxToolRounds to bound callback rounds, and maxToolResponseBytes to bound each buffered response; defaults are 10 rounds and 8 MiB. On reaching the round limit, pending calls are returned to the caller without execution. Pass an AbortSignal through fetch to cancel buffering or prevent later callbacks; a callback already running must manage its own cancellation. Truncated calls, malformed arguments, and oversized streams fail before tool execution. Upstream HTTP errors retain their status. OpenAI tool loops require a single completion choice. Custom providers can opt in through streamingToolLoop on LLMContentProvider.

Semantic enrichment for machine translation

Optional gender and scope attributes on PII tags (<PII type="PERSON" gender="male" id="1"/>, <PII type="LOCATION" scope="city" id="2"/>) preserve grammatical context for downstream systems.

Stable external tag IDs

Callers that manage PII maps across independent anonymization calls can seed lowercase alphanumeric IDs through existingPiiMap. This allows an ID to be derived from the value it masks, for example with a keyed HMAC, instead of depending on a per-call counter.

const existingPiiMap = new Map([
  ['EMAIL_a4f2c9d8e7b6q', '[email protected]'],
]);

const result = await anonymizer.anonymize(
  'Email [email protected]',
  undefined,
  policy,
  existingPiiMap,
);
// → 'Email <PII type="EMAIL" id="a4f2c9d8e7b6q"/>'

External IDs must match [0-9a-z]+. Decimal-only IDs retain their existing numeric behavior. Avoid IDs beginning with recognizer prefixes such as case, file, ref, or ticket, and avoid runs of seven or more digits; those shapes may themselves be detected as case IDs or phone numbers inside an inbound tag.

Example: Full Round-Trip with Sessions

import {
  createAnonymizer,
  InMemoryKeyProvider,
  SQLitePIIStorageProvider,
} from 'rehydra';

const keyProvider = new InMemoryKeyProvider();
const anonymizer = createAnonymizer({
  ner: {
    mode: 'quantized',              // ~280 MB model, auto-downloads on first use
    caseFallback: true,             // detect lowercase names like "tom"
    thresholds: { PERSON: 0.8 },   // require higher confidence for names
    onStatus: console.log,          // log model download progress
  },
  semantic: { enabled: true },      // adds gender/scope attributes for MT
  secrets: { enabled: true },       // detect API keys, JWTs, connection strings
  keyProvider,
  piiStorageProvider: new SQLitePIIStorageProvider('./pii.db'),
});

const session = anonymizer.session('chat-123');

// Message 1 — NER detects names and orgs, regex catches emails
const r1 = await session.anonymize(
  'Tell John Smith at Acme Corp ([email protected]) we accept the offer'
);
// → "Tell <PII type="PERSON" gender="male" id="1"/> at <PII type="ORG" id="2"/>
//    (<PII type="EMAIL" id="3"/>) we accept the offer"

// Message 2 — same entities keep their IDs across messages
const r2 = await session.anonymize(
  'CC [email protected] and loop in [email protected]'
);
// → "CC <PII type="EMAIL" id="3"/> and loop in <PII type="EMAIL" id="4"/>"

// Rehydrate any message — PII map is loaded from SQLite automatically
const original = await session.rehydrate(r2.anonymizedText);
// → "CC [email protected] and loop in [email protected]"

await anonymizer.dispose();

Packages

Package Description
rehydra Core SDK — detect, anonymize, rehydrate
@rehydra/cli CLI proxy and terminal anonymization
@rehydra/opencode OpenCode plugin — scrubs secrets before they reach LLM providers

Documentation

For API reference, configuration, guides, and examples, visit docs.rehydra.ai.

License

MIT

Address detection

The default regex registry detects UK postcode syntax and numbered English-language street addresses such as 34a Friskin Road. Apartment identifiers are included when adjacent to a street address, as in Flat 1\n34a Friskin Road. A contiguous UK address block ending in a postcode is masked as one ADDRESS; a standalone postcode uses POSTAL_CODE. Bare apartment numbers, unnumbered buildings, and other countries' postal formats need custom recognizers or NER. Postcode matching checks syntax, not whether a postcode is currently assigned.

Disable ADDRESS or POSTAL_CODE through the detection policy to opt out of either recognizer.

French formats

French social security numbers (NIR) are detected as NATIONAL_ID when their mod-97 key is valid, including Corsican 2A/2B numbers. SIRET numbers are detected as TAX_ID when they pass the Luhn check and are either written in the usual 732 829 320 00074 grouping or follow a SIRET/SIREN label. A 9-digit SIREN is only detected after a label, because bare 9- and 14-digit numbers pass Luhn one time in ten. Disable NATIONAL_ID or TAX_ID through the detection policy to opt out.

French street addresses such as 12 rue de la Paix are detected as ADDRESS when the street name is capitalized; a following 75002 Paris line becomes part of the same ADDRESS. A standalone French postcode is detected as POSTAL_CODE when it starts a line or follows a comma and a city name closes the line. Dates written in French (15 mars 2024, 1er janvier, mars 2024) are detected as DATE; abbreviated months such as sept. need a year.

関連プロジェクトを探す

読み込み中…