data-vault-mcp 0.1.0__tar.gz

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.
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.5
2
+ Name: data-vault-mcp
3
+ Version: 0.1.0
4
+ Summary: Local MCP tools for Confidential Agentic Data Vault
5
+ Project-URL: Repository, https://github.com/aptos-labs/agentic-data-vault
6
+ Project-URL: Homepage, https://private-vault-web-6vgsvc5oma-uc.a.run.app/
7
+ Requires-Python: <3.14,>=3.12
8
+ Requires-Dist: anyio<5,>=4.5
9
+ Requires-Dist: aptos-sdk<0.13,>=0.12.2
10
+ Requires-Dist: cryptography<51,>=50.0.1
11
+ Requires-Dist: httpx<1,>=0.28
12
+ Requires-Dist: mcp==2.2.0
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Private Vault
16
+
17
+ Private storage for agent logs, scoped memories and attachments.
18
+ This is the independent `private-vault` branch.
19
+
20
+ **[Design and API — review and comment in Notion](https://www.notion.so/4168b846eb72814592c3fadf9db02995)**
21
+
22
+ [Repository snapshot](docs/private-vault-service-design.md).
23
+
24
+ [Try the prototype](https://private-vault-web-6vgsvc5oma-uc.a.run.app/).
25
+ Use synthetic data: real on-chain attestation verification is still a production dependency.
26
+
27
+ The current service runs one serving CVM per assigned vault in a pool,
28
+ with an ordinary keeper and opaque relay. Its browser lives in
29
+ `web-private-vault/`; `examples/private_vault_client.py` is the API reference client.
30
+ Inherited `portal/` targets an older architecture; the MCP below targets this service.
31
+
32
+ ## Connect an agent harness
33
+
34
+ Create/export an API key in the [prototype website](https://private-vault-web-6vgsvc5oma-uc.a.run.app/), then run (after the first PyPI release):
35
+
36
+ ```sh
37
+ uvx --python 3.12 data-vault-mcp@latest setup atlas # or codex, both, claude, generic
38
+ ```
39
+
40
+ Setup privately prompts for the key once. Alternatively pass `--api-key-file /path/to/key`
41
+ with a 0600 Ed25519 seed file or the website's downloaded Ed25519 JWK. Deployment
42
+ URLs, module address and operational Client keys are bundled; no node/gas key or
43
+ npm setup is needed on the user device. Atlas local-clone virtualenvs and Codex's
44
+ application bundle are detected even when their CLIs are absent from PATH.
45
+ The registered MCP is named **data-vault**. Restart/reload your harness after setup.
46
+ Its registered command uses `uv tool run --python 3.12 data-vault-mcp@latest`.
47
+ Each new MCP process resolves the latest stable PyPI release and uses a cached
48
+ environment if it is unchanged. Already-running processes keep their current version.
49
+ No source clone is needed after setup. A release-resolution failure is reported;
50
+ setup does not silently fall back to old source code or change the registration.
51
+ Rerun setup once to migrate a previous local-checkout installation.
52
+
53
+ At the start of each conversation the model shows vault names/intents and asks
54
+ which may automatically receive relevant records. `start_vault_session` records
55
+ that choice in memory; an empty choice keeps all writes manual. Unselected
56
+ writes, file uploads, forget and sharing changes require specific approval.
57
+ Changed intents revoke automatic selection and trigger `tools/list_changed`.
58
+ These are conversational choices reported by the model, not proof of a human
59
+ click; use the harness's write-tool confirmation UI when that is required.
60
+ Reads and search work without auto-write selection, by vault ID or exact name.
61
+ `add_record` accepts local `file_paths`; `download_attachment` returns a local
62
+ file path for the harness's normal viewers/file tools, regardless of file type.
63
+
64
+ The installer allows attachment files under your home directory by default;
65
+ `--allow-dir /path` narrows it (repeat for multiple directories). The standalone
66
+ `data-vault-mcp` defaults to its working directory. The configured API-key file
67
+ cannot be uploaded or overwritten. Downloads preserve existing destinations
68
+ unless `overwrite` is explicitly requested.
69
+
70
+ Keys live under `~/.config/confidential-vault-6038be20/`, separate from c26t's old
71
+ deployments. `get_mcp_version` reports the running code/deployment and private
72
+ log file. Logs live under `~/Library/Logs/confidential-vault-6038be20/` on macOS,
73
+ or `$XDG_STATE_HOME/confidential-vault-6038be20/` (default `~/.local/state/`) on Linux;
74
+ logs omit credentials, queries, record text, files and exception messages.
75
+
76
+ ```sh
77
+ uvx --python 3.12 data-vault-mcp@latest setup atlas --uninstall
78
+ ```
79
+
80
+ Uninstall unregisters only **data-vault**, retaining credentials and downloads.
81
+ The inherited c26t installer remains available as `scripts/install_legacy_mcp.py`;
82
+ its keys, registrations and endpoints are not reused by the new MCP.
83
+
84
+ For development, `./scripts/install_mcp.py atlas --local` explicitly registers this
85
+ checkout. Without `--local`, that script installs the same auto-updating release
86
+ entry as the package's `setup` command.
87
+
88
+ ## MCP releases
89
+
90
+ The standalone `data-vault-mcp` package uses `mcp/pyproject.toml`. The release
91
+ stager copies only tracked client modules and stamps their source commit/version;
92
+ ACE, embedding models and worker runtime dependencies are excluded. CI builds the
93
+ sdist and wheel, checks metadata, and exercises the installed wheel's setup and
94
+ stdio entry points in a fresh environment.
95
+
96
+ Publishing follows ACE's GitHub OIDC Trusted Publisher pattern; no PyPI API token
97
+ is stored in GitHub. Before the first upload, add a pending publisher at
98
+ [PyPI Publishing](https://pypi.org/manage/account/publishing/) with:
99
+
100
+ | Field | Value |
101
+ | --- | --- |
102
+ | PyPI project | `data-vault-mcp` |
103
+ | GitHub owner | `aptos-labs` |
104
+ | Repository | `agentic-data-vault` |
105
+ | Workflow filename | `publish-mcp.yml` |
106
+ | Environment | `pypi` |
107
+
108
+ For TestPyPI, configure the same project/workflow with environment `testpypi` at
109
+ [TestPyPI Publishing](https://test.pypi.org/manage/account/publishing/).
110
+ The workflow is `.github/workflows/publish-mcp.yml`. Branch/PR runs only build and
111
+ test. Manual runs default to `target=check`; choose `testpypi` or `pypi` to upload
112
+ and optionally specify a version. Pushing `mcp-v0.1.0` publishes version `0.1.0` to
113
+ PyPI. PyPI versions are immutable; use a new version for each subsequent release.
@@ -0,0 +1,99 @@
1
+ # Private Vault
2
+
3
+ Private storage for agent logs, scoped memories and attachments.
4
+ This is the independent `private-vault` branch.
5
+
6
+ **[Design and API — review and comment in Notion](https://www.notion.so/4168b846eb72814592c3fadf9db02995)**
7
+
8
+ [Repository snapshot](docs/private-vault-service-design.md).
9
+
10
+ [Try the prototype](https://private-vault-web-6vgsvc5oma-uc.a.run.app/).
11
+ Use synthetic data: real on-chain attestation verification is still a production dependency.
12
+
13
+ The current service runs one serving CVM per assigned vault in a pool,
14
+ with an ordinary keeper and opaque relay. Its browser lives in
15
+ `web-private-vault/`; `examples/private_vault_client.py` is the API reference client.
16
+ Inherited `portal/` targets an older architecture; the MCP below targets this service.
17
+
18
+ ## Connect an agent harness
19
+
20
+ Create/export an API key in the [prototype website](https://private-vault-web-6vgsvc5oma-uc.a.run.app/), then run (after the first PyPI release):
21
+
22
+ ```sh
23
+ uvx --python 3.12 data-vault-mcp@latest setup atlas # or codex, both, claude, generic
24
+ ```
25
+
26
+ Setup privately prompts for the key once. Alternatively pass `--api-key-file /path/to/key`
27
+ with a 0600 Ed25519 seed file or the website's downloaded Ed25519 JWK. Deployment
28
+ URLs, module address and operational Client keys are bundled; no node/gas key or
29
+ npm setup is needed on the user device. Atlas local-clone virtualenvs and Codex's
30
+ application bundle are detected even when their CLIs are absent from PATH.
31
+ The registered MCP is named **data-vault**. Restart/reload your harness after setup.
32
+ Its registered command uses `uv tool run --python 3.12 data-vault-mcp@latest`.
33
+ Each new MCP process resolves the latest stable PyPI release and uses a cached
34
+ environment if it is unchanged. Already-running processes keep their current version.
35
+ No source clone is needed after setup. A release-resolution failure is reported;
36
+ setup does not silently fall back to old source code or change the registration.
37
+ Rerun setup once to migrate a previous local-checkout installation.
38
+
39
+ At the start of each conversation the model shows vault names/intents and asks
40
+ which may automatically receive relevant records. `start_vault_session` records
41
+ that choice in memory; an empty choice keeps all writes manual. Unselected
42
+ writes, file uploads, forget and sharing changes require specific approval.
43
+ Changed intents revoke automatic selection and trigger `tools/list_changed`.
44
+ These are conversational choices reported by the model, not proof of a human
45
+ click; use the harness's write-tool confirmation UI when that is required.
46
+ Reads and search work without auto-write selection, by vault ID or exact name.
47
+ `add_record` accepts local `file_paths`; `download_attachment` returns a local
48
+ file path for the harness's normal viewers/file tools, regardless of file type.
49
+
50
+ The installer allows attachment files under your home directory by default;
51
+ `--allow-dir /path` narrows it (repeat for multiple directories). The standalone
52
+ `data-vault-mcp` defaults to its working directory. The configured API-key file
53
+ cannot be uploaded or overwritten. Downloads preserve existing destinations
54
+ unless `overwrite` is explicitly requested.
55
+
56
+ Keys live under `~/.config/confidential-vault-6038be20/`, separate from c26t's old
57
+ deployments. `get_mcp_version` reports the running code/deployment and private
58
+ log file. Logs live under `~/Library/Logs/confidential-vault-6038be20/` on macOS,
59
+ or `$XDG_STATE_HOME/confidential-vault-6038be20/` (default `~/.local/state/`) on Linux;
60
+ logs omit credentials, queries, record text, files and exception messages.
61
+
62
+ ```sh
63
+ uvx --python 3.12 data-vault-mcp@latest setup atlas --uninstall
64
+ ```
65
+
66
+ Uninstall unregisters only **data-vault**, retaining credentials and downloads.
67
+ The inherited c26t installer remains available as `scripts/install_legacy_mcp.py`;
68
+ its keys, registrations and endpoints are not reused by the new MCP.
69
+
70
+ For development, `./scripts/install_mcp.py atlas --local` explicitly registers this
71
+ checkout. Without `--local`, that script installs the same auto-updating release
72
+ entry as the package's `setup` command.
73
+
74
+ ## MCP releases
75
+
76
+ The standalone `data-vault-mcp` package uses `mcp/pyproject.toml`. The release
77
+ stager copies only tracked client modules and stamps their source commit/version;
78
+ ACE, embedding models and worker runtime dependencies are excluded. CI builds the
79
+ sdist and wheel, checks metadata, and exercises the installed wheel's setup and
80
+ stdio entry points in a fresh environment.
81
+
82
+ Publishing follows ACE's GitHub OIDC Trusted Publisher pattern; no PyPI API token
83
+ is stored in GitHub. Before the first upload, add a pending publisher at
84
+ [PyPI Publishing](https://pypi.org/manage/account/publishing/) with:
85
+
86
+ | Field | Value |
87
+ | --- | --- |
88
+ | PyPI project | `data-vault-mcp` |
89
+ | GitHub owner | `aptos-labs` |
90
+ | Repository | `agentic-data-vault` |
91
+ | Workflow filename | `publish-mcp.yml` |
92
+ | Environment | `pypi` |
93
+
94
+ For TestPyPI, configure the same project/workflow with environment `testpypi` at
95
+ [TestPyPI Publishing](https://test.pypi.org/manage/account/publishing/).
96
+ The workflow is `.github/workflows/publish-mcp.yml`. Branch/PR runs only build and
97
+ test. Manual runs default to `target=check`; choose `testpypi` or `pypi` to upload
98
+ and optionally specify a version. Pushing `mcp-v0.1.0` publishes version `0.1.0` to
99
+ PyPI. PyPI versions are immutable; use a new version for each subsequent release.
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "data-vault-mcp"
3
+ version = "0.1.0"
4
+ description = "Local MCP tools for Confidential Agentic Data Vault"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12,<3.14"
7
+ dependencies = [
8
+ "anyio>=4.5,<5",
9
+ "aptos-sdk>=0.12.2,<0.13",
10
+ "cryptography>=50.0.1,<51",
11
+ "httpx>=0.28,<1",
12
+ "mcp==2.2.0",
13
+ ]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/aptos-labs/agentic-data-vault"
17
+ Homepage = "https://private-vault-web-6vgsvc5oma-uc.a.run.app/"
18
+
19
+ [project.scripts]
20
+ data-vault-mcp = "c26t.vault_mcp_entry:main"
21
+
22
+ [build-system]
23
+ requires = ["hatchling>=1.27,<2"]
24
+ build-backend = "hatchling.build"
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/c26t"]
28
+
29
+ [tool.hatch.build.targets.sdist]
30
+ include = ["pyproject.toml", "README.md", "src/c26t"]
@@ -0,0 +1 @@
1
+ """C26T: a prototype attested agentic data vault."""
@@ -0,0 +1 @@
1
+ {"git_revision": "17d9de4a342d9a2cbf78077c6fc57d91dae29828", "git_dirty": false, "source_sha256": "bab5226ed4836a58df41c9acef2f2cd36b345ed54ebac81cfe7fdca5a649874f", "package_version": "0.1.0", "self_reported": true}
@@ -0,0 +1,67 @@
1
+ """Bounded public version schema. Build stamps are reports, not attestation proofs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ PUBLIC_FIELDS = frozenset(
12
+ {
13
+ "git_revision",
14
+ "git_dirty",
15
+ "source_sha256",
16
+ "package_version",
17
+ "started_at_utc",
18
+ "provenance",
19
+ "self_reported",
20
+ }
21
+ )
22
+
23
+
24
+ def valid_hex(value: object, length: int) -> bool:
25
+ return isinstance(value, str) and re.fullmatch(f"[0-9a-f]{{{length}}}", value) is not None
26
+
27
+
28
+ def source_digest(package_dir: Path) -> str:
29
+ """Hash exact Python source bytes/names; exclude generated JSON and bytecode."""
30
+ digest = hashlib.sha256()
31
+ for path in sorted(package_dir.rglob("*.py")):
32
+ digest.update(path.relative_to(package_dir).as_posix().encode())
33
+ digest.update(b"\0")
34
+ digest.update(path.read_bytes())
35
+ return digest.hexdigest()
36
+
37
+
38
+ def validate_public_metadata(value: object) -> dict[str, Any]:
39
+ """Reject unknown keys, paths and malformed remote version reports."""
40
+ if not isinstance(value, dict) or set(value) != PUBLIC_FIELDS:
41
+ raise ValueError("invalid component version fields")
42
+ for key, length in (("git_revision", 40), ("source_sha256", 64)):
43
+ if value[key] is not None and not valid_hex(value[key], length):
44
+ raise ValueError("invalid component version digest")
45
+ if value["git_dirty"] is not None and type(value["git_dirty"]) is not bool:
46
+ raise ValueError("invalid component version dirty state")
47
+ if value["provenance"] not in ("checkout", "build_stamp", "unknown"):
48
+ raise ValueError("invalid component version provenance")
49
+ version = value["package_version"]
50
+ if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9.+_-]{1,128}", version):
51
+ raise ValueError("invalid component package version")
52
+ started = value["started_at_utc"]
53
+ if not isinstance(started, str) or len(started) > 40:
54
+ raise ValueError("invalid component start time")
55
+ try:
56
+ parsed = datetime.fromisoformat(started)
57
+ if parsed.utcoffset() is None or parsed.utcoffset().total_seconds() != 0:
58
+ raise ValueError("not UTC")
59
+ except ValueError as exc:
60
+ raise ValueError("invalid component start time") from exc
61
+ if value["provenance"] == "unknown" and value["git_revision"] is not None:
62
+ raise ValueError("unknown provenance cannot claim Git revision")
63
+ if type(value["self_reported"]) is not bool or value["self_reported"] != (
64
+ value["provenance"] == "build_stamp"
65
+ ):
66
+ raise ValueError("invalid component self-report state")
67
+ return dict(value)
@@ -0,0 +1,61 @@
1
+ """Public prototype client credentials compiled into the CVM worker and MCP.
2
+
3
+ These keys identify the disposable Shelbynet app to paid infrastructure. They
4
+ are copyable API client credentials, never the ACE root, worker signing key,
5
+ or a Gas Station Server key. This release reuses the disposable Shelbynet
6
+ client credentials only after the Gas Station policy includes its new module
7
+ address. Any other deployment needs an explicit policy and key review.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+
14
+ _SHELBYNET_CHAIN_ID = 119
15
+ _SHELBYNET_MODULE_ADDRESS = "0x9c303c89de51d9b5b67732462b320a577deb5e5895e3d304d2a6d095714629e5"
16
+ _SHELBYNET_FULLNODE_URL = "https://api.shelbynet.shelby.xyz/v1"
17
+ _SHELBYNET_GAS_STATION_URL = "https://api.shelbynet.shelby.xyz/gs/v1"
18
+
19
+ # Public Client key also embedded in the c26t MCP for this disposable app.
20
+ # The Gas Station policy, not secrecy of this value, bounds sponsored calls.
21
+ _BUNDLED_GAS_STATION_CLIENT_KEY = "AG-AL9R8P5UEKDJB6NHB3H6K2TVW2GHEXKVU"
22
+
23
+ # Separate public Client key for the c26t-cvm-prototype-client Shelby API
24
+ # resource. Fullnode, ACE, and Shelby calls all use this same API endpoint.
25
+ _BUNDLED_SHELBY_NODE_CLIENT_KEY = "AG-9TYW5IAKQEKGYGRPFYM85N8QCRXHPIK2G"
26
+
27
+
28
+ class CVMOperationalKeyError(RuntimeError):
29
+ """No approved public Client keys exist for this worker deployment."""
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class CVMOperationalKeys:
34
+ gas_station_api_key: str
35
+ shelby_api_key: str
36
+
37
+
38
+ def _valid_header_value(value: str | None) -> bool:
39
+ return (
40
+ isinstance(value, str)
41
+ and 1 <= len(value) <= 4096
42
+ and all(33 <= ord(character) <= 126 for character in value)
43
+ )
44
+
45
+
46
+ def bundled_operational_keys(
47
+ *, chain_id: int, module_address: str, fullnode_url: str, gas_station_url: str
48
+ ) -> CVMOperationalKeys:
49
+ """Return only the approved public keys for this exact prototype app."""
50
+ if (
51
+ chain_id != _SHELBYNET_CHAIN_ID
52
+ or module_address != _SHELBYNET_MODULE_ADDRESS
53
+ or fullnode_url != _SHELBYNET_FULLNODE_URL
54
+ or gas_station_url != _SHELBYNET_GAS_STATION_URL
55
+ ):
56
+ raise CVMOperationalKeyError("no bundled Client keys for this deployment")
57
+ if not _valid_header_value(_BUNDLED_GAS_STATION_CLIENT_KEY):
58
+ raise CVMOperationalKeyError("bundled Gas Station Client key is unavailable")
59
+ if not _valid_header_value(_BUNDLED_SHELBY_NODE_CLIENT_KEY):
60
+ raise CVMOperationalKeyError("bundled Shelby Client key is unavailable")
61
+ return CVMOperationalKeys(_BUNDLED_GAS_STATION_CLIENT_KEY, _BUNDLED_SHELBY_NODE_CLIENT_KEY)
@@ -0,0 +1,291 @@
1
+ """Domain-separated keys and authenticated ciphertexts for the CVM variant.
2
+
3
+ The stable root is reconstructed only inside an attested CVM. No caller-held
4
+ recovery key or mutable encrypted key snapshot is involved in this variant.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+ import re
13
+ import secrets
14
+ from dataclasses import dataclass
15
+
16
+ from aptos_sdk.bcs import Deserializer, Serializer
17
+ from cryptography.exceptions import InvalidTag
18
+ from cryptography.hazmat.primitives import hashes, serialization
19
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
20
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
21
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
22
+
23
+ _ADDRESS = re.compile(r"0x[0-9a-fA-F]{1,64}\Z")
24
+ _FRAME_VERSION = b"c26t-aead-v1\x00"
25
+ _NONCE_BYTES = 12
26
+ _MAX_RECORD_BYTES = 16 * 1024 - len(_FRAME_VERSION) - _NONCE_BYTES - 16
27
+ _MAX_INDEX_OBJECT_BYTES = 16 * 1024 * 1024
28
+
29
+
30
+ def _part(value: bytes) -> bytes:
31
+ return len(value).to_bytes(4, "big") + value
32
+
33
+
34
+ def _text(value: str, name: str) -> bytes:
35
+ if not isinstance(value, str) or not value or len(value) > 1024:
36
+ raise ValueError(f"{name} must be a nonempty bounded string")
37
+ encoded = value.encode("utf-8")
38
+ if len(encoded) > 4096 or any(ord(character) < 32 for character in value):
39
+ raise ValueError(f"{name} contains invalid characters")
40
+ return encoded
41
+
42
+
43
+ def aptos_address_bytes(address: str) -> bytes:
44
+ """Parse an Aptos account or object address into its 32-byte representation."""
45
+ if not isinstance(address, str) or _ADDRESS.fullmatch(address) is None:
46
+ raise ValueError("invalid Aptos address")
47
+ return bytes.fromhex(address[2:].zfill(64))
48
+
49
+
50
+ def aptos_address_text(address: bytes) -> str:
51
+ if not isinstance(address, bytes) or len(address) != 32:
52
+ raise ValueError("Aptos address must have 32 bytes")
53
+ return "0x" + address.hex()
54
+
55
+
56
+ def _open(key: bytes, aad: bytes, frame: bytes) -> bytes:
57
+ if (
58
+ not isinstance(frame, bytes)
59
+ or not frame.startswith(_FRAME_VERSION)
60
+ or len(frame) < len(_FRAME_VERSION) + _NONCE_BYTES + 16
61
+ ):
62
+ raise ValueError("invalid ciphertext frame")
63
+ offset = len(_FRAME_VERSION)
64
+ nonce = frame[offset : offset + _NONCE_BYTES]
65
+ ciphertext = frame[offset + _NONCE_BYTES :]
66
+ try:
67
+ return AESGCM(key).decrypt(nonce, ciphertext, aad)
68
+ except InvalidTag as exc:
69
+ raise ValueError("ciphertext authentication failed") from exc
70
+
71
+
72
+ def _seal(key: bytes, aad: bytes, plaintext: bytes, *, limit: int = _MAX_RECORD_BYTES) -> bytes:
73
+ if not isinstance(plaintext, bytes) or len(plaintext) > limit:
74
+ raise ValueError("plaintext is not bounded bytes")
75
+ nonce = secrets.token_bytes(_NONCE_BYTES)
76
+ return _FRAME_VERSION + nonce + AESGCM(key).encrypt(nonce, plaintext, aad)
77
+
78
+
79
+ @dataclass(frozen=True, slots=True)
80
+ class CVMKeySchedule:
81
+ """A stable service root scoped to one chain and one Move deployment."""
82
+
83
+ root_seed: bytes
84
+ chain_id: int
85
+ module_address: str
86
+
87
+ def __post_init__(self) -> None:
88
+ if not isinstance(self.root_seed, bytes) or len(self.root_seed) != 32:
89
+ raise ValueError("root_seed must have 32 bytes")
90
+ if (
91
+ not isinstance(self.chain_id, int)
92
+ or isinstance(self.chain_id, bool)
93
+ or not 0 <= self.chain_id <= 255
94
+ ):
95
+ raise ValueError("chain_id must be an Aptos u8")
96
+ aptos_address_bytes(self.module_address)
97
+
98
+ def derive(self, purpose: str, *fields: bytes) -> bytes:
99
+ label = _text(purpose, "purpose")
100
+ if any(not isinstance(field, bytes) for field in fields):
101
+ raise ValueError("KDF fields must be bytes")
102
+ deployment = bytes([self.chain_id]) + aptos_address_bytes(self.module_address)
103
+ salt = hashlib.sha256(b"c26t/kdf-salt/v1\x00" + deployment).digest()
104
+ info = b"c26t/kdf-info/v1\x00" + _part(label) + b"".join(_part(field) for field in fields)
105
+ return HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=info).derive(
106
+ self.root_seed
107
+ )
108
+
109
+ def user_private_key(self, issuer: str, subject: str) -> Ed25519PrivateKey:
110
+ seed = self.derive("user-sign", _text(issuer, "issuer"), _text(subject, "subject"))
111
+ return Ed25519PrivateKey.from_private_bytes(seed)
112
+
113
+ def user_address(self, issuer: str, subject: str) -> str:
114
+ public = (
115
+ self.user_private_key(issuer, subject)
116
+ .public_key()
117
+ .public_bytes(
118
+ encoding=serialization.Encoding.Raw,
119
+ format=serialization.PublicFormat.Raw,
120
+ )
121
+ )
122
+ return aptos_address_text(hashlib.sha3_256(public + b"\x00").digest())
123
+
124
+ def index_publisher_private_key(self) -> Ed25519PrivateKey:
125
+ return Ed25519PrivateKey.from_private_bytes(self.derive("index-publisher"))
126
+
127
+ def registrar_private_key(self) -> Ed25519PrivateKey:
128
+ return Ed25519PrivateKey.from_private_bytes(self.derive("identity-registrar"))
129
+
130
+ def seal_identity(self, actor: str, issuer: str, subject: str) -> bytes:
131
+ address = aptos_address_bytes(actor)
132
+ claims = {
133
+ "iss": _text(issuer, "issuer").decode(),
134
+ "sub": _text(subject, "subject").decode(),
135
+ }
136
+ payload = json.dumps(claims, separators=(",", ":"), sort_keys=True).encode()
137
+ return _seal(
138
+ self.derive("identity", address), b"c26t/identity-aad/v1\x00" + address, payload
139
+ )
140
+
141
+ def open_identity(self, actor: str, frame: bytes) -> tuple[str, str]:
142
+ address = aptos_address_bytes(actor)
143
+ payload = _open(
144
+ self.derive("identity", address), b"c26t/identity-aad/v1\x00" + address, frame
145
+ )
146
+ try:
147
+ claims = json.loads(payload)
148
+ if not isinstance(claims, dict) or set(claims) != {"iss", "sub"}:
149
+ raise ValueError("invalid identity envelope")
150
+ issuer = _text(claims["iss"], "issuer").decode()
151
+ subject = _text(claims["sub"], "subject").decode()
152
+ except (UnicodeDecodeError, json.JSONDecodeError, TypeError) as exc:
153
+ raise ValueError("invalid identity envelope") from exc
154
+ if self.user_address(issuer, subject) != aptos_address_text(address):
155
+ raise ValueError("identity does not match account")
156
+ return issuer, subject
157
+
158
+ def email_lookup_hash(self, normalized_email: str) -> bytes:
159
+ email = _text(normalized_email, "email")
160
+ if normalized_email != normalized_email.strip().lower() or b"@" not in email:
161
+ raise ValueError("email must be normalized")
162
+ return hmac.digest(self.derive("email-lookup"), email, "sha256")
163
+
164
+ def record_request_commitment(
165
+ self,
166
+ thread_id: str,
167
+ actor: str,
168
+ request_id: bytes,
169
+ message: str,
170
+ attachments: list[str],
171
+ ) -> bytes:
172
+ """Commit to a retry's cleartext without exposing a public dictionary oracle."""
173
+ thread = aptos_address_bytes(thread_id)
174
+ if not isinstance(request_id, bytes) or len(request_id) != 32:
175
+ raise ValueError("request ID must be 32 bytes")
176
+ if not isinstance(message, str) or not isinstance(attachments, list):
177
+ raise TypeError("invalid record request")
178
+ body = (
179
+ b"c26t/record-request/v1\x00"
180
+ + aptos_address_bytes(actor)
181
+ + request_id
182
+ + _part(message.encode("utf-8"))
183
+ + len(attachments).to_bytes(4, "big")
184
+ + b"".join(_part(uri.encode("utf-8")) for uri in attachments)
185
+ )
186
+ return hmac.digest(self.derive("record-request-commitment", thread), body, "sha256")
187
+
188
+ def seal_intent(self, thread_id: str, intent: str) -> bytes:
189
+ thread = aptos_address_bytes(thread_id)
190
+ return _seal(
191
+ self.derive("intent", thread),
192
+ b"c26t/intent-aad/v1\x00" + thread,
193
+ _text(intent, "intent"),
194
+ )
195
+
196
+ def open_intent(self, thread_id: str, frame: bytes) -> str:
197
+ thread = aptos_address_bytes(thread_id)
198
+ plaintext = _open(self.derive("intent", thread), b"c26t/intent-aad/v1\x00" + thread, frame)
199
+ return plaintext.decode("utf-8")
200
+
201
+ def seal_record(
202
+ self,
203
+ thread_id: str,
204
+ sequence: int,
205
+ writer: str,
206
+ created_at: int,
207
+ message: str,
208
+ attachments: list[str],
209
+ ) -> bytes:
210
+ """Encrypt the exact BCS RecordPayload documented by the Move package."""
211
+ thread = aptos_address_bytes(thread_id)
212
+ if (
213
+ not isinstance(created_at, int)
214
+ or isinstance(created_at, bool)
215
+ or not 0 <= created_at < 2**64
216
+ ):
217
+ raise ValueError("created_at must be a u64")
218
+ if not isinstance(message, str) or not isinstance(attachments, list):
219
+ raise TypeError("invalid record payload")
220
+ serializer = Serializer()
221
+ serializer.fixed_bytes(aptos_address_bytes(writer))
222
+ serializer.u64(created_at)
223
+ serializer.to_bytes(message.encode("utf-8"))
224
+ serializer.sequence([uri.encode("utf-8") for uri in attachments], Serializer.to_bytes)
225
+ return _seal(
226
+ self.derive("record", thread), self._record_aad(thread, sequence), serializer.output()
227
+ )
228
+
229
+ def open_record(self, thread_id: str, sequence: int, frame: bytes) -> dict:
230
+ thread = aptos_address_bytes(thread_id)
231
+ plaintext = _open(self.derive("record", thread), self._record_aad(thread, sequence), frame)
232
+ try:
233
+ decoder = Deserializer(plaintext)
234
+ writer = aptos_address_text(decoder.fixed_bytes(32))
235
+ created_at = decoder.u64()
236
+ message = decoder.to_bytes().decode("utf-8")
237
+ attachments = [
238
+ item.decode("utf-8") for item in decoder.sequence(Deserializer.to_bytes)
239
+ ]
240
+ if decoder.remaining() != 0:
241
+ raise ValueError("trailing record bytes")
242
+ except (ValueError, UnicodeError, OverflowError) as exc:
243
+ raise ValueError("invalid encrypted record payload") from exc
244
+ return {
245
+ "writer": writer,
246
+ "created_at": created_at,
247
+ "message": message,
248
+ "attachment_uris": attachments,
249
+ }
250
+
251
+ def _record_aad(self, thread: bytes, sequence: int) -> bytes:
252
+ if (
253
+ not isinstance(sequence, int)
254
+ or isinstance(sequence, bool)
255
+ or not 0 <= sequence < 2**64
256
+ ):
257
+ raise ValueError("sequence must be a u64")
258
+ return (
259
+ b"c26t/record/v1\x00"
260
+ + bytes([self.chain_id])
261
+ + thread
262
+ + sequence.to_bytes(8, "little")
263
+ )
264
+
265
+ def seal_index_object(
266
+ self, thread_id: str, generation: int, object_id: bytes, plaintext: bytes
267
+ ) -> bytes:
268
+ thread = aptos_address_bytes(thread_id)
269
+ aad = self._index_aad(thread, generation, object_id)
270
+ return _seal(self.derive("index", thread), aad, plaintext, limit=_MAX_INDEX_OBJECT_BYTES)
271
+
272
+ def open_index_object(
273
+ self, thread_id: str, generation: int, object_id: bytes, frame: bytes
274
+ ) -> bytes:
275
+ thread = aptos_address_bytes(thread_id)
276
+ aad = self._index_aad(thread, generation, object_id)
277
+ return _open(self.derive("index", thread), aad, frame)
278
+
279
+ @staticmethod
280
+ def _index_aad(thread: bytes, generation: int, object_id: bytes) -> bytes:
281
+ if (
282
+ not isinstance(generation, int)
283
+ or isinstance(generation, bool)
284
+ or not 0 <= generation < 2**64
285
+ ):
286
+ raise ValueError("generation must be a u64")
287
+ if not isinstance(object_id, bytes) or not object_id or len(object_id) > 256:
288
+ raise ValueError("invalid index object id")
289
+ return (
290
+ b"c26t/index-aad/v1\x00" + thread + generation.to_bytes(8, "little") + _part(object_id)
291
+ )