# maskyr threat model

Scope: maskyr 0.1 running as a local gateway on one user's machine, between an application and an external AI provider.
Labels used below: **Implemented** = code exists and is covered by a software test in this repo. **Partial** = works for some cases, limits stated. **Not covered** = out of scope or not built. Nothing here has had an external security review, and no detection-quality benchmark has been run.

## Assets

1. Original sensitive values in prompts, attachments, tool results and conversation history.
2. The mapping vault (original ↔ pseudonym pairs) and the provider API keys stored in it.
3. The structure and context of the conversation (what is being asked), which may identify a person even when every value is masked.

## Trust boundaries

| Component | Trust |
|---|---|
| The user's machine and OS account | Trusted. A local attacker with the same OS account is out of scope (see "Not covered"). |
| maskyr process | Trusted. It is the enforcement point. |
| Local inference backend | Trusted with originals (it is on-device or on a private network address; `assertLocalUrl` accepts only `localhost`, `*.local` names and literal loopback/private IP addresses, so a public name that merely looks like a private address is refused). |
| External provider and everything on the path to it | Untrusted. It sees only masked text. |
| Model output | Untrusted input. It is treated as data, never executed. |
| Browser pages | Untrusted. They must not reach the admin API. |

## Threats and mitigations

### T1 Incomplete masking (a sensitive value is not detected)
The most likely failure. Detection is rules + context cues + heuristics; names and free-form addresses are heuristic and will miss cases (rare names, names used as ordinary words, non-Latin scripts, misspellings).
- Implemented: every outbound payload is re-scanned after masking (`residualScan`) with (a) a check for any known original value or alias, normalised for case, whitespace and separators, and (b) a second detector pass. Findings block the request when `onResidual = block` (default).
- Implemented: once a value is in the vault, every later occurrence is caught by exact match regardless of detector confidence, in any message of the history.
- Implemented: manual terms, deny-list terms and the optional model-assisted detector can only add spans. The detector model failing, or being prompt-injected into returning nothing, cannot reduce protection.
- Implemented: unknown request fields and unknown message fields are dropped, not forwarded; `user` and `metadata` are never sent.
- Partial: a value the detectors never see (first mention, unusual format, no cue) is sent unmasked. The residual scan cannot catch what no detector recognises. **This is the main residual risk. Use deny-terms for known-sensitive names, enable the local detector once a validated model exists, and prefer the strict policy for high-stakes data.**
- Not covered: sensitive content inside images, audio, PDFs and other binary attachments. These are blocked by default (fail closed). Allowing images sends them unmasked.

### T2 Contextual re-identification
Masked text can still identify someone: unusual job + employer + city + event dates, rare medical conditions, or a quasi-identifier such as "the only CFO of a 40-person firm in Lyon".
- Partial: dates of birth are shifted by a per-scope offset (intervals preserved); organisations, addresses and locations are replaced by policy; per-conversation scope means the provider cannot link pseudonyms across conversations.
- Not covered: semantic quasi-identifier detection, and a "semantic judge" that rates re-identification risk. The interface for a local model to do this is specified (`docs/MODEL-SHORTLIST.md`) but no such model is integrated or validated. Numbers (amounts, quantities) and unlabelled dates are intentionally left intact so calculations remain correct, which also means they remain linkable context.
- Not covered: stylometric or behavioural fingerprinting by the provider; the same account sees traffic timing and volume.

### T3 Prompt injection
(a) Injection in user content or attachments aiming to make the external model misbehave: out of maskyr's control; maskyr does not claim to filter it.
(b) Injection aimed at maskyr's own components:
- The enforcement path is deterministic code; no LLM decides what is masked, restored or sent.
- A model-assisted detector receives untrusted text. Its output is parsed as JSON, every entity must be an exact substring of the input, and it can only add protection (Implemented, tested for parsing; the model itself is not integrated).
- Injected text cannot read the vault: the vault is not reachable from model output.

### T4 Mapping (vault) exposure
- Implemented: vault is AES-256-GCM encrypted at rest with a key from either a passphrase (scrypt N=32768) or a 0600 key file; header is authenticated; writes are atomic, 0600, fresh IV each save; tampering is detected. Saves are serialised, a change made while a write is in flight is saved by the next one, and a failed save does not block later ones (found in review, fixed, regression-tested).
- Implemented: audit log is metadata only by construction (the type carries counts, route and reason, no text or values); error messages returned to the client use fixed text for unsupported content and do not quote request content; the log writer has no access to originals.
- Implemented: vault listings return originals only with an explicit `?reveal=1`; the encrypted backup export never contains plaintext.
- Partial: the local admin API, used by the bundled UI, returns the user's own prompt and the replaced values for `POST /preview` and `GET /transmissions/:id` without a reveal flag, because the UI shows what the user typed next to what is sent. Access needs the per-start admin token and a same-origin request. The data is the user's own input, held in memory only (last 20 transmissions, cleared on lock), but it is not gated like vault reveal.
- Partial: with a key file, anything that can read both files (same OS user, backups that include both) can decrypt. With a passphrase, an unlocked gateway holds keys and plaintext mappings in process memory; JavaScript cannot guarantee zeroisation, and swap or core dumps may expose them.
- Implemented: the admin API needs a per-start random token, rejects cross-origin and unexpected `Host` headers (DNS-rebinding defence), sends no CORS headers, and the UI is served with a strict CSP. The gateway binds to loopback by default and refuses to bind elsewhere without `MASKYR_GATEWAY_TOKEN`.
- Not covered: a malicious process running as the same user, malware with debugger access, or a compromised browser extension on the same machine.

### T5 Malicious or misleading external responses
- Exfiltration through restoration: a hostile model could emit a known pseudonym inside a URL or markdown image/link so that restoring it would send the real value to an attacker when rendered. Implemented: pseudonyms that sit inside a URL token or a markdown link target are **not restored** (counted in `maskyr.urlGuarded`). Also guarded: protocol-relative URLs, host/path/query shapes such as `evil.example/x?q=` and `src=`/`href=` attribute values; the back-scan is bounded so a hostile token cannot cause quadratic work. Not covered: restored text placed somewhere a renderer later turns into a URL in a way these patterns do not recognise.
- Tool-call abuse: the model can request a tool call whose arguments contain pseudonyms, causing the client to execute it with real values. Implemented: `toolCalls.restore` defaults to `allowlist` with an empty list, i.e. tool arguments stay pseudonymised unless the tool is named in the policy. Setting `all` removes this protection.
- Fake pseudonyms: a model inventing a string that equals a pseudonym only causes restoration of that mapping's original into the user's own response (a local disclosure to the user, not to the provider) except in the two contexts above.
- Oversized or malformed responses: request bodies are capped (`maxBodyBytes`); provider errors are mapped to generic messages with no upstream body echoed. Response size is not separately capped (Not covered).
- Streaming: restoration holds back any tail that could still become a pseudonym, so a value split across chunks is restored correctly and a partial one is never emitted for single-space-separated pseudonyms. Known gap: a multi-word pseudonym split across a newline or other non-space whitespace can be emitted unrestored (it leaks a pseudonym to the user, never an original). Tool-call arguments are buffered and restored once complete.

### T6 Leakage through logs, telemetry, errors, tool calls and history
- Implemented: no telemetry; `scripts/check-egress.mjs` statically checks that network primitives appear only in provider adapters, the local backend client, the SDK, the CLI and the same-origin UI.
- Implemented: errors from unexpected failures return a fixed message; provider errors carry status and code only.
- Implemented: tool definitions (descriptions, enums, defaults), tool-call arguments in history (values and object keys), tool results, message `name` fields, `stop` sequences and file names are masked, and the final residual scan covers every string and key of the outbound body.
- Partial: schema fields outside the masked set (`$comment`, `pattern`, `x-*` extensions, tool function names) are forwarded as written; the residual scan still blocks them if a detector recognises a value. Matching of known values also folds zero-width characters (removed from outbound text) and NFKC look-alikes (flagged by the residual scan and blocked), but a value split by an invisible character that was joined across a word boundary is only caught by the whitespace-insensitive residual check, not masked in place.
- Implemented: the UI keeps chat history in memory only; it is not written to disk or browser storage. The in-memory "what was sent" ring holds the last 20 masked payloads and is cleared when the vault locks.
- Partial: pseudonyms are stored in the audit log never; scope identifiers are stored only as a keyed hash.
- Not covered: the provider's own retention of the masked prompts; a separate application logging its own copy of the original prompt before it reaches maskyr.

### T7 Availability and fail-closed behaviour
- Implemented: vault locked, detector error, residual finding, unsupported attachment, blocked kind, missing key → request is not sent, the client receives `{"error":{"type":"maskyr_blocked", ...}}`.
- Implemented: optional local fallback is used only when the provider fails *before any response*, and sends to the local backend, never to a second external provider. Streaming requests that fail mid-stream end with an error event; they are not retried elsewhere.
- Implemented: mask-and-commit is serialised per scope, so parallel requests in one conversation cannot assign two pseudonyms to the same original.
- Not covered: denial of service by a local process; CPU exhaustion from adversarial inputs beyond the body size cap (detectors are written to avoid catastrophic backtracking but have not been fuzzed).

## Explicit non-goals
Anonymity from the provider's account-level identity (the API key identifies the user); protection of data the user types into other applications; protection against a compromised host; legal compliance claims (GDPR, HIPAA and similar). maskyr is a risk-reduction tool, not a compliance certificate.

## Verification status
Software tests in `test/` exercise the mechanisms above against mock servers and fixtures. There has been no penetration test, no fuzzing campaign, no measured detection precision/recall on realistic data, and no verification against live providers. See `docs/STATUS.md`.
