10 KiB
Mesh Client
Native clients can import mesh_client/crypto_native for bounded byte-slice
SHA-256, streaming digests, HMAC-SHA-256, XChaCha20-Poly1305, secure random bytes,
clearing buffers and compatible Argon2id exports. Link libsodium for this optional
provider; it uses the same 24-byte nonces and appended authentication tags as
existing encrypted content. Applications retain their account and content keys,
authenticated schema context, storage, and node policy. keys.ValidateIdentity
verifies an existing binary ML-DSA-44 account and private-key proof without
creating or replacing keys.
Mesh Client is the independent Ziran library for applications that sync with
Mesh. It contains no server, mesh node, database,
or UI implementation.
It has no Kryon dependency and lives in the
Ziran organization. Add it with
ziran add https://git.waozi.xyz/ziranlang/mesh-client.git.
The package name and public dependency namespace are mesh_client. Release APIs use MeshRelease, MeshParseRelease,
MeshSha256Matches, and the MESH_RELEASE_* limits. Old daochi_client
imports and Daochi* source aliases are not provided.
Released protocol values keep their original spelling: daochi-* signature
contexts, X-Daochi-* HTTP headers, daochi-record-v1 envelopes and
daochi-entity-v1/* key derivation strings. The account-key-v1 and
ksync-account-key-v2 key files, account IDs, stored state and result codes
also stay unchanged. Renaming these bytes would invalidate signatures or prevent
existing users from decrypting their data. This source/package rename does not
migrate stored data or change the wire protocol.
The protocol modules currently provide:
- canonical challenge, login body, and signed message builders (
wire.zi); - signed app releases (
daochi-zib-release-v2): shape, ordering and bounds, the canonical signed message, and the signature through the application's own Ed25519 check (release.zi); - HTTPS and local network URL policy (
url.zi); - challenge parsing, signed login preparation, and token parsing (
auth.zi); - login and bearer requests with one fresh login after a
401(client.zi); - canonical device registration and protocol v6 transaction messages
(
transaction.zi); - signed device registration and protocol v6 sync requests (
sync.zi); - encrypted record profile v1 (
daochi-record-v1) envelopes with canonical authenticated metadata and fresh XChaCha20-Poly1305 nonces (record.zi, native; link libsodium); - entity data keys and shared chunks (
entity.zi): the record key of each kind of account data and convergent 8 MiB chunk sealing, so every app of the account stores one copy of each photo or level (Meshdocs/entity-data.md), and entity records sealed and opened asdaochi-record-v1envelopes in plain Ziran, without libsodium; - polled login, bearer requests, and signed sync operations
(
async_client.zi,async_sync.zi); - resumable record pages, bounded transfer recovery and cursor validation
(
sync_flow.zi, used byasync_sync.zi); - alias and friend requests, actions, lists, and stats (
social.zi); - challenge signed account deletion without transmitting a key backup
(
account.zi). - WebSocket URL, event validation, and one event wait through a host callback
(
events.zi). - account keys: an ML-DSA-44 key pair with its SHA-256 public id, message
signing, and the plain (
account-key-v1) and passphrase-encrypted (ksync-account-key-v2) key files (keys.zi, signing through the Oqs package); - PBKDF2 for the key files, ChaCha20-Poly1305 and XChaCha20-Poly1305
(
crypto.zi), which also passes on SHA-256, HMAC-SHA-256 and hex from the crypto package.
The application supplies the account signer and body digest; keys.zi
provides both for Mesh account keys (SignAccountMessage, Sha256Hex), and
the app still stores the keys. A host supplies
bounded HTTP requests through SendRequest; the host must NUL terminate every
response buffer, including on error. This keeps private keys in the app's key
store and keeps platform transport outside the protocol core. Applications
persist Session if they want bearer tokens to survive restart. Account keys
must remain when a bearer token expires.
Session.registration remembers one successful device registration for up to
an hour between successful requests, scoped to the normalized node URL,
account, app, client, device key ID and public key. Sync then sends only its
signed transaction. The node still verifies both signatures and revocation on
every request. A missing-device response permits one fresh registration and
a newly signed transaction; revoked devices cannot register again. Clearing or
renewing the bearer session clears the hint. Hosts may save this public metadata
with WriteRegistration and restore it with ReadRegistration; it contains no
private key or bearer token.
record_codec.zi optionally packs JSON before encryption with a bounded gzip
frame. Keep the released identity ciphertext and send an independently sealed
packed_nonce/packed_ciphertext pair alongside it. Readers request
record_encoding:"gzip-v1" on record pages; older nodes and readers continue to
use the identity representation. After authenticating the ciphertext, validate
the frame's claimed length before allocating and call UnpackRecord with the
app's own record limit. Binary media bypass this codec. Native hosts link zlib
(-lz); Emscripten hosts use -sUSE_ZLIB=1.
A transport may resend a signed POST when a reused connection drops after the node committed it. Sync recognizes the exact signed-transaction replay response and retries with a fresh nonce within its existing bounded recovery budget. The node's replay protection remains enforced.
Import the package modules with #import "mesh_client/client" and
#import "mesh_client/sync". Set Client.app_id, supply a Device with a
persisted Ed25519 key and signer, and supply a cryptographically random 64-digit
hex nonce callback. Sync registers the device and signs the exact sync body
with both the account and device keys. The app owns the payload format and
merges the response. A native host can adapt SendRequest to Ziran's curl HTTP
module and ReceiveEvent to its bounded curl WebSocket module. Browser and
Android hosts must implement those host boundaries before those builds sync.
Event loops can use BeginRequest/PollRequest and BeginSync/PollSync
with AsyncTransport. Its start callback copies the request metadata and
retains the caller's bounded output buffer; poll returns -1 while pending,
0 for transport failure, or 1 with the HTTP status when complete. Every
completed response must be NUL terminated. Cancel releases all transport
references to that output buffer before returning. Keep the pending operation,
session, client identity, signing contexts, body, and extra header strings alive
until completion or cancellation. Each pending operation has its own transport
context. CancelRequest and CancelSync release an active transfer and finish
with AUTH_REQUEST_FAILED. Both request modes share the same one-login retry
after a 401; sync modes share the exact registration and transaction builders.
Pass a SyncFlow to BeginSync to sync accounts larger than one response
buffer. Mesh Client switches to the server's encrypted record pages after a
capacity failure, signs each page request, retries interrupted transfers and
validates forward cursor progress. It retains a bounded response buffer across
pages; total account size has no fixed client buffer limit. An optional transport
failure callback reports TRANSFER_FAILURE_CAPACITY; other failures retain the
existing result codes. Smaller record pages are tried if a page itself overflows.
The flow's host callbacks load/save account-and-node-local SyncPageState,
prepare the app's current encrypted records, and accept each response. accept
must atomically merge records and persist the proposed next state, returning
false without advancing durable progress on failure. Only a terminal page may
advance the account watermark. On restart the library resumes the saved cursor;
cancel releases the current transfer and owned request memory. The host's clock
callback refreshes transaction time between pages. These callbacks contain app
storage policy, not page requests or transport retry decisions.
prepare receives the maximum encrypted record count for the next upload,
including any reduction after an oversized page. Retain its returned body until
the next prepare call or completion.
Zero means download only: after overflow recovery or while resuming a partial
download, the library omits uploads until the terminal page. Otherwise repeated
uploads could keep moving the same account's download cursor. A later sync can
upload the retained local queue.
sh tests/run.sh checks the library using the toolchain selected by
ziran pkg path ziran, including portable .zx URL and wire tests. An
ignored ziran.local.toml can select the local compiler at
../../ziran; otherwise the test uses ziran.lock. The wire
test also checks a saved .zir to .zx round trip. Set ZIRAN_BIN to use
a different launcher, or ZIRAN_DIR and ZI2C_BIN for explicit compiler
overrides.
The library does not provision keys, revoke devices, store account data, or merge application records. Each app owns those operations and supplies its payload builder, response merge, key store, and platform transport.
The protocol uses Ziran's TextView and bounded TextUntilNul instead of
a native string-layout adapter. URL policy, wire builders, and signed device
registration message construction compile and run as portable .zx. The
full HTTP client is not yet a .zx bundle: host transport, digest, and
signer callbacks need bundle capabilities. Native Linux integration is tested;
browser and Android transports remain application host work.
sync.PrepareRequestHeader prepares the same account/device signed v6
transaction for an exact HTTP method, path and byte-counted body, including
empty GET/HEAD bodies and binary blob uploads. Hosts that already stream and
hash the body can use sync.SignTransactionHeader with an explicit
transaction.SyncTransaction; its account, app and device must match the
supplied client. PrepareSyncHeader retains the existing POST sync behavior.
The host still owns transport, pinned-node policy, session/key storage and
remote acknowledgment handling.