Metadata-Version: 2.4
Name: nxd
Version: 0.3.7
Summary: Encrypted compute layer for AI agents
Author: Nexplora Labs
License-Expression: LicenseRef-Nexplora-Proprietary
Project-URL: Homepage, https://github.com/Nexploraai/nxd
Project-URL: Repository, https://github.com/Nexploraai/nxd
Project-URL: Issues, https://github.com/Nexploraai/nxd/issues
Keywords: fhe,encryption,ai-agents,privacy,homomorphic-encryption
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=42.0.0
Requires-Dist: mcp>=1.28.1
Requires-Dist: numpy>=1.26.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: portalocker>=3.2.0
Requires-Dist: scikit-learn>=1.5.0
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Provides-Extra: fhe
Requires-Dist: concrete-ml==1.9.0; extra == "fhe"
Dynamic: license-file

# NXD 0.3.7

NXD is an encrypted compute layer for AI agents. It wraps fully homomorphic encryption, credential vaulting, privacy primitives, and operator-only reveal flows behind a single Python import so developers can run agents on sensitive data without exposing client records, credentials, or proprietary code to models, clouds, or MCP servers.

## Three guarantees

1. **The agent works fully** - capability unchanged; scores, matches, charges, and aggregates complete normally.
2. **The agent sees nothing** - when `shield()` is used for full payload encryption. `vault.safe_use()` prevents credential leakage from callbacks. `redact()` reduces PII exposure but is not a guarantee wall.
3. **The operator holds the keys** - keys stay local, auditable, and revocable.

## Install

```bash
export NXD_OPERATOR_PASSPHRASE="NXD-2026-Nexplora-Secure!"
pip install nxd==0.3.7
```

Requires Python 3.10 or 3.11 for the FHE path (`concrete-ml`).

## Passphrase Requirements

`NXD_OPERATOR_PASSPHRASE` must be:

- At least 12 characters
- A mix of letters, numbers, and symbols
- Not a common word or phrase

Strong example: `NXD-2026-Nexplora-Secure!`

Weak examples rejected at startup: `nexplora2026`, `password123`

Your vault security depends entirely on passphrase strength. A weak passphrase is vulnerable to offline dictionary attacks if the vault files are obtained.

## Quick start

```python
import nxd

# 1. Shield code before any AI call
code = "api_key = 'sk_live_xxxx'"
shielded = nxd.shield(code)
recovered = nxd.unshield(shielded)
print(f"AI sees:  {shielded[:40]}...")
print(f"You see:  {recovered}")
print(f"Match:    {code == recovered}")

# 2. Redact PII before sending to AI
note = "Patient John Smith, DOB 1985-04-12, SSN 432-11-5678"
clean, mapping = nxd.redact(note)
print(f"\nAI gets:  {clean}")
print(f"Original: {nxd.deredact(clean, mapping)}")

# 3. Vault a credential and use it without returning it
vault = nxd.Vault(agent_id="my-agent")
vault.store("stripe_key", "sk_live_xxxx")
result = vault.safe_use(
    "stripe_key",
    lambda key: {"status": "charged", "auth_len": len(key)},
)
print(f"\nAgent got: {result}")
print("Key seen:  never")

# 4. Verify tamper-proof audit chain
nxd.audit.log("session", agent_id="my-agent")
print(f"\nAudit valid: {nxd.audit.verify()}")
```

## Redaction

`redact()` returns both the safe text and the local restoration mapping:

```python
import nxd

safe, mapping = nxd.redact("Patient John Smith, SSN 432-11-5678")
restored = nxd.deredact(safe, mapping)
print(safe)
print(restored)
```

`redact()` catches common PII and secret formats including emails, phone numbers, SSNs, many API key families, bearer tokens, physician names, dates, and account numbers.

Important: `redact()` is pattern-based detection. It reduces exposure, but it is not a guaranteed wall. For complete payload protection, combine it with `shield()`.

## Security Model

### Memory Safety

NXD provides `SecureString` for credential handling and `secure_store()` for best-effort zeroing after storage.

```python
import nxd

vault = nxd.Vault(agent_id="memory-safe")

with nxd.SecureString("sk_live_xxxx") as secret:
    vault.store("api_key", secret.read())

credential = bytearray(b"sk_live_buffered_secret")
vault.secure_store("buffered_key", credential)
print(vault.use("api_key", lambda value: len(value)))
```

Honest caveat: Python string interning and garbage collection mean zero-on-delete is best-effort, not guaranteed. The strongest protection is to avoid loading secrets into Python strings at all:

```python
import os
import nxd

vault = nxd.Vault(agent_id="env-pop")
os.environ["API_KEY"] = "sk_live_env_secret"
vault.store("api_key", os.environ.pop("API_KEY"))
print("API_KEY" in os.environ)
```

### Callback Safety

Use `safe_use()` in production to detect accidental credential leakage in callback return values.

```python
import nxd

vault = nxd.Vault(agent_id="callback-safe")
vault.store("stripe_key", "sk_live_xxxx")

try:
    vault.safe_use("stripe_key", lambda key: {"status": "ok", "key": key})
except nxd.CredentialLeakError as exc:
    print(type(exc).__name__)

result = vault.safe_use(
    "stripe_key",
    lambda key: {"status": "charged", "auth_len": len(key)},
)
print(result)
```

`use()` still exists when you need callback flexibility, but callbacks must use credentials, not return them.

### Audit Integrity

The audit chain is protected against:

- Entry modification via HMAC-signed entries
- Entry injection via sequential hash verification
- Entry reordering via chained previous-hash checks
- Entry truncation via a signed manifest with entry count and tail hash

If the manifest is lost, recover it explicitly:

```python
import nxd

nxd.audit.log("example", agent_id="recover-demo")
print(nxd.audit.verify())
print(nxd.audit.recover())
print(nxd.audit.verify())
```

CLI equivalent:

```bash
nxd audit-recover
```

Back up `~/.nxd/` regularly. Losing `master.key` means losing access to vaulted data.

## Import Surface

```python
import nxd

with nxd.SecureString("sk_live_xxxx") as secret:
    vault = nxd.Vault(agent_id="imports")
    vault.store("key", secret.read())

vault.secure_store("key", bytearray(b"sk_live_buffer"))
vault.safe_use("key", lambda credential: {"status": "ok", "len": len(credential)})

print(nxd.CredentialLeakError.__name__)
print(nxd.VaultError.__name__)
print(nxd.audit.recover())
```

## Handoff tokens

Handoff tokens are single-use. A token that has already been unpacked raises `ReplayError` if it is unpacked again.

```python
import nxd

handoff = nxd.Handoff()
token = handoff.pack({"client": "Jane Doe", "balance": 50000})
payload = handoff.unpack(token)
print(payload)
```

For multi-agent workflows where the same context is needed by multiple agents, pack a separate token for each agent.

## Audit export

```python
import nxd

nxd.audit.log("docs-example", agent_id="my-agent")
nxd.audit.export("audit_report.json")
print("export works")
```

## Benchmarks (MacBook Air, Python 3.11, Concrete ML 1.9.0)

| Operation | Latency | Notes |
|-----------|---------|-------|
| FHE score (1 record) | ~183 ms | First-call cold start |
| FHE score (1k records, parallel) | 1.6 s | 8 cores, ~1.6 ms/record |
| FHE match (single pair) | 352 ms | Cross-system comparison |
| FHE aggregate (1k records, parallel) | 1.8 s | ~0.009% quantization error |
| Credential vault use | <1 ms | Decrypt in memory only |
| Proof suite | 96/96 passed | `python3 prove.py` |
| Real-world simulation | 34/34 passed | `python3 realworld.py` |
| Pytest suite | 62 passed | `pytest -q` |

## What NXD does not protect against

NXD protects credentials and sensitive data from AI providers, model context, and ordinary cloud exposure. It does not remove the need for normal endpoint security and key management discipline.

- Local machine compromise still defeats local key custody. `master.key` lives on your machine. If your machine is compromised, keys are at risk. Hosted key management is planned for `v0.4.0`.
- `split()` and `blur()` are pending external cryptographic review. All other primitives wrap vetted libraries such as `Fernet`, `Ed25519`, `PBKDF2`, and `Concrete ML`.
- `redact()` remains best-effort pattern detection. It catches many common formats, but unusual or context-dependent secrets can still be missed.
- `SecureString` and `secure_store()` are best-effort mitigations inside CPython. Python string interning and garbage collection mean the strongest protection is still to avoid creating long-lived plaintext strings in the first place.
- NXD uses FHE for specific compute operations such as `score`, `match`, and `aggregate`. It does not run the full LLM context window under FHE.
- NXD does not protect against a trusted operator with physical access, because that operator holds the keys by design.
- Current encryption choices are not presented as quantum-resistant. Post-quantum primitives are not part of the current release.

## Operator workflow

Set `NXD_OPERATOR_PASSPHRASE` before using the vault, audit chain, signatures, or any operator-only reveal flow. NXD stores ciphertext at rest, and local key files are wrapped with a PBKDF2-derived key from that operator passphrase.

When you use `nxd init`, NXD can vault `.env` secrets, replace them with `NXD_VAULT::NAME` references, and write an encrypted `.env.backup.nxd` recovery file.

On the MCP path, decrypt-style tools such as `nxd_unshield`, `nxd_unseal_text`, and `nxd_detokenize` no longer return plaintext to the agent. They queue an operator-only reveal:

```bash
nxd reveal <reveal_id>
```

## Roadmap

### v0.3.x shipped

- Agent vault isolation
- Concurrent vault safety
- Passphrase strength enforcement
- API key redaction coverage
- Audit truncation detection
- Uniform `VaultError` messages
- `SecureString` memory-safety helpers
- `safe_use()` callback leak detection
- Audit manifest recovery

### v0.4.0

- Hosted key management (`HashiCorp Vault`, `AWS KMS`)
- `nxd.Vault(hosted=True)`

### v0.5.0

- External cryptographic audit of `split()` and `blur()`
- Formal security certification

### v0.6.0

- Hardware-accelerated FHE on GPU/TPU
- Sub-10 ms encrypted inference

## Development

```bash
git clone https://github.com/Nexploraai/nxd
cd nxd
pip install -e ".[dev]"
python3 prove.py
pytest -q
python3 realworld.py
```

## License

Proprietary - Nexplora Labs. Free to use in projects, but the source may not be modified, redistributed, resold, or used to build a competing encryption or agent-protection product. See [LICENSE](LICENSE).
