Metadata-Version: 2.5
Name: maskflare
Version: 0.3.0
Summary: Official Python SDK for Maskflare - mask sensitive data before it reaches an AI model, unmask it when you get a result back.
Project-URL: Homepage, https://maskflare.com
Project-URL: Documentation, https://maskflare.com/developers
Project-URL: Integrations, https://maskflare.com/integrations
Project-URL: Repository, https://github.com/maskflare/maskflare-sdk-python
Project-URL: Changelog, https://github.com/maskflare/maskflare-sdk-python/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/maskflare/maskflare-sdk-python/issues
Author: Maskflare
License-Expression: MIT
License-File: LICENSE
License-File: LICENSES/Unicode-3.0.txt
Keywords: ai,data masking,llm,maskflare,pii,redaction,tokenization
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.27
Provides-Extra: edm
Requires-Dist: pyyaml>=6; extra == 'edm'
Provides-Extra: evidence
Requires-Dist: asn1crypto<2,>=1.5; extra == 'evidence'
Requires-Dist: cryptography>=42; extra == 'evidence'
Provides-Extra: litellm
Requires-Dist: litellm<2,>=1.104; (python_version >= '3.10') and extra == 'litellm'
Description-Content-Type: text/markdown

# maskflare

Official Python SDK for [Maskflare](https://maskflare.com) - mask sensitive data before it
reaches an AI model, unmask it when you get a result back.

Built on [httpx](https://www.python-httpx.org/), its only runtime dependency.

Links: [maskflare.com](https://maskflare.com) · [Developer guide](https://maskflare.com/developers) · [AI provider integrations](https://maskflare.com/integrations) · [Book a demo](https://maskflare.com/contact)

## Install

```bash
pip install maskflare
```

## Quickstart

Generate a **Redaction**-purpose API key from your Maskflare dashboard (Configure → API keys →
Create key → Purpose: Redaction) and you're ready to go:

```python
import os
from maskflare import Maskflare

client = Maskflare(
    api_key=os.environ["MASKFLARE_API_KEY"],
    # base_url defaults to https://api.maskflare.com - set it to the gateway URL
    # shown in your Maskflare console if your organization uses its own.
)

result = client.mask("Contact ada@example.com for details")
# result.output: "Contact mf_mask_170b8521c1b944b3beb9ca02b328efbe for details"
# result.tokens: [MaskedToken(token="170b8521c1b944b3beb9ca02b328efbe", rule_key="email")]

# ... send result.output to your LLM, store it, log it - the real value never leaves your key's reach ...

original = client.unmask([t.token for t in result.tokens])
# original: {"170b8521c1b944b3beb9ca02b328efbe": "ada@example.com"}
```

Earlier releases spelled the names `MaskFlare`, `AsyncMaskFlare` and `MaskFlare*Error`. Those still
work - they are the same classes - but new code should use the `Maskflare` spelling.

`Maskflare` also works as a context manager, which releases its connection pool on exit:

```python
with Maskflare(api_key=os.environ["MASKFLARE_API_KEY"]) as client:
    result = client.mask("Contact ada@example.com for details")
```

A **Redaction** key can only mask/unmask - it's rejected if used against Maskflare's AI-gateway
forwarding routes, so a leaked SDK key can never be used to spend your AI-provider budget. Masking
rules (what counts as sensitive, and whether request/response text is checked) are configured per
environment on the dashboard's Rules page - the SDK just applies whatever your key's environment
has configured.

## Unmasking

Tokens resolve back to their original value for as long as your organization's masking-token
lifetime allows: 30 days by default, counted from the last time a request or response carried the
token. Owners, admins and security members change it in the organization's masking settings
(`masking_token_ttl_days` on `PUT /api/platform/v1/organizations/current/masking-settings`, 1 to
365 days); a change applies to tokens sent from then on. After that, unmasking leaves them as they
are. This is not your API key's expiry, which is set on the key.

## API

### `Maskflare(api_key, *, base_url=..., timeout=..., max_retries=..., http_client=..., on_key_expiring=...)`

| Parameter         | Type                         | Default                      | Description                                                             |
| ----------------- | ---------------------------- | ---------------------------- | ------------------------------------------------------------------------ |
| `api_key`         | `str` or `Callable[[], str]` | _required_                   | A Redaction-purpose API key, or a function that returns the current one (see [Key rotation and expiry](#key-rotation-and-expiry)). |
| `base_url`        | `str`                        | `https://api.maskflare.com`  | Override for a self-hosted deployment or local development.              |
| `timeout`         | `float`                      | `10.0`                       | Per-request timeout, in seconds.                                        |
| `max_retries`     | `int`                        | `2`                           | Automatic retries on `429`/`5xx`, honoring `Retry-After`. `0` disables.  |
| `http_client`     | `httpx.Client`               | a new, internally-owned one  | Bring your own `httpx.Client` (e.g. to share a connection pool or add custom transport/proxy settings). When supplied, `Maskflare` never closes it for you. |
| `on_key_expiring` | `Callable[[datetime], None]` | log a warning                | Called instead of the warning when the key has less than 7 days left.   |

`client.key_expires_at` is the key's expiry (a UTC `datetime`) as the API last reported it: `None`
before the first successful request and for a key that never expires.

### `client.mask(input: str, *, deterministic: bool = False, subject_tenant: str | None = None, spoken: bool = False, spans: bool = False) -> MaskResult`

```python
@dataclass(frozen=True)
class MaskResult:
    output: str  # input, with each match replaced by an opaque token
    tokens: tuple[MaskedToken, ...]
    spans: tuple[MaskSpan, ...] | None = None  # only with spans=True


@dataclass(frozen=True)
class MaskedToken:
    token: str
    rule_key: str
```

- `deterministic` (default `False`): when true, matches are replaced with stable, typed
  stand-ins (e.g. `EMAIL_kovapeluzi`) instead of random `mf_mask_...` tokens - the same value in
  the same scope always becomes the same stand-in, so you can mask text before embedding it and
  still get consistent matches at query time. **Deterministic stand-ins are pseudonymous data,
  not anonymous**: the original value is only one vault lookup away for anyone who can call
  `unmask`/`unmask_text` in that scope, so treat masked-with-`deterministic=True` text and any
  index built from it with the same care as the data it was derived from. Omitted entirely from
  the request when `False` (the default, unchanged behaviour).
- `subject_tenant` (default `None`): scopes deterministic masking to one of your end customers,
  so the same value under different tenants produces different stand-ins and can only be unmasked
  within that tenant's scope. Sent as the `X-Maskflare-Subject-Tenant` header, only when set. Must
  be 1-128 characters of `[A-Za-z0-9._:-]`; anything else raises `TypeError` before any request is
  made.
- `spoken` and `spans` (default `False`): see [Voice](#voice-speech-to-speech). Both need
  `deterministic=True`; without it `mask` raises `ValueError` before any request.

### `client.unmask(tokens: Sequence[str], *, subject_tenant: str | None = None) -> dict[str, str]`

Returns a map of token → original value, for every token that was found and belonged to the
calling key. A token you don't own, or one that's expired, is simply omitted - check
`token in result` for the ones you need. Also resolves deterministic stand-ins from `mask(...,
deterministic=True)`.

`subject_tenant` must match the value used when the stand-in was created (see `mask` above); same
validation and header as `mask`.

### `client.unmask_text(text: str, *, subject_tenant: str | None = None) -> str`

Finds every `mf_mask_<id>` token and deterministic stand-in (e.g. `EMAIL_kovapeluzi`) in `text`
- typically an LLM response or a document retrieved from a RAG index built on masked text - and
replaces each one with its original value, resolving them from the API in batches of up to 100.
Anything that can't be resolved, including an ordinary identifier that merely happens to look like
a stand-in, is left untouched. Makes no request when `text` contains no candidate token.

```python
readable = client.unmask_text("Contact EMAIL_kovapeluzi about mf_mask_170b8521c1b944b3beb9ca02b328efbe")
# readable: "Contact jane.doe@acme.com about ada@example.com"
```

### Errors

- `MaskflareError` - the API rejected the request. Has `.status`, `.code`, `.detail`, and (for a
  `429`) `.retry_after_seconds`. `.is_expired` is true when the API key has expired
  (`api_key_expired`): retrying with the same key can't succeed.
- `MaskflareConnectionError` - the request never reached the API (network failure or timeout).
- A plain `TypeError` for invalid input caught client-side before any request is made (e.g. an
  empty string to `mask`).

```python
from maskflare import Maskflare, MaskflareError

try:
    client.mask(user_input)
except MaskflareError as error:
    if error.code == "rate_limited":
        ...  # back off - or just let the SDK's built-in retry handle it (see max_retries)
    raise
```

### `AsyncMaskflare`

The asyncio client: the same constructor (with an optional `httpx.AsyncClient`), methods and
errors as `Maskflare`, awaited, and closed with `await client.aclose()` or `async with`:

```python
from maskflare import AsyncMaskflare

async with AsyncMaskflare(api_key=os.environ["MASKFLARE_API_KEY"]) as client:
    result = await client.mask("Contact ada@example.com for details")
    readable = await client.unmask_text(result.output)
```

### Key rotation and expiry

A key from the console never expires unless your organization's expiry policy sets a maximum age.
When it does expire, every request fails with `401 api_key_expired` (`error.is_expired`). Two
things keep that from catching you out:

- **A provider function.** Pass `api_key` a function that returns the current key - read from your
  secret manager, a mounted file or an environment variable - and a key rotated in the console or
  by Terraform is picked up without restarting your process. It is called before every request, so
  cache inside it if fetching is slow. After a `401` the SDK calls it once more and retries the
  request if it returned a different key. `AsyncMaskflare` also accepts an `async` function.

  ```python
  from pathlib import Path

  client = Maskflare(api_key=lambda: Path("/run/secrets/maskflare-api-key").read_text().strip())
  ```

- **An expiry warning.** Responses carry the key's expiry (`Maskflare-Key-Expires`). With less than
  7 days left the SDK logs one warning per expiry on the `maskflare` logger, or calls
  `on_key_expiring(expires_at)` instead when you pass one.

Rotating a key in the console keeps the old one working for the grace period (7 days unless your
organization changed it), so a provider function has that long to see the new key.

## Voice (speech-to-speech)

For voice agents that hear the caller directly, mask the speech-to-text transcript and silence
the matching audio before it reaches the model. The helpers are pure functions (no audio or STT
dependency); all offsets are code points.

```python
from maskflare import (
    MUTED_SPAN_INSTRUCTIONS,
    PROTECTED_REFERENCE_INSTRUCTIONS,
    SpokenWord,
    mute_intervals,
    mute_pcm16,
    transcript_from_words,
)

words = [SpokenWord("my", 0, 200), SpokenWord("email", 200, 500), ...]  # from your STT
# If the turn has no words, skip `mask` (an empty transcript is rejected): there is nothing to mute.
transcript = transcript_from_words(words)
result = client.mask(transcript.text, deterministic=True, spoken=True, spans=True, subject_tenant=company_id)
intervals = mute_intervals(words, result.spans)  # spans is set whenever spans=True
safe_audio = mute_pcm16(pcm16_bytes, 24000, intervals)  # send this to the model, never the raw audio

# Tell the relay model about the stand-ins and the silences.
instructions = f"{base_instructions} {PROTECTED_REFERENCE_INSTRUCTIONS} {MUTED_SPAN_INSTRUCTIONS}"
```

With `spans=True`, `mask` raises `MaskflareResponseError` if the response has no well-formed `spans`,
so a missing list is never mistaken for "nothing to mute": audio must never go out unmuted.

`spoken=True` also finds values the way speech-to-text writes them (`jane dot doe at acme dot com`)
and gives them the same stand-in as the typed value. `spans=True` returns where each masked value
sat in the input, which `mute_intervals` maps to the words to silence.

### `transcript_from_words(words: Sequence[SpokenWord]) -> Transcript`

Joins the words with single spaces. `Transcript(text, offsets)` holds the joined text and each
word's `(start, end)` offsets in it. `SpokenWord(text, start_ms, end_ms)` is a frozen dataclass.

### `mute_intervals(words, spans, *, pad_ms=50) -> list[MuteInterval]`

Merged, sorted `MuteInterval(start_ms, end_ms)` values covering every word that overlaps a span,
padded on both sides and clamped at 0. `spans` must index `transcript_from_words(words).text`.

### `mute_pcm16(pcm: bytes, sample_rate: int, intervals) -> bytes`

A copy of 16-bit little-endian mono PCM with the samples inside each interval set to zero.
Interval edges round outward to whole samples.

### `PROTECTED_REFERENCE_INSTRUCTIONS` and `MUTED_SPAN_INSTRUCTIONS`

Two sentences for the model's instructions: the first tells it stand-ins such as
`EMAIL_pluvikanor` are protected references it must not read aloud; the second tells it that a
short silence in the caller's speech is captured sensitive data and not to ask for a repeat.

## Routing GPT-Live through Maskflare

To mask a GPT-Live session without touching audio code, point your server's GPT-Live WebSocket URL
at the gateway instead of OpenAI: `wss://<gateway>/v1/openai/live?model=<model>`. Send
`x-maskflare-key: <gateway key>` (or `Authorization: Bearer <mf key>`) and
`X-Maskflare-Subject-Tenant: <tenant>`, the same scope as the `subject_tenant` mask option, so the
stand-ins match.

```python
import os
import websockets

headers = {
    "x-maskflare-key": os.environ["MASKFLARE_API_KEY"],
    "X-Maskflare-Subject-Tenant": company_id,
}
async with websockets.connect(
    f"wss://{gateway}/v1/openai/live?model={model}", additional_headers=headers
) as ws:
    async for event in ws:
        ...  # stand-ins in provider events: unmask for display
```

Client text events (instructions, thinking, commentary, `function_call_output`) reach the provider
masked, and their stand-ins resolve with `unmask`/`unmask_text` in the same scope. The provider's
events come back unchanged. Audio is not masked: combine this with the voice helpers above (mute
spans) for spoken values.

A refused handshake or a kill switch closes the socket with `1008` and the reason
`maskflare:<code>`; `1011` is an outage on Maskflare's or the provider's side (the reason says which, e.g. `maskflare:masking_unavailable`, `maskflare:upstream_unavailable`). The
[developer documentation](https://maskflare.com/developers) lists every close code.

## Keeping values out of your own logs: `Sensitive`

Maskflare keeps sensitive data away from AI providers. `Sensitive` keeps it out of your own logs,
tracebacks and serialized output. Wrap a value once and pass the wrapper around. Every way Python
turns an object into text shows a placeholder instead of the value: `print`, `repr`/`str`,
f-strings, `%s`/`%r`, `logging`, exception messages and containers. `json.dumps` refuses the
wrapper. The value comes back only through `.reveal()`:

```python
import logging
from maskflare import Sensitive

email = Sensitive("ada@example.com")
print(email)  # Sensitive(***)
logging.info("signed up: %s", email)  # signed up: Sensitive(***)
print(Sensitive("ada@example.com", partial=True))  # Sensitive(ad***om)
send_welcome_mail(to=email.reveal())  # the one place the value is used
```

`partial=True` keeps the first and last two characters of a string of 8 or more; shorter strings
and other types stay fully hidden. Two wrappers compare equal when their values do (in constant
time for strings and bytes). Copies and pickles keep the value.

With Pydantic v2 installed (not a dependency), `Sensitive[str]` works as a model field. Input is
validated as `str` and wrapped, and `model_dump()` / `model_dump_json()` write the placeholder:

```python
from pydantic import BaseModel


class User(BaseModel):
    email: Sensitive[str]


user = User(email="ada@example.com")
user.model_dump()  # {'email': '***'}
user.email.reveal()  # 'ada@example.com'
```

For tests and local debugging only, `MASKFLARE_DISABLE_REDACTION=1` shows values as they are. It
is read once, when `maskflare` is imported, so nothing can switch redaction off later at runtime.
`Sensitive` guards against accidents, not against code that calls `.reveal()` on purpose.

## LiteLLM guardrail

Running [LiteLLM](https://docs.litellm.ai/) as your AI gateway? `MaskflareGuardrail` masks what
LiteLLM sends a model and restores the tokens in what comes back, so the model never sees the
values and your clients still get them:

```bash
pip install "maskflare[litellm]" "litellm[proxy]"   # LiteLLM needs Python 3.10+
```

```yaml
guardrails:
  - guardrail_name: maskflare
    litellm_params:
      guardrail: maskflare.integrations.litellm.MaskflareGuardrail
      mode: [pre_call, post_call]
      default_on: true
      api_key: os.environ/MASKFLARE_API_KEY   # a Redaction-purpose key
      fail_policy: closed
```

A complete config is in [`examples/litellm/config.yaml`](examples/litellm/config.yaml).

- **Before the call**, every message text and tool-call argument string is masked through
  `/v1/mask` (up to `max_concurrency`, default 8, at once).
- **After the call**, `mf_mask_` tokens in the answer's text and tool-call arguments are restored
  through `/v1/unmask` - streamed or not. A streamed token split across chunks is held back until
  it is whole (at most 39 characters, only while the text ends like the start of a token).
  Streams are restored for chat completions; other streamed shapes pass through as sent.
- **Only tokens minted for the same call are restored.** LiteLLM shares one Maskflare key across
  all of its users, so a token copied from another conversation into a prompt comes back as a
  token, never as another user's value.
- Outputs of non-reversible rule actions (redact, partial, hash) and format-preserving
  encryption are left as the model returned them.
- **`fail_policy`**: `closed` (default) refuses the call with a 503 when Maskflare can't mask it
  or restore the answer; `open` forwards the request unmasked (or returns the answer with its
  tokens) and logs a warning. A match of a `block` rule refuses the call with a 403 whatever the
  policy.
- Errors and log lines name a category (`blocked`, `connection`, `unavailable`, `rate_limited`,
  `auth`, `rejected`, `internal`) and the API's error code - never text, values, tokens or keys.

Other options: `api_base` (default `MASKFLARE_BASE_URL`, else the public API), `timeout`,
`max_retries`.

## Claude Code hook

`maskflare-hook` checks what Claude Code sends and reads with your organization's masking rules:

| Claude Code event | What the hook does |
| --- | --- |
| **Prompt** (`UserPromptSubmit`) | A prompt any rule would mask or block is stopped, with a reason naming the rule keys, never the values. Claude Code can block a prompt but not rewrite it. |
| **Tool input** (`PreToolUse`: Bash, WebFetch, WebSearch, Write, Edit, MultiEdit, NotebookEdit, `mcp__*`) | String values are masked before the tool runs (`updatedInput`). A block rule's match denies the call. Your own permission rules still apply to the masked call. File paths and Edit's `old_string` are left as they are. |
| **Tool output** (`PostToolUse`: Bash, Read, Grep, WebFetch, WebSearch, `mcp__*`) | Strings are masked before the model reads them (`updatedToolOutput`, same shape as the tool's output). A block rule's match is withheld. |

Install the command, then the plugin:

```bash
uv tool install maskflare          # or: pipx install maskflare - puts maskflare-hook on your PATH
```

```text
/plugin install maskflare --marketplace maskflare/maskflare-sdk-python
```

On Claude Code before 2.1.275, run `/plugin marketplace add maskflare/maskflare-sdk-python` and then `/plugin install maskflare@maskflare`. The plugin asks for:

- **API key:** a `gateway` or `redaction` key. It is stored in your OS keychain.
- **Base URL:** defaults to `https://api.maskflare.com`.
- **Fail mode:** `closed` (the default) blocks prompts and tool calls, and withholds tool output, that couldn't be checked. `open` lets them through.

Without the plugin, set `MASKFLARE_API_KEY`, `MASKFLARE_BASE_URL`, `MASKFLARE_HOOK_FAIL` (`open` or `closed`) and `MASKFLARE_HOOK_TIMEOUT` (seconds, default 5). Then point the hooks in `plugins/maskflare/hooks/hooks.json` at `maskflare-hook` from your own `settings.json`.

Notes:

- **What masking can't undo:** masking tool output changes only what the model reads. The tool has already run, and Claude Code's local transcript keeps the original output.
- **What the model sees instead:** values masked in tool input reach the tool as `mf_mask_` tokens (or redactions). The model is told which rule keys were masked.
- **Speed:** each event starts one process and makes one `/v1/mask` call, with every string of a tool call sent together. The hook imports only light standard-library modules, about 47 ms on a slow Windows laptop. The rest of its time is the interpreter starting and the round trip to your gateway.

## Cursor, Codex CLI and GitHub Copilot hooks

The same command checks Cursor, Codex CLI and GitHub Copilot (Copilot CLI, and VS Code's agent mode, which shares its hooks) traffic with `--agent cursor`, `--agent codex` or `--agent copilot --event NAME`. Configuration is the same environment variables as above. Each agent lets a hook change less than Claude Code does, so the hook does what each one allows:

| | Cursor (`maskflare-hook --agent cursor`) | Codex CLI (`maskflare-hook --agent codex`) | GitHub Copilot (`maskflare-hook --agent copilot --event ...`) |
| --- | --- | --- | --- |
| **Prompt** | `beforeSubmitPrompt`: a prompt any rule would mask or block is stopped. | `UserPromptSubmit`: a prompt any rule would mask or block is stopped. | `userPromptTransformed`: the prompt the model gets is masked; on a block rule's match the model gets a notice instead. |
| **Tool input** | `preToolUse` (Shell, Write, Task, MCP): strings masked (`updated_input`); a block rule's match denies the call. | `PreToolUse` (Bash, `apply_patch`, MCP): strings masked (`updatedInput`); a block rule's match denies the call. For `apply_patch` only the patch's added lines are masked. | `preToolUse` (every tool): strings masked (`modifiedArgs`); a block rule's match denies the call. |
| **Tool output** | `postToolUse`: an MCP tool's output is masked (`updated_mcp_tool_output`); Shell output is only flagged to the model. | `PostToolUse` (Bash, MCP): output that needs masking is replaced by its masked text. | `postToolUse` (every tool): the result is masked (`modifiedResult`). |
| **File reads** | `beforeReadFile`: a file any rule would mask or block is not read. | Read through Bash, so covered by `PostToolUse`. | The `view` tool's result, covered by `postToolUse`. |

Copy [`examples/cursor/hooks.json`](examples/cursor/hooks.json) to `.cursor/hooks.json` (project) or `~/.cursor/hooks.json` (user). Copy [`examples/codex/hooks.json`](examples/codex/hooks.json) to `.codex/hooks.json` (project; Codex loads it once the project is trusted) or `~/.codex/hooks.json`, then review the hooks with `/hooks`. Copy [`examples/copilot/hooks.json`](examples/copilot/hooks.json) into `~/.copilot/hooks/` (user: Copilot CLI and VS Code) or `.github/hooks/` (repository).

Limits:

- **Cursor:**
  - It can't change a non-MCP tool's output, so Shell output reaches the model as it is. When it holds sensitive data, the hook tells the model which kinds (`additional_context`, rule keys only) and asks it to keep them to itself.
  - A sensitive file is refused, not masked.
  - `failClosed: true` in the example makes Cursor block when the hook crashes or times out. Set it to `false` together with `MASKFLARE_HOOK_FAIL=open`.
  - When the hook allows a tool call, it answers `permission: allow` (Cursor needs an explicit answer).
- **Codex:**
  - It accepts a masked tool input only with `permissionDecision: allow`.
  - A replaced output reaches the model as the hook's `reason`. Codex also writes it to its own log, masked.
  - The command has already run.
  - Codex has no fail-closed setting for a hook that crashes or times out: such a call goes through.
- **GitHub Copilot:**
  - Its payloads don't name the event, so each entry passes `--event`.
  - It can't stop a prompt: the person's own timeline keeps what they typed, while the model gets the masked prompt or the notice.
  - A masked tool call carries no `permissionDecision`, so Copilot's own permission prompt still applies.
  - A tool call whose arguments aren't a JSON object can't be rewritten: it is denied when masking would change it.
  - A `preToolUse` hook that crashes denies the call; one that times out lets it through.
  - On Windows Copilot runs hooks in PowerShell 7.
- **All three:** Masking happens in the hook, so the agent's local history keeps what was typed or read.

Checked live against Codex CLI 0.143 (prompt blocked, Bash input masked before running, output replaced). The Cursor and Copilot sides follow each vendor's documented hook protocol and are covered by tests.

## Exact Data Match (EDM) uploads

Exact Data Match masks the values of *your own* customer list - names, emails, account numbers -
wherever they show up in AI traffic. The `maskflare` command hashes the list on your machine and
uploads only keyed one-way hashes: no value from the file ever touches the network or the disk
(the work dir holds hashes only), and the organization's EDM key lives in memory only.

```bash
pip install 'maskflare[edm]'   # adds PyYAML for schema.yaml; hashing needs CPython 3.13
export MASKFLARE_API_KEY=mf_...   # an EDM-purpose API key (dashboard: Configure -> API keys)

maskflare edm upload customers.csv --schema schema.yaml --dry-run   # validate and report only
maskflare edm upload customers.csv --schema schema.yaml
maskflare edm status [--dataset customers] [--json]
maskflare edm delete --dataset customers [--yes]
maskflare edm delete --all [--shred-key] --yes   # --shred-key also destroys the EDM key
```

`schema.yaml` names the columns to upload and how each one matches:

```yaml
version: 1
dataset: customers              # ^[a-z][a-z0-9_]{0,31}$
name: Customer master list
csv: {delimiter: ",", header: true, encoding: utf-8-sig}
fields:
  - column: full_name
    type: text                  # text | email | identifier
    label: Customer name
    rule_key: customer_name     # default edm_<dataset>_<column>; always put under edm_
    min_tokens: 2               # text only: the fewest words a value may have (1-4)
    apply_to: [request, response]   # default: request only for text, both otherwise
  - {column: email, type: email, label: Customer email}
  - {column: account_no, type: identifier, label: Account number}   # min_length defaults to 6
corroborating: []               # reserved; must be empty
```

At most 8 fields per dataset (the server allows 10 datasets per organization). With
`header: false`, `column` is a 1-based column number.

- **Upload options:** `--memory-mb 128` bounds the memory used to sort hashes (sorted runs go to
  `--work-dir`, a temporary directory by default, removed afterwards unless `--keep-work-dir`);
  `--json` prints the result as JSON on stdout; `--quiet` silences the progress on stderr.
- **Files:** any text encoding (`csv.encoding`; `utf-16` with `delimiter: "	"` reads Excel's
  "Unicode Text" export) and CR, LF or CRLF line endings; blank lines are skipped.
- **Empty fields:** committing a version replaces the live one, so an upload in which a field
  ends with no uploadable value (a wrong column or encoding, a file of placeholders) is refused
  unless you pass `--allow-empty-field`; one with no value in any field is always refused (use
  `edm delete` to remove a dataset). A commit that comes back `superseded` (a newer version was
  already active) warns and exits non-zero.
- **Auth:** `MASKFLARE_API_KEY` or `--api-key-file PATH`; `--api-key` works but warns (shell
  history). The base URL comes from `MASKFLARE_BASE_URL` or `--base-url`, and must be `https://`
  (plain `http://` only to a loopback host): the EDM key travels in a response body.
- **What is not uploaded:** cells that can't be matched as their type (`empty`, `too_few_tokens`,
  `too_many_tokens`, `too_long`, `too_short`, `bad_shape`, `unsupported_script` - Han, Thai and
  other scripts written without spaces aren't supported in text fields) and placeholder cells such
  as `N/A`, `test`, `unknown` or `noreply@...` (`junk`). They are counted per field and listed
  by row number and reason - the report never prints a value. Run `--dry-run` first to see them;
  it makes no network call.
- **Resume:** an upload is named by the hash of its schema, key version and hash streams, so
  re-running the same command after an interruption uploads only the chunks still missing, and
  re-running a completed upload changes nothing. Transient failures (429, 5xx, network) are
  retried with backoff. A 503 `edm_unavailable` from the key request is not: it means EDM is not
  configured on that Maskflare, so the command stops at once and says so. A changed file becomes a new version that replaces the active one when it
  commits.
- **Python:** `import maskflare` keeps working on Python 3.9+, and `edm status`/`edm delete` run
  anywhere; hashing (`edm upload`) needs **CPython 3.13** because it must use exactly the Unicode
  15.1 tables Maskflare's servers canonicalise with, and refuses to run on anything else.

## Verifying audit evidence offline

Maskflare records evidence of what it did with every request. Each piece of evidence is a salted
commitment to the request's metadata, never its content. The commitments are sealed hourly into a
hash chain per organization, signed, and anchored with OpenTimestamps (Bitcoin) and an RFC 3161
Time Stamping Authority. `maskflare evidence verify` lets an auditor check that evidence without
trusting Maskflare's servers:

```bash
pip install "maskflare[evidence]"
# download a day's bundle (owner, admin, security or auditor role) - or use the console's Evidence page
curl -H "Authorization: Bearer $TOKEN" -H "X-Maskflare-Organization: $ORG" \
  "https://<your-maskflare>/api/ledger/v1/evidence/bundle?day=2026-11-04" -o evidence.ndjson
maskflare evidence verify evidence.ndjson --key <signing key fingerprint> --tsa-ca tsa-roots.pem
```

It recomputes every leaf, Merkle root, seal hash and chain link, checks the Ed25519 signatures, and
checks that the seals cover the whole day. It then checks the anchor proofs. For an OpenTimestamps
proof it prints the Bitcoin block height and merkle root; compare them with any copy of the chain,
or pass `--bitcoin-explorer https://blockstream.info/api`. For an RFC 3161 token it checks the
TSA's signature over the root, and with `--tsa-ca`, its certificate chain to roots you trust.

- `--evm-rpc https://<your node>` checks an EVM anchor (an organization's own chain) online: the
  transaction, its data, sender and block hash, against a node you choose.
- `--key` pins the signing key's fingerprint; it is shown in the console and in `GET /evidence/keys`.
- `maskflare evidence verify-record proof.json` checks one record's proof (`GET /evidence/records/{id}`).
- `--json` prints a machine-readable report.
- A `gaps` warning lists records the ledger gave up storing (a message JetStream stopped
  delivering). Each one is sealed as a gap leaf with its stream sequence and reason, so the loss is
  part of the evidence. It doesn't fail the check.
- A `canaries` check reports the latest canary attestation per environment: Maskflare runs known
  synthetic values through each environment's policy daily and seals the result. A rule whose
  sample passed unmasked is a warning. This is the only part of the report that speaks to masking
  quality, and only for known samples.
- `--require-anchor` exits 2 while the newest seal is not anchored yet. Bitcoin confirmation takes a few hours.
- Exit codes: 0 verified, 1 a check failed, 2 not anchored yet under `--require-anchor`.

The checks run offline. The only network access is `--bitcoin-explorer` and `--evm-rpc`, and only to
the explorer or node you name. The format code (`maskflare/evidence/_format.py`, `_ots.py`) is a
verbatim copy of what Maskflare's ledger runs, so you can read it - or reimplement the checks from
it - without trusting this tool.

What this proves: the records existed unchanged since their anchor time, and Maskflare's key signed
them. It does not prove that the masking itself was correct.

## Development

```bash
uv sync
uv run pytest       # tests
uv run ruff check .  # lint
uv run pyright       # typecheck
```

`src/maskflare/edm/_canon.py`, `_confusables.py`, `src/maskflare/evidence/_format.py` and
`_ots.py` are generated copies of the code Maskflare's servers run - never edit them here: the
tests pin each file's SHA-256 (`tests/fixtures/edm_canon_vectors.json`, `evidence_vectors.json`), so
an upload or a verification always agrees with the server. Two tests run only beside Maskflare's
server code and are skipped otherwise (`tests/test_edm_core_e2e.py`,
`tests/test_edm_platform_contract.py`). `MASKFLARE_SLOW_TESTS=1` runs the opt-in 5M-row
external-sort test.

`tests/test_litellm_proxy.py` starts a real LiteLLM proxy (`litellm[proxy]`, a dev dependency)
from `examples/litellm/config.yaml`, between local fakes of the Maskflare API and an OpenAI
provider (`tests/litellm_fakes.py`), and checks what the model received and what the client got
back.

## Versioning and releases

The package follows [Semantic Versioning](https://semver.org). Until 1.0, a minor version may
change the API; every change is listed in [CHANGELOG.md](CHANGELOG.md). Releases are published to
PyPI from a `vX.Y.Z` tag.

Other Maskflare packages: the TypeScript SDK [`@maskflare/sdk`](https://github.com/maskflare/maskflare-sdk-js)
and the admin MCP server [`maskflare-mcp`](https://github.com/maskflare/maskflare-mcp-server).

## License

MIT. `src/maskflare/edm/_confusables.py` is generated from Unicode's `confusables.txt` (UTS #39),
distributed under the Unicode License v3 ([LICENSES/Unicode-3.0.txt](LICENSES/Unicode-3.0.txt)).
