vaultdb-client 0.4.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.
vaultdb/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """Python client for hosted VaultDB, wire 3 (SPEC.md in core/vaultdb/wire).
2
+
3
+ `connect` a service card with the service key's secret, then `open_vault` or `create_vault`; every
4
+ operation is a coroutine of the vault handle (asyncio) and takes the `actor`. Keys, the seal,
5
+ search tokens, parts and frames are public too, for the apps that need them."""
6
+
7
+ from ._version import VERSION as __version__
8
+ from .client import Connection, ServiceKey, connect, generate_service_key
9
+ from .envelope import (
10
+ event_subject,
11
+ file_meta_subject,
12
+ file_part_subject,
13
+ open_envelope,
14
+ open_record,
15
+ record_subject,
16
+ seal,
17
+ seal_record,
18
+ )
19
+ from .errors import VaultDBError
20
+ from .frames import FRAME_MAX, Frame, decode_frame, encode_frame
21
+ from .keys import event_key, file_key, generate_id, index_key, outer_key, record_key
22
+ from .normalize import TABLE_SHA256_HEX, normalize
23
+ from .parts import PART_SIZE, check_file, open_part, part_count, seal_part, split_parts
24
+ from .records import (
25
+ AppEvent, AuditEvent, AuditHead, AuditPage, BatchResult, Condition, FileEntry, FileInfo, FilePut,
26
+ FileUpload, Grant, Item, Page, PutResult, Record, SearchPage, VaultInfo, VaultRef,
27
+ )
28
+ from .parts import FileMeta
29
+ from .plain import PlainStatement, PlainTable, PlainValue
30
+ from .session import Card
31
+ from .tokens import bucket_token, exact_token, final_check, search_token
32
+ from .vault import Vault
33
+
34
+ __all__ = [
35
+ "FRAME_MAX", "PART_SIZE", "TABLE_SHA256_HEX", "AppEvent", "AuditEvent", "AuditHead", "AuditPage",
36
+ "BatchResult", "Card", "Condition", "Connection", "FileEntry", "FileInfo", "FileMeta", "FilePut",
37
+ "FileUpload", "Frame", "Grant", "Item", "Page", "PlainStatement", "PlainTable", "PlainValue", "PutResult",
38
+ "Record", "SearchPage", "ServiceKey", "Vault", "VaultDBError", "VaultInfo", "VaultRef",
39
+ "bucket_token", "check_file", "connect", "decode_frame", "encode_frame", "event_key", "event_subject",
40
+ "exact_token", "file_key", "file_meta_subject", "file_part_subject", "final_check", "generate_id",
41
+ "generate_service_key", "index_key", "normalize", "open_envelope", "open_part", "open_record",
42
+ "outer_key", "part_count", "record_key", "record_subject", "seal", "seal_part", "seal_record",
43
+ "search_token", "split_parts",
44
+ ]
vaultdb/_version.py ADDED
@@ -0,0 +1,4 @@
1
+ """The package's number: the client family's, the same for every client (#4866), set by Johan
2
+ (D-407: 0.3.0, 23 Nov 2026; atom #4909; 0.4.0 on 24 Nov 2026 with wire 3)."""
3
+
4
+ VERSION = "0.4.0"
vaultdb/client.py ADDED
@@ -0,0 +1,199 @@
1
+ """A connection to hosted VaultDB: the service card, the secret, the session behind it, and the
2
+ calls that need no vault (SPEC §1, §3, §8.1).
3
+
4
+ Calls are safe to make at the same time from many tasks: they share one session (one WebSocket,
5
+ one Noise session) and run independently. When the session has dropped, the next call opens a
6
+ new one (§1, §6); callers that race that share one handshake. A call is never retried here:
7
+ `retry_after_ms` is on the error, and every write is idempotent by its ids (§1)."""
8
+
9
+ import asyncio
10
+ from dataclasses import dataclass, replace
11
+ from typing import Any, AsyncIterator, Callable
12
+
13
+ from . import crypto, keys
14
+ from .errors import VaultDBError
15
+ from .records import Page, VaultRef
16
+ from .session import HOME, REKEYED, Card, KeyAnswer, Replica, Session, card_json, check_followed_key, check_secret, parse_card
17
+ from .vault import Vault, check_actor, check_declaration
18
+ from .wirecheck import b64e, integer, items, obj, optional_text, text
19
+ from .grammar import check_uint, check_vault
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class ServiceKey:
24
+ """A service key (§2): `secret` is the 32 bytes the app keeps; `public` is the 65-byte
25
+ identity the operator registers (SERVER.md §6)."""
26
+
27
+ secret: bytes
28
+ public: bytes
29
+
30
+
31
+ def generate_service_key() -> ServiceKey:
32
+ """GenerateServiceKey (§2): a fresh P-256 key from the platform's randomness."""
33
+ key = crypto.p256_generate()
34
+ return ServiceKey(crypto.p256_secret(key), crypto.p256_public_bytes(key))
35
+
36
+
37
+ class Connection:
38
+ """The channel to one POP. Make one with `connect`."""
39
+
40
+ def __init__(
41
+ self, card: Card, secret: bytes, on_card_change: Callable[[bytes], Any] | None = None,
42
+ ) -> None:
43
+ self._card = card # this connection's own copy; the app's card is never touched (§3.5)
44
+ self._secret = secret
45
+ self._on_card_change = on_card_change
46
+ self._session: Session | None = None
47
+ self._connect_lock = asyncio.Lock()
48
+ self._closed = False
49
+
50
+ def card(self) -> bytes:
51
+ """The connection's current card as JSON text (§3.5): the one to save after the hook."""
52
+ return card_json(self._card)
53
+
54
+ async def _ready(self) -> Session:
55
+ if self._closed:
56
+ raise VaultDBError("CLAV-NET-DROPPED", retry_after_ms=1000)
57
+ session = self._session
58
+ if session is None or session.closed:
59
+ changed: bytes | None = None
60
+ async with self._connect_lock:
61
+ session = self._session
62
+ if session is None or session.closed:
63
+ before = card_json(self._card)
64
+ session, card = await self._dial(self._card)
65
+ self._session = session
66
+ self._card = card
67
+ if card_json(card) != before:
68
+ changed = card_json(card)
69
+ if changed is not None and self._on_card_change is not None:
70
+ # after the new card is in place, outside the lock; the hook's failure is the app's (§3.5)
71
+ try:
72
+ self._on_card_change(changed)
73
+ except Exception:
74
+ pass
75
+ return session
76
+
77
+ async def _dial(self, card: Card) -> tuple[Session, Card]:
78
+ """Connect's steps 1 to 5 (§3.5): at most one new key and three handshakes, all before any
79
+ call. Nothing of a failed Connect is kept: the caller sets the card only on success."""
80
+ try:
81
+ session, replica = await Session.open(card.url, card.server_key, card.service, self._secret)
82
+ return session, _with_welcome_replica(card, replica)
83
+ except KeyAnswer as answer:
84
+ if answer.code == HOME:
85
+ raise VaultDBError("CLAV-NET-HANDSHAKE") from None # §15 [rs 1]
86
+ key = check_followed_key(answer.server_key, card.server_key) # step 2
87
+ followed = replace(card, server_key=key)
88
+ return await self._after_key(followed, followed.url, key)
89
+ except VaultDBError as first:
90
+ if first.code not in ("CLAV-NET-HANDSHAKE", "CLAV-NET-UNREACHABLE") or card.replica is None:
91
+ raise
92
+ via = await self._via_replica(card, card.replica)
93
+ if via is None:
94
+ raise first # step 3: "Connect fails with step 1's error"
95
+ return via
96
+
97
+ async def _after_key(self, card: Card, url: str, key: bytes) -> tuple[Session, Card]:
98
+ """Step 4: the handshake after a key was taken must end in Welcome; anything else, an
99
+ unreachable socket included, is CLAV-NET-HANDSHAKE (§15 [rs 4])."""
100
+ try:
101
+ session, replica = await Session.open(url, key, card.service, self._secret)
102
+ except VaultDBError:
103
+ raise VaultDBError("CLAV-NET-HANDSHAKE") from None
104
+ return session, _with_welcome_replica(card, replica)
105
+
106
+ async def _via_replica(self, card: Card, replica: Replica) -> tuple[Session, Card] | None:
107
+ """Step 3: one handshake with the replica. None is "anything else, or a check that fails"
108
+ (the caller then fails with step 1's error); once a key is taken, step 4 rules."""
109
+ try:
110
+ session, welcome_replica = await Session.open(replica.url, replica.server_key, card.service, self._secret)
111
+ except KeyAnswer as answer:
112
+ if answer.code == REKEYED:
113
+ return None
114
+ try:
115
+ key = check_followed_key(answer.server_key, card.server_key) # §15 [46]
116
+ except VaultDBError:
117
+ return None
118
+ return await self._after_key(replace(card, server_key=key), card.url, key)
119
+ except VaultDBError:
120
+ return None
121
+ # promoted (SERVER §6): the replica is the home now; its Welcome's replica, or none (§15 [46])
122
+ return session, Card(replica.url, replica.server_key, card.service, welcome_replica)
123
+
124
+ async def request(self, head: dict[str, Any]) -> dict[str, Any]:
125
+ """One call; the result's head."""
126
+ result, _tail = await (await self._ready()).request(head)
127
+ return result
128
+
129
+ async def request_tail(self, head: dict[str, Any], tail: bytes) -> tuple[dict[str, Any], bytes]:
130
+ """One call with a tail (file.part) and the result's tail (file.read)."""
131
+ return await (await self._ready()).request(head, tail)
132
+
133
+ async def stream(self, head: dict[str, Any]) -> AsyncIterator[dict[str, Any]]:
134
+ async for item in (await self._ready()).stream(head):
135
+ yield item
136
+
137
+ async def close(self) -> None:
138
+ """End the session for good; calls in flight fail with CLAV-NET-DROPPED."""
139
+ self._closed = True
140
+ if self._session is not None:
141
+ await self._session.close()
142
+
143
+ async def __aenter__(self) -> "Connection":
144
+ return self
145
+
146
+ async def __aexit__(self, *exc: object) -> None:
147
+ await self.close()
148
+
149
+ # ---- calls that need no vault ----------------------------------------------------------
150
+
151
+ async def ping(self, *, actor: str) -> int:
152
+ """ping: the server's time, unix ms."""
153
+ result = obj(await self.request({"op": "ping", "actor": check_actor(actor)}), frozenset({"time"}))
154
+ return integer(result, "time")
155
+
156
+ async def list_vaults(self, *, actor: str, after: str | None = None) -> Page[VaultRef]:
157
+ """vault.list: this service's vaults on this POP, and those it holds a grant in."""
158
+ head: dict[str, Any] = {"op": "vault.list", "actor": check_actor(actor)}
159
+ if after is not None:
160
+ head["after"] = after
161
+ result = obj(await self.request(head), frozenset({"vaults", "next"}))
162
+ refs = []
163
+ for raw in items(result, "vaults"):
164
+ ref = obj(raw, frozenset({"vault", "role"}))
165
+ refs.append(VaultRef(check_vault(text(ref, "vault")), text(ref, "role")))
166
+ return Page(refs, optional_text(result, "next"))
167
+
168
+ async def open_vault(self, vault_id: str, k: bytes, *, actor: str) -> Vault:
169
+ """OpenVault (§1): checks `K`, reads vault.info, holds the declaration and revision."""
170
+ vault = Vault(self, vault_id, k, {}, 0)
171
+ await vault.info(actor=actor)
172
+ return vault
173
+
174
+ async def create_vault(self, k: bytes, declaration: dict[str, Any], *, actor: str) -> Vault:
175
+ """CreateVault (§1): vault.create with this vault's L1, the same handle as OpenVault."""
176
+ check_declaration(declaration)
177
+ head = {"op": "vault.create", "actor": check_actor(actor), "declaration": declaration,
178
+ "key": b64e(keys.outer_key(k))}
179
+ result = obj(await self.request(head), frozenset({"vault", "revision"}))
180
+ return Vault(self, check_vault(text(result, "vault")), k, declaration, check_uint(integer(result, "revision"), 53))
181
+
182
+
183
+ def _with_welcome_replica(card: Card, replica: Replica | None) -> Card:
184
+ """Step 5: a Welcome without `replica` leaves the card's as it is (§15 [rs 3])."""
185
+ return card if replica is None else replace(card, replica=replica)
186
+
187
+
188
+ async def connect(
189
+ card: "str | bytes | dict[str, Any] | Card", secret: bytes,
190
+ on_card_change: Callable[[bytes], Any] | None = None,
191
+ ) -> Connection:
192
+ """Connect (§3.1, §3.5): checks the card, opens the WebSocket, handshakes, and follows a new
193
+ node key or the replica. `secret` is the service key's 32 bytes (`generate_service_key`).
194
+ `on_card_change(card_json_bytes)` is called once, before this returns, when the card changed;
195
+ save what it gets where you keep your card. The library writes and fetches no card."""
196
+ parsed = parse_card(card)
197
+ connection = Connection(parsed, check_secret(secret), on_card_change)
198
+ await connection._ready()
199
+ return connection