@txnlab/zs-proto
v0.25.2
Published
ZeroSignal protocol primitives for TypeScript: envelope sealing, AAD and canonical bytes, ticket and receipt signatures, operator selection, pricing, tokenize bounds, transient-error classification, routing-signal arithmetic, and TEE attestation checks. B
Maintainers
Readme
@txnlab/zs-proto
TypeScript primitives for the ZeroSignal protocol: envelope sealing, AAD and canonical bytes, ticket and receipt signatures, operator selection, pricing, tokenize bounds, transient-error classification, escrow box decoding and settlement rules, and TEE attestation checks. Enough for a browser or Node process to speak the protocol directly to a node, with no proxy daemon in front.
It is a port of the Go reference implementation and is kept byte-for-byte compatible with it on
every signed or AAD-bound payload. The authoritative wire spec is
SPEC.md; the Go module is
go/.
This package ships primitives only. Chain access and request orchestration (routing, reserve,
escrow open / settle, sealing, relay hops, streaming, receipt checks) are in the payer SDK,
@txnlab/zerosignal, which builds on this
package. Operator discovery is in the Go SDK
(go/zs); a TypeScript host supplies its
own to @txnlab/zerosignal.
Install
pnpm add @txnlab/zs-protoESM only, Node ≥ 20.19 or any modern browser. Five runtime dependencies: @noble/ciphers,
@noble/ed25519, @noble/hashes, @scure/base, age-encryption.
Entry points
| Import | Contents |
|---|---|
| @txnlab/zs-proto | Everything from wire, ticket, selection, imageprice, tokenize, attest, inject, tools |
| …/wire | Envelope types, wrapRequest / unwrapResponseKey / decryptBody / decryptSSEDataValue, decryptRequest / ResponseSealer (node side, for round-trip tests), AAD builders, admission-tag HMAC, body hash, sealed inner frame, ephemeral identity, protocol version |
| …/ticket | Ticket / UsageReceipt / reserve types, signTicket / verifyTicketFor / signReceipt / verifyReceiptFor (bound layouts only), the deployment id, signature digests, commitResponseKey, receipt header codec, Algorand address codec, BytesSigner |
| …/selection | Operator and relay selection policy, deriveMaxOutput |
| …/pricing | Token pricing and verifyTicketPrice |
| …/imageprice | Image-generation pricing |
| …/tokenize | Input-token bound used to size a reserve |
| …/transient | Retryable-vs-terminal error classification and the shared retry schedule; the reserve 429 BusyCodes with retryableBusyCode; retryableAfterPayment |
| …/steering | The arithmetic behind a payer's own routing signals: relay-reputation decay / bump / relayDownranked, target backoff (backoffWindowMs, recordFailure, backoffRemaining), and the weights-digest weightsConsensus. The stores they feed stay with the payer |
| …/relay | Relay request metadata and the inner-path allow-list |
| …/tools | What a payer reads off a tool-bearing stream: the sealed tool-status and image progress / partial / completed frames with parseStatusEvent and partialImageDataUrl, ToolAction and its source icons (iconHostKey, iconDataUrl, sanitizeIcons), isLinkableUrl for any URL that becomes an href, and the usage shapes with generatedOutputTokens |
| …/escrow | Escrow app box keys, ticket / operator / node record decoders, ticketView and classify over a ticket box, settle-group sizing; re-exports settle's fee math |
| …/settle | The settlement rules every rail shares: TicketView, SettleStatus, classify (what call a live ticket allows now), and the protocol fee math (netFee, computeFeeBreakdown) |
| …/attest | dstack / Intel TDX measurement checks and compose-file policy |
| …/inject | The /v1/zs/details discovery types and parseOperatorDetails, retention tiers (isKnownRetention, combineRetention), TEE modes, the payer's pre-seal body mutators (dropRoutingPreferences, dropPromptCacheKey, dropEmptyTools, clampMaxOutput), tool classification (classifyToolEntry, normalizeToolName), server-side tool-growth detection, request-dialect helpers |
| …/testdata/* | The golden-vector fixtures this package is tested against |
escrow, settle, pricing, transient, steering, and relay are subpath-only: their names
(classify, wait, decay, buildRequest, …) are package-qualified in Go and would be
ambiguous at the root.
Signing: raw Ed25519, not Algorand signBytes
A BytesSigner must return a raw Ed25519 signature over the exact bytes it is given — a
32-byte sha256 digest of a domain-tagged canonical body. This is not go-algorand-sdk's
crypto.SignBytes (which prepends MX) and not ARC-60 signData. A wallet whose sign-bytes
flow adds any prefix or tag cannot implement BytesSigner; the signer needs raw key access.
inMemoryEd25519Signer is the reference implementation.
Wire shape and JSON property names
Wire-shaped types (RequestEnvelope, ResponseEnvelope, Ticket, UsageReceipt, ReserveRequest, ReserveResponse) use snake_case property names that match the JSON wire format. JSON.stringify(ticket) produces the exact bytes the Go side emits — no field-name remapping layer.
Function names use camelCase. Constants use UPPER_SNAKE.
Numeric fields
Go's uint64 / int64 fields are typed as number here. Real values stay well within JS's safe-integer range (token counts, microUSDC totals up to ~10^12). Internally, the canonical-bytes encoder coerces via BigInt before writing the 8-byte big-endian form, so values up to 2^53−1 are encoded correctly.
escrow is the exception: it decodes on-chain boxes, whose uint64 fields can hold any value, so they are bigint. Fields the contract stores in one or two bytes (statuses, the pending side, usage types, fee bps, staging) are number. Its arithmetic is unbounded where Go's uint64 wraps, so the two agree only on values the contract can actually produce; the fee functions accept fee bps as either type. decodeNodeRecord refuses a base URL that is not valid UTF-8, which Go decodes with the raw bytes kept.
Secret-key lifetime
JS strings are immutable, so the AGE-SECRET-KEY-1… representation of an ephemeral identity cannot be reliably wiped from memory the way the Go side does (ZeroEphemeralIdentity reaches into age internals via reflect+unsafe). Callers should:
- Hold the
EphemeralIdentityonly as long as needed (until the response is fully decrypted). - Drop the reference and let GC collect it; do not log or persist it.
- Treat in-memory secret lifetime as "best-effort" — the underlying bytes linger until GC runs and reclaims the string.
For higher-assurance setups, terminate envelopes in a worker / iframe whose JS heap can be discarded entirely on completion.
Not ported (intentionally): the Go file-IO identity loader, the Go ZeroEphemeralIdentity wipe,
the Go algo, algod, and keystore packages, the node-side half of tools (request rewriters,
the tool loop, markup recovery), and the chain-access half of escrow (transaction composition,
box reads, group verification). @txnlab/zerosignal carries that half: its escrow module
(sdk/src/escrow/open.ts, settle.ts, group.ts, algod.ts) checks and completes the open and
settle groups a node builds and reaches the escrow app over algod.
Cross-implementation byte parity
Every vectored module is checked against a fixture the Go implementation generates: AAD layout,
admission tag, body hash, ticket / receipt canonical bytes, signature digests, address
encoding, selection order, pricing, tokenize bounds, transient verdicts, escrow box keys,
record decoding, classify and fee math, discovery field names and retention tiers, which
bodies the pre-seal mutators change (compared by value: TS splices the original text where Go
re-marshals), tool-status frames as a node emits them, icon host keys and the usage arithmetic,
reputation decay, target backoff and the weights consensus, and attestation checks. parseOperatorDetails is deliberately more lenient than Go's decoder —
it drops a malformed field rather than rejecting the whole body — and that part is tested
here only. The Go suite fails when its output no longer matches the fixture, and this package's
suite fails when its output does, so drift on either side fails. In a checkout of the
repository:
make test # Go suite, this package's suite, and the generator check
make update-vectors # regenerate fixtures after an intentional format changeDevelopment
This package and the SDK (../sdk) are one pnpm workspace with one lockfile, rooted one
directory up, so install from there.
cd .. && pnpm install && cd ts
pnpm test # vitest --run
pnpm typecheck
pnpm buildLicense
Apache-2.0 — see LICENSE.
