Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
{
"name": "datafog",
"source": "./",
"description": "Replaces personal data and credentials with reversible markers before the model sees them. Development build (0.2.0-dev)."
"description": "Replaces personal data and credentials with reversible markers before the model sees them."
}
]
}
6 changes: 3 additions & 3 deletions .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "datafog",
"displayName": "DataFog",
"description": "Keeps emails, phone numbers, card and ID numbers, API keys and other credentials out of the model's context: values in files, command output and tool results are replaced by reversible markers before Claude sees them, and swapped back locally when Claude writes. Development build; see the README for what is and is not covered.",
"version": "0.2.0-dev",
"description": "Keeps emails, phone numbers, card and ID numbers, API keys and other credentials out of the model's context: values in files, command output and tool results are replaced by reversible markers before Claude sees them, and swapped back locally when Claude writes. See the README for coverage and platform limits.",
"version": "0.2.0",
"author": {
"name": "DataFog",
"url": "https://datafog.ai"
Expand All @@ -15,7 +15,7 @@
"keep_vault_on_uninstall": {
"type": "boolean",
"title": "Keep the vault when the plugin is uninstalled",
"description": "On: the vault (the table that turns markers back into your real values) is stored in your user data folder and survives an uninstall. Off: it is stored in the plugin's data folder, which Claude Code deletes on uninstall; markers left in your files can then never be restored.",
"description": "On: the encrypted vault (the table that turns markers back into your real values) is stored in your user data folder and survives an uninstall, and its key stays in your key store. Off: it is stored in the plugin's data folder, which Claude Code deletes on uninstall; markers left in your files can then never be restored.",
"default": true
},
"unscannable_file_policy": {
Expand Down
10 changes: 6 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ jobs:
with:
python-version: ${{ matrix.python }}

- name: Install zsh (Linux)
# zsh for the shell tests; a D-Bus session, GNOME Keyring and secret-tool so that
# tests/test_keystore.py can run the key-store mode against a private Secret Service.
- name: Install zsh and a Secret Service (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y zsh
run: sudo apt-get update && sudo apt-get install -y zsh dbus gnome-keyring libsecret-tools

- name: Install the engine's one dependency and the test tools
run: python -m pip install "datafog-core>=1.4.0,<1.5" "pytest>=8" "ruff>=0.6" "mypy>=1.10"
- name: Install the engine's two dependencies and the test tools
run: python -m pip install "datafog-core>=1.7.0,<1.8" "datafog-fogvault>=1.7.0,<1.8" "pytest>=8" "ruff>=0.6" "mypy>=1.10"

- name: Manifests and hook config parse
run: |
Expand Down
3 changes: 2 additions & 1 deletion .mcp.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"env": {
"CLAUDE_PROJECT_DIR": "${CLAUDE_PROJECT_DIR}",
"DATAFOG_DATA_DIR": "${DATAFOG_DATA_DIR:-}",
"DATAFOG_VAULT_DIR": "${DATAFOG_VAULT_DIR:-}"
"DATAFOG_VAULT_DIR": "${DATAFOG_VAULT_DIR:-}",
"DATAFOG_VAULT_KEY": "${DATAFOG_VAULT_KEY:-}"
}
}
}
Expand Down
368 changes: 298 additions & 70 deletions README.md

Large diffs are not rendered by default.

9 changes: 8 additions & 1 deletion commands/doctor.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ Run exactly this command with the Bash tool, then show its output to the user un
sh "${CLAUDE_PLUGIN_ROOT}/scripts/datafog-guard" --data-dir "${CLAUDE_PLUGIN_DATA}" doctor
```

If a line starts with `[FAIL]`, explain in one or two sentences what the user should do. If the detector library is missing, the fix is to run this in a terminal and then start a new session:
If a line starts with `[FAIL]`, explain in one or two sentences what the user should do:

- "supported machine": the plugin cannot run on this computer (it needs macOS on Apple Silicon, or Linux on x86_64 with glibc 2.38 or later). The only remedy is to disable or uninstall the plugin.
- `keystore_unavailable`: the operating system's key store (macOS Keychain, or the Secret Service on Linux) is locked, not running or refused access. The user should unlock it or allow access. On a machine without a key store, the README describes the weaker `vault_key: file` setting.
- `vault_key_mismatch`, `vault_corrupt`, `vault_insecure`: say what the line says. Do not suggest deleting anything except through `/datafog:purge`, and say that purging makes existing markers unrestorable.
- "no unencrypted vault left over": an old development build left an unencrypted vault; `/datafog:purge` deletes it.

If the detector library or the vault library is missing, the fix is to run this in a terminal and then start a new session:

```
sh "${CLAUDE_PLUGIN_ROOT}/scripts/datafog-guard" --data-dir "${CLAUDE_PLUGIN_DATA}" bootstrap
Expand Down
2 changes: 1 addition & 1 deletion commands/purge.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ The user wants to delete the DataFog vault. This cannot be undone. Follow these
sh "${CLAUDE_PLUGIN_ROOT}/scripts/datafog-guard" --data-dir "${CLAUDE_PLUGIN_DATA}" purge
```

2. Tell the user plainly: the vault is the only thing that can turn markers such as `[[EMAIL_ABC123]]` back into real values. After deletion, any file, note or transcript that still contains markers can never be restored. Files that already contain the real values are not affected.
2. Tell the user plainly: this deletes the encrypted vault and removes its key from the operating system's key store (macOS Keychain or the Linux Secret Service). The vault is the only thing that can turn markers such as `[[EMAIL_ABC123]]` back into real values. After deletion, any file, note or transcript that still contains markers can never be restored. Files that already contain the real values are not affected.

3. Ask the user to reply with the exact words `delete the vault`. Stop and wait for their reply. Anything else means cancel.

Expand Down
9 changes: 6 additions & 3 deletions engine/datafog_guard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
to the real values locally when the agent writes.
"""

__version__ = "0.2.0.dev0"
__version__ = "0.2.0"

# The only runtime dependency. 1.5.0 has a known email-detection regression.
CORE_REQUIREMENT = "datafog-core>=1.4.0,<1.5"
# The detector. 1.5.0 and 1.6.0 have an email-detection regression (core #266); 1.7.0 fixed it.
CORE_REQUIREMENT = "datafog-core>=1.7.0,<1.8"
# The encrypted vault (datafog_fogvault.ApplicationVault). Released together with core; compiled
# wheels exist for macOS arm64, Linux x86_64 (glibc 2.38+) and Windows x64 only.
VAULT_REQUIREMENT = "datafog-fogvault>=1.7.0,<1.8"
APP_ID = "claude-code"
42 changes: 37 additions & 5 deletions engine/datafog_guard/ccperms.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ def managed_dirs() -> list[str]:

def config_home(env=None) -> str:
env = os.environ if env is None else env
return env.get("CLAUDE_CONFIG_DIR") or os.path.join(os.path.expanduser("~"), ".claude")
return env.get("CLAUDE_CONFIG_DIR") or os.path.join(env.get("HOME") or os.path.expanduser("~"), ".claude")


def _salvage(text: str, rules: RuleSet, source: str, source_dirs: list[str] | None = None) -> None:
Expand Down Expand Up @@ -949,6 +949,33 @@ def is_simple(command: str, markers=()) -> bool:


_TEST_EVALUATES = frozenset({"-v", "-R", "-eq", "-ne", "-lt", "-le", "-gt", "-ge", "-o", "-a"})
_PRINTF_TEXT_FORMAT = re.compile(r"(?:[^%]|%%|%[-+ #0]*[0-9]*(?:\.[0-9]+)?[sbq])*")
_NUMBER = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")


def builtin_evaluates(words: list[str]) -> bool:
"""Whether a nominally literal builtin can interpret an operand as shell arithmetic.

In zsh, `printf %d 'path[$(cmd)]'` and `exit 'path[$(cmd)]'` execute cmd even though
the shell parser sees a single-quoted argument. Plain grammar alone cannot clear them
against deny/ask rules. Numeric literals and printf text conversions do not evaluate code.
"""
if not words:
return False
name, arguments = os.path.basename(words[0]), words[1:]
if name == "test":
return any(word in _TEST_EVALUATES for word in arguments)
if name == "exit":
return any(not _NUMBER.fullmatch(word) for word in arguments)
if name != "printf":
return False
if any(word.startswith("-v") for word in arguments):
return True
if arguments[:1] == ["--"]:
arguments = arguments[1:]
if not arguments or _PRINTF_TEXT_FORMAT.fullmatch(arguments[0]):
return False
return any(not _NUMBER.fullmatch(word) for word in arguments[1:])


def allow_rule_for(rules: RuleSet, command: str, exact_only: bool = False) -> Rule | None:
Expand All @@ -961,10 +988,9 @@ def allow_rule_for(rules: RuleSet, command: str, exact_only: bool = False) -> Ru
# an exact-match rule for the full command string". STRICTER: the same for every wrapper, including
# the ones Claude Code strips (the docs do not say whether the unstripped text is matched as well),
# for shells and eval, and for a command name that is quoted or escaped.
# `test -v 'x[$(cmd)]'`, an arithmetic operand of test, and `printf -v 'x[$(cmd)]'` make bash evaluate
# the operand. Claude Code's own wildcard rule would approve them; STRICTER: only an exact rule does here.
evaluates = (name == "test" and any(plain in _TEST_EVALUATES for _, plain in words[1:])) or \
(name == "printf" and any(plain.startswith("-v") for _, plain in words[1:]))
# Some builtins evaluate even single-quoted operands as arithmetic. STRICTER: without a
# restrictive rule only an exact allow rule can approve them; with one the caller asks firmly.
evaluates = builtin_evaluates([plain for _, plain in words])
needs_exact = exact_only or evaluates or not unquoted or name in WRAPPERS or name in SHELLS or name == "eval" or \
name in ("watch", "setsid", "ionice", "flock") or \
(name == "find" and any(plain in _FIND_ACTIONS for _, plain in words[1:]))
Expand Down Expand Up @@ -1304,6 +1330,12 @@ def ask(step: int, reason: str, found: Rule | None = None, firm: bool = False) -
if markers and egress:
return ask(5, f"DataFog: this command would run with real values ({markers}) and looks like it sends data "
"to another machine.")
if parsed is not None and any(builtin_evaluates([word.text for word in simple.words])
for simple in parsed.commands) \
and (rules.deny or rules.ask or rules.paths or rules.block_outside_reads):
return ask(6, "DataFog: a shell builtin can evaluate an operand as arithmetic, including commands "
"inside a quoted argument, so the plugin cannot clear it against your deny or ask "
"rules. It is not approved without a prompt in any permission mode.", firm=True)
unsupported = [rule for rule in rules.paths if rule.unsupported]
if parsed is None:
# Never allow, never "no decision" while a rule exists the plugin could be misreading the command
Expand Down
88 changes: 76 additions & 12 deletions engine/datafog_guard/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,26 @@ def _problem(error: BaseException) -> str:
return f"{error.code}: {error.user_message}" if isinstance(error, GuardError) else safe_code(error)


PROTECTION_TEXT = {
"credential_store": "encrypted; the key is in the operating system's key store (macOS Keychain, or the "
"Secret Service on Linux)",
"file_key": "encrypted, but the key is a file beside the data (vault_key: file): anyone who can read the "
"vault directory can read the vault",
}
LEGACY_TEXT = ("an UNENCRYPTED vault from a development build is still in the vault directory. This version "
"cannot read it; delete it with /datafog:purge")


def status_report(for_model: bool = False) -> str:
settings = config.load()
lines = [f"DataFog guard {__version__}"]
protection = None
try:
from .engine import open_vault
vault, _ = open_vault(settings)
health = vault.health()
entries = vault.entry_counts()
protection = health["protection"]
lines.append("Protection: ON")
lines.append(f"Values held in the vault: {sum(entries.values())} ({describe_counts(entries)})")
lines.append(f"Vault revision: {health['revision']}")
Expand All @@ -37,7 +49,11 @@ def status_report(for_model: bool = False) -> str:
lines.append(f"Vault location: {place}")
if not for_model:
lines.append(f"Vault path: {settings.vault_dir}")
lines.append("Vault encryption at rest: NONE in this version (owner-only file permissions)")
lines.append("Vault encryption at rest: " + (PROTECTION_TEXT.get(protection, str(protection)) if protection
else "the vault could not be opened"))
from .store import legacy_plain_store, vault_path
if legacy_plain_store(vault_path(settings.vault_dir)):
lines.append("WARNING: " + LEGACY_TEXT)
lines.append(f"Detected types: {', '.join(settings.entities)}")
lines.append("Not detected: names of people, addresses without a label, anything in images or PDFs")
lines.append(f"Allowlisted exact values: {len(settings.allowlist)}")
Expand All @@ -60,13 +76,18 @@ def status_report(for_model: bool = False) -> str:

def purge(argv: list[str]) -> int:
settings = config.load()
from .store import FileVaultStore
store = FileVaultStore(settings.vault_dir)
from .engine import open_store
from .store import KEYSTORE_SERVICE
store = open_store(settings)
info = store.describe()
if "--confirm" not in argv:
print("This deletes the DataFog vault at:")
print(f" {settings.vault_dir}")
print(f"Current state: {info.get('state')}, revision {info.get('revision', 0)}.")
if info.get("protection") == "credential_store":
print("Its key is removed from the operating system's key store as well.")
if info.get("legacy_plain_store"):
print("The unencrypted vault of a development build in the same directory is deleted too.")
print("After that, every marker issued so far is meaningless: text that still holds markers")
print("(files Claude wrote with markers, old transcripts, notes) can NEVER be turned back into")
print("the real values. Files on disk that already hold real values are not affected.")
Expand All @@ -77,14 +98,28 @@ def purge(argv: list[str]) -> int:
print(f"Not confirmed; nothing was deleted. The confirmation word is {PURGE_WORD}.")
return 1
try:
existed = store.purge()
shutil.rmtree(settings.shadow_dir, ignore_errors=True)
result = store.purge()
if os.path.islink(settings.shadow_dir):
os.unlink(settings.shadow_dir)
else:
try:
shutil.rmtree(settings.shadow_dir)
except FileNotFoundError:
pass
except Exception as error:
print(f"The vault could not be deleted ({_problem(error)}).")
return 1
print("The vault was deleted." if existed else "There was no vault to delete.")
print("The vault was deleted." if result["existed"] or result["legacy"] else "There was no vault to delete.")
if result["legacy"]:
print("The unencrypted vault of a development build was deleted.")
if result["keystore"] == "removed":
print("Its key was removed from the operating system's key store.")
elif result["keystore"] == "left":
print("Its key could not be removed from the operating system's key store. It opens nothing now that the")
print(f"vault file is gone. To remove it by hand, delete the entry with service \"{KEYSTORE_SERVICE}\"")
print(f"and account \"{result['account']}\" (macOS: Keychain Access; Linux: Seahorse or secret-tool).")
print("Markers issued before now can no longer be restored. A new, empty vault is created on next use.")
return 0
return 1 if result["keystore"] == "left" else 0


def _claude_version() -> tuple[int, ...] | None:
Expand Down Expand Up @@ -112,6 +147,11 @@ def check(name: str, ok, detail: str = "") -> None:

print(f"DataFog guard {__version__} doctor")
check("Python 3.10 or later", sys.version_info >= (3, 10), sys.version.split()[0])
from . import VAULT_REQUIREMENT
from .support import UNSUPPORTED, platform_problem
problem = platform_problem()
check("supported machine (macOS on Apple Silicon, or Linux x86_64 with glibc 2.38 or later)", not problem,
f"{problem}. {UNSUPPORTED}" if problem else "")
try:
started = time.perf_counter()
from importlib.metadata import version
Expand All @@ -123,22 +163,46 @@ def check(name: str, ok, detail: str = "") -> None:
check("configured entity types are supported", not missing, ", ".join(missing))
except Exception as error:
check("detector library", False, safe_code(error) + "; run the bootstrap command shown at session start")
try:
started = time.perf_counter()
from importlib.metadata import version

import datafog_fogvault # noqa: F401
check(f"vault library ({VAULT_REQUIREMENT})", True, f"datafog-fogvault {version('datafog-fogvault')}, "
f"import {1000 * (time.perf_counter() - started):.1f} ms")
except Exception as error:
check("vault library", False, safe_code(error) + ("" if problem else
"; run the bootstrap command shown at session start"))
check("configuration files", not settings.problems, "; ".join(settings.problems))
from .store import legacy_plain_store, vault_path
protection = None
try:
from .engine import open_vault
vault, _ = open_vault(settings)
started = time.perf_counter()
vault.health()
check("vault opens, lock works, detector finds a test value", True,
protection = vault.health()["protection"]
check("vault opens (private files, lock, key, decryption) and the detector finds a test value", True,
f"{1000 * (time.perf_counter() - started):.1f} ms")
text, counts = vault.tokenize("doctor probe.synthetic@example.com")
check("tokenize and restore round trip", vault.restore(text).text == "doctor probe.synthetic@example.com")
except Exception as error:
check("vault and detector", False, _problem(error))
if os.name != "nt" and os.path.isdir(settings.vault_dir):
mode = os.stat(settings.vault_dir).st_mode & 0o777
directory = vault_path(settings.vault_dir)
if os.name != "nt" and os.path.isdir(directory):
mode = os.stat(directory).st_mode & 0o777
check("vault directory is owner-only", mode == 0o700, oct(mode))
check("vault encryption at rest", None, "none in this version")
loose = sorted(name for name in os.listdir(directory)
if os.path.isfile(os.path.join(directory, name))
and os.stat(os.path.join(directory, name)).st_mode & 0o077)
check("vault files are owner-only", not loose, ", ".join(loose))
if protection == "credential_store":
check("vault encryption at rest", True, PROTECTION_TEXT[protection])
elif protection == "file_key":
check("vault encryption at rest", None, PROTECTION_TEXT[protection])
else:
check("vault encryption at rest", False, "the vault could not be opened, so nothing can be said")
if legacy_plain_store(directory):
check("no unencrypted vault left over", False, LEGACY_TEXT)
check("vault location", None, f"{settings.vault_location}: {settings.vault_dir}")
for name in ("launcher", "wrap_script"):
check(f"plugin file {os.path.basename(getattr(settings, name))}", os.path.exists(getattr(settings, name)))
Expand Down
Loading
Loading