relayvault 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
relayvault/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """RelayVault: Zero-Trust Cross-Model Task State Handoff & Redaction Ledger."""
2
+
3
+ __version__ = "0.2.0"
relayvault/access.py ADDED
@@ -0,0 +1,85 @@
1
+ """Authentication and workspace grants shared by HTTP MCP and REST.
2
+
3
+ Static bearer keys are provisioned locally, not an OAuth authorization server.
4
+ Never send these credentials to an LLM provider.
5
+ """
6
+
7
+ import hmac
8
+ import json
9
+ import os
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ from relayvault.crypto import private_path
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Principal:
18
+ name: str
19
+ grants: dict
20
+
21
+ def authorize(self, workspace: str, operation: str):
22
+ if operation not in self.grants.get(workspace, []):
23
+ raise PermissionError("Workspace permission denied")
24
+
25
+
26
+ def configured_clients() -> dict:
27
+ config = os.environ.get("RELAYVAULT_AUTH_FILE")
28
+ if config:
29
+ path = Path(config)
30
+ private_path(path)
31
+ clients = json.loads(path.read_text())
32
+ else:
33
+ key = os.environ.get("RELAYVAULT_API_KEY")
34
+ if not key:
35
+ raise RuntimeError("RELAYVAULT_API_KEY or RELAYVAULT_AUTH_FILE must be configured")
36
+ grants = os.environ.get("RELAYVAULT_WORKSPACES")
37
+ if not grants:
38
+ raise RuntimeError("Explicit RELAYVAULT_WORKSPACES grants are required for HTTP clients")
39
+ clients = {"local-client": {"key": key, "workspaces": json.loads(grants)}}
40
+ if not isinstance(clients, dict) or not clients:
41
+ raise RuntimeError("At least one HTTP client must be configured")
42
+ keys = set()
43
+ for name, config in clients.items():
44
+ if not isinstance(config, dict):
45
+ raise RuntimeError("Invalid HTTP client configuration")
46
+ key, grants = config.get("key"), config.get("workspaces")
47
+ if (
48
+ not isinstance(name, str)
49
+ or not isinstance(key, str)
50
+ or not key
51
+ or key in keys
52
+ or not isinstance(grants, dict)
53
+ ):
54
+ raise RuntimeError("Invalid HTTP client configuration or duplicate key")
55
+ keys.add(key)
56
+ for workspace, permissions in grants.items():
57
+ if (
58
+ not isinstance(workspace, str)
59
+ or workspace == "*"
60
+ or not isinstance(permissions, list)
61
+ or not permissions
62
+ or any(not isinstance(p, str) or p not in ("read", "write") for p in permissions)
63
+ ):
64
+ raise RuntimeError("HTTP grants must name explicit workspaces and read/write operations")
65
+ return clients
66
+
67
+
68
+ def authenticate(token: str) -> Principal | None:
69
+ result = None
70
+ for name, config in configured_clients().items():
71
+ if hmac.compare_digest(token.encode(), config["key"].encode()):
72
+ result = Principal(name, config["workspaces"])
73
+ return result
74
+
75
+
76
+ def verify_rehydration_key(provided: str | None):
77
+ expected = os.environ.get("RELAYVAULT_REHYDRATE_KEY")
78
+ if not expected:
79
+ raise PermissionError("REST rehydration is disabled; configure a distinct RELAYVAULT_REHYDRATE_KEY")
80
+ if any(
81
+ hmac.compare_digest(expected.encode(), item["key"].encode()) for item in configured_clients().values()
82
+ ):
83
+ raise PermissionError("Rehydration key must differ from every model-facing API key")
84
+ if provided is None or not hmac.compare_digest(provided.encode(), expected.encode()):
85
+ raise PermissionError("Invalid rehydration key")
relayvault/cli.py ADDED
@@ -0,0 +1,139 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from relayvault.engine import RelayVaultEngine
8
+ from relayvault.files import atomic_write
9
+
10
+
11
+ def main() -> None:
12
+ parser = argparse.ArgumentParser(
13
+ prog="relayvault", description="Local pattern redaction and task handoffs"
14
+ )
15
+ sub = parser.add_subparsers(dest="command", required=True)
16
+ mcp = sub.add_parser("serve-mcp")
17
+ mcp.add_argument("--transport", choices=["stdio", "sse", "streamable-http"], default="stdio")
18
+ mcp.add_argument("--port", type=int, default=8090)
19
+ mcp.add_argument("--allow-agent-rehydrate", action="store_true")
20
+ api = sub.add_parser("serve-api")
21
+ api.add_argument("--host", default="127.0.0.1")
22
+ api.add_argument("--port", type=int, default=8000)
23
+ for name in ("rehydrate-file", "dehydrate-file", "preview-file"):
24
+ p = sub.add_parser(name)
25
+ p.add_argument("--workspace", required=True)
26
+ p.add_argument("--file", required=True)
27
+ if name != "preview-file":
28
+ p.add_argument("--in-place", action="store_true")
29
+ if name == "rehydrate-file":
30
+ p.add_argument(
31
+ "--allow-partial", action="store_true", help="Explicitly allow unresolved placeholders"
32
+ )
33
+ if name == "dehydrate-file":
34
+ p.add_argument(
35
+ "--reviewed", action="store_true", help="Confirm local review when review policy is enabled"
36
+ )
37
+ log = sub.add_parser("log")
38
+ log.add_argument("--workspace", required=True)
39
+ log.add_argument("--branch")
40
+ for name in ("inspect-checkpoint", "approve-checkpoint"):
41
+ p = sub.add_parser(name)
42
+ p.add_argument("--workspace", required=True)
43
+ p.add_argument("--commit", required=True)
44
+ if name == "approve-checkpoint":
45
+ p.add_argument(
46
+ "--reviewed",
47
+ action="store_true",
48
+ required=True,
49
+ help="Confirm that you inspected this exact checkpoint locally",
50
+ )
51
+ for name in ("backup", "restore", "rotate-key", "migrate-vault"):
52
+ p = sub.add_parser(name)
53
+ p.add_argument("--destination", required=True, help="New private vault directory; must not exist")
54
+ if name == "restore":
55
+ p.add_argument("--source", required=True)
56
+ sub.add_parser("verify-vault")
57
+ args = parser.parse_args()
58
+ try:
59
+ execute(args)
60
+ except (ValueError, RuntimeError, OSError) as exc:
61
+ print(f"Error: {exc}", file=sys.stderr)
62
+ raise SystemExit(1) from None
63
+
64
+
65
+ def execute(args):
66
+ if args.command == "serve-mcp":
67
+ from relayvault.mcp_server import run_server
68
+
69
+ run_server(args.transport, args.port, args.allow_agent_rehydrate)
70
+ return
71
+ if args.command == "serve-api":
72
+ import uvicorn
73
+
74
+ from relayvault.access import configured_clients
75
+
76
+ configured_clients()
77
+ uvicorn.run("relayvault.rest_api:app", host=args.host, port=args.port, proxy_headers=False)
78
+ return
79
+ if args.command in ("migrate-vault", "restore"):
80
+ from relayvault.maintenance import migrate_vault, restore_vault
81
+
82
+ destination = Path(args.destination).absolute()
83
+ if args.command == "restore":
84
+ restore_vault(Path(args.source).absolute(), destination)
85
+ else:
86
+ migrate_vault(
87
+ Path(os.environ.get("RELAYVAULT_HOME", Path.home() / ".relayvault")).absolute(), destination
88
+ )
89
+ print(f"Verified {args.command} at {destination}; original home unchanged")
90
+ return
91
+ engine = RelayVaultEngine()
92
+ if args.command in ("rehydrate-file", "dehydrate-file", "preview-file"):
93
+ target = Path(args.file)
94
+ if target.is_symlink() or not target.is_file():
95
+ raise ValueError("Input must be a regular file, not a symlink")
96
+ if target.stat().st_size > 2_000_000:
97
+ raise ValueError("Input exceeds the 2 MB file limit")
98
+ content = target.read_bytes().decode("utf-8")
99
+ if args.command == "preview-file":
100
+ print(json.dumps(engine.preview_text(content), indent=2))
101
+ return
102
+ if args.command == "rehydrate-file":
103
+ transformed, count = engine.rehydrate_text(
104
+ args.workspace, content, allow_partial=args.allow_partial
105
+ )
106
+ else:
107
+ if engine.policy == "review" and not args.reviewed:
108
+ raise ValueError("Local review required; inspect preview-file then pass --reviewed")
109
+ transformed, count = engine.redact_text(args.workspace, content)
110
+ if args.in_place:
111
+ # Plaintext output is private regardless of the original file's group/other permissions.
112
+ mode = 0o600 if args.command == "rehydrate-file" else None
113
+ atomic_write(target, transformed.encode("utf-8"), mode=mode)
114
+ print(f"Processed {count} secret token(s) in-place in {target}")
115
+ else:
116
+ sys.stdout.buffer.write(transformed.encode("utf-8"))
117
+ elif args.command == "log":
118
+ print(json.dumps(engine.list_checkpoints(args.workspace, args.branch), indent=2))
119
+ elif args.command == "inspect-checkpoint":
120
+ state = engine.checkout_handoff(args.workspace, commit_hash=args.commit, _local_review=True)
121
+ if state is None:
122
+ raise ValueError("Checkpoint not found")
123
+ print(json.dumps(state, indent=2))
124
+ elif args.command == "approve-checkpoint":
125
+ engine.approve_checkpoint(args.workspace, args.commit)
126
+ print("Checkpoint approved for export")
127
+ elif args.command == "verify-vault":
128
+ engine.verify_all()
129
+ print("Vault integrity verified")
130
+ elif args.command in ("backup", "rotate-key"):
131
+ from relayvault.maintenance import backup_vault, rotate_key
132
+
133
+ operation = backup_vault if args.command == "backup" else rotate_key
134
+ operation(engine, Path(args.destination))
135
+ print(f"Verified {args.command} at {args.destination}; original home unchanged")
136
+
137
+
138
+ if __name__ == "__main__":
139
+ main()
relayvault/crypto.py ADDED
@@ -0,0 +1,74 @@
1
+ """Persistent local key management. Keys never appear in logs or tool responses."""
2
+
3
+ import base64
4
+ import os
5
+ import stat
6
+ import tempfile
7
+ from pathlib import Path
8
+
9
+ from cryptography.fernet import Fernet
10
+ from cryptography.hazmat.primitives import hashes
11
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
12
+
13
+ DEFAULT_SALT = b"rv-local-default-salt-2026"
14
+
15
+
16
+ def private_path(path: Path, *, directory: bool = False) -> None:
17
+ info = path.lstat()
18
+ if stat.S_ISLNK(info.st_mode) or not (
19
+ stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode)
20
+ ):
21
+ raise RuntimeError("Vault paths must be regular files/private directories, never symlinks")
22
+ if os.name == "posix" and (info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) & 0o077):
23
+ raise RuntimeError(
24
+ "Unsafe vault ownership or permissions; require owner-only access (0700 directories, 0600 files)"
25
+ )
26
+
27
+
28
+ def derive_key(master: bytes, salt: bytes, purpose: bytes) -> bytes:
29
+ return HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=purpose).derive(master)
30
+
31
+
32
+ def cipher_for(master: bytes, salt: bytes) -> Fernet:
33
+ return Fernet(base64.urlsafe_b64encode(derive_key(master, salt, b"relayvault-fernet-v1")))
34
+
35
+
36
+ def load_master(home: Path, *, create: bool) -> bytes:
37
+ home.mkdir(parents=True, exist_ok=True, mode=0o700)
38
+ private_path(home, directory=True)
39
+ key_path = home / "master.key"
40
+ if not key_path.exists() and not key_path.is_symlink():
41
+ if not create:
42
+ raise RuntimeError("master.key is missing; restore the original key and matching database")
43
+ fd, name = tempfile.mkstemp(prefix=".master-key-", dir=home)
44
+ try:
45
+ with os.fdopen(fd, "wb") as handle:
46
+ handle.write(os.urandom(32))
47
+ handle.flush()
48
+ os.fsync(handle.fileno())
49
+ try:
50
+ os.link(name, key_path)
51
+ except FileExistsError:
52
+ pass
53
+ finally:
54
+ os.unlink(name)
55
+ private_path(key_path)
56
+ # O_NOFOLLOW also protects the final component against substitution after lstat.
57
+ fd = os.open(key_path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
58
+ with os.fdopen(fd, "rb") as handle:
59
+ info = os.fstat(handle.fileno())
60
+ if os.name == "posix" and (info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) & 0o077):
61
+ raise RuntimeError("Unsafe master.key permissions")
62
+ master = handle.read()
63
+ if len(master) != 32:
64
+ raise ValueError("Invalid RelayVault master key")
65
+ return master
66
+
67
+
68
+ def get_or_create_fernet(vault_salt: bytes) -> Fernet:
69
+ home = Path(os.environ.get("RELAYVAULT_HOME", Path.home() / ".relayvault"))
70
+ return cipher_for(load_master(home, create=True), vault_salt)
71
+
72
+
73
+ def generate_vault_salt() -> bytes:
74
+ return os.urandom(32)