TypeScript
This section covers installing, understanding, and integrating the DeRec protocol using the official TypeScript SDKs for Node.js and the Web.
TypeScript SDK Overview
The DeRec TypeScript SDK provides a managed surface over the same DeRecProtocol orchestrator the Rust SDK exposes. Internally each package wraps the WASM compilation of the Rust derec-library crate — the WASM blob, the JS glue, and the bigint/Uint8Array marshalling are all internal details. TypeScript consumers see a managed DeRecProtocol class, async/await methods, typed DeRecEvent objects, and a thrown DeRecError shape.
The SDK ships as two packages with the same API surface:
@derec-alliance/nodejs
Node.js
@derec-alliance/web
Browsers (and other ESM environments that can load a .wasm blob)
Both packages expose the same TypeScript types (DeRecProtocol, DeRecProtocolBuilder, DeRecEvent, ContactMode, SenderKind, FlowKind, StatusEnum, the five store interfaces, Transport, …) declared in their index.d.ts. The only difference is that @derec-alliance/web additionally exports init. Pick the package that matches your runtime; every code sample in the rest of this section works against either one.
The SDK allows applications to:
Distribute Secret shares across trusted Helpers using a threshold secret-sharing scheme
Verify Helpers still hold shares
Recover the Secret from a threshold of Helpers
Manage paired channels: unpair, announce new endpoints or contact details, refuse requests
Optionally extend the Owner identity across multiple devices via the replica feature, with automatic Secret synchronization between them
Installation
Both packages publish at the same version as the derec-library Rust crate they wrap. These chapters document lib-derec 0.0.10.
Node.js
The Node package loads its WASM blob synchronously on import — no initialization step is required.
Browser
The Web package ships the WASM blob as a separate asset and exposes an init() function that must be awaited before any other API is used. The exact wiring depends on the bundler.
Vite, Webpack, and Rollup all need to be told how to resolve and serve the .wasm asset alongside the JS bundle — consult the bundler's documentation on bundling WebAssembly modules.
Both packages also ship the protocol schema: the .proto files under proto/ and a compiled derec_descriptor.bin. See Schema distribution.
Quick Start
Implement the five store interfaces and a transport, then drive the orchestrator. The example below is the minimum scaffold; the flow chapters show how each protocol round-trip flows through process(...).
Builder configuration
The builder requires withChannelStore, withShareStore, withSecretStore, withUserSecretStore, withStateStore, withTransport, and own transports, set with withOwnTransports or the own_transports key of a withConfig config — calling build() without all seven throws. withStores({ channelStore, shareStore, secretStore, userSecretStore, stateStore }) sets the five stores in one call; every store setter may be called again, before or after it, and the last call for a store wins.
withOwnTransports(endpoints: Endpoint[]) lists every endpoint this application serves, in its own preference order. Endpoint is { uri: string; protocol: "https" | "grpc" }. The list must be non-empty and hold at most one entry per protocol: an empty list fails build() with code invalid_input (category input), and two entries of the same protocol are refused. Every listed endpoint must actually be served — delivery is push-only, so an endpoint this application does not serve makes pairing succeed and replies vanish. Recognised schemes are https://, http://, grpcs:// and grpc://.
Optional setters — leaving one uncalled keeps the library default:
withThreshold(n)
3
The starting threshold t, in subshares, for a secret with no threshold stored; see Threshold and Secret version. 0 and 1 are refused at build().
withMaxSubshares(max)
unset (no cap)
Cap on a sharing round's total subshares; bigint | number. A cap below the threshold fails build() with invalid_input. See Weighted helpers.
withTimeouts(timeouts)
see below
The four wait budgets.
withCommunicationInfo(info)
empty
Contact details sent to peers at pairing.
withAutoRespondOnFailure(enabled)
false
Who answers a failed inbound request. true: the library sends the response. false: nothing is sent and RequestFailed carries a token for reject. See Failed requests.
withAutoReplyTo(enabled)
false
Stamp every outbound request's replyToTransports with this node's own endpoints.
withAutoAccept(policy)
every flow off
Accept matching inbound requests inside process(); see Auto-accept policy.
withUnsafeConnection(allow)
false
Accept plaintext http:// / grpc:// endpoints. Development only.
withReplicaId(id)
unset
Stable per-device replica id; required for every replica flow.
withParameterRange(range)
unset
Bounds advertised and checked at pairing; Partial<ParameterRange>.
withUnsafeConnection(true) accepts plaintext http:// and grpc:// endpoints for any host, including endpoints a peer supplies. With it false, plaintext is accepted only for an endpoint this device configured for itself that names loopback, so a local dev server needs no configuration. See Transport endpoints and plaintext connections.
withParameterRange declares the bounds this node advertises in pairing messages. A peer whose range does not intersect it is refused with incompatible_parameter_range; see Parameter ranges. Every field defaults to 0, which reads as no bound on that side: a max of 0 is no upper bound. build() validates the range: each min and max must be >= 0, and min <= max unless max is 0; a range that breaks either rule fails build() with invalid_input naming the field. A helper also enforces its own min_share_size / max_share_size on every inbound share.
Local configuration can change after build(): setCommunicationInfo(info) and setOwnTransports(endpoints) replace the values the builder set. Both return Promise<void>, and neither contacts a peer — see Update channel info.
Configuration from a file or record
Applications usually load settings as a whole: general settings from the environment or a config file, per-user settings from a user record. DeRecProtocolConfig holds every data setting of the builder, each one optional, and withConfig applies it in one call:
Only set fields are applied. An absent or
nullfield leaves whatever the builder already holds.Last write wins, per field. WASM holds one config and layers every
withConfigand per-option setter call into it field by field, so the later call always wins regardless of which form it took. Nested objects replace the builder's value as a whole, excepttimeouts: each of its fields is merged separately, so a per-user config that sets onlyinbound_message_secskeeps thesharing_round_secsthe general config set.Most rules are checked in
build(), with the same result whether the value came fromwithConfigor its own setter. Athresholdof1from a config file fails exactly aswithThreshold(1)does. A value that needs parsing rather than range-checking — the protocol name in anown_transportsentry, theunpair_ackstring — is resolved as soon as it is supplied, sowithOwnTransports/withUnpairAckcan throw straight from the call, and the sameown_transports/unpair_ackkey inside awithConfigargument can throw from that call instead.Stores, the transport and the constructor's
secretIdare not settings and are not carried in the config.Unknown keys throw, at any level —
decode_error— instead of being silently ignored, so a misspelled key in a config file fails loudly.
The canonical JSON, shared by every SDK, is:
Keys are snake_case and every key is optional. replica_id and max_subshares are u64 values written as decimal strings — a bigint throws decode_error; call withReplicaId/withMaxSubshares directly for a bigint. Timeouts are whole seconds. The same type and JSON shape apply to @derec-alliance/web; see the DeRecProtocolConfig doc comment in either package's index.d.ts for every field's accepted forms.
Store contracts
The five store interfaces are declared in index.d.ts; Implementing a persistent store covers each one. The points below are the ones a store most often gets wrong.
ShareStore.recordVerification(secretId: string, channelId: string, version: number): Promise<void>is required. The helper calls it once per accepted verification challenge, after the challenged share is found and before it answers. An app with no verification limit resolves it. TypeScript enforces the method at compile time; a plain-JS app does not, and aShareStorewithout it makes every verification a store failure: with the defaultwithAutoRespondOnFailure(false)the helper getsRequestFailed, and unless it answers the token the owner sees its challenges time out.Refusing from the share store. On a helper channel,
save(a new share version) andrecordVerificationmay throw, or reject with,shareStoreRefusal("too_frequent" | "size_limit_exceeded" | "rejected"). The library answers the owner withTOO_FREQUENT,SIZE_LIMIT_EXCEEDEDorREJECTED, the owner seesShareRejectedorShareVerifyRejected, and the helper's call returns[{ type: "NoOp" }]. Any other rejection is a backend failure, reported asRequestFailed.ShareStore.keepVersion(secretId: string, version: number): Promise<number>is the owner's retention decision, asked once per sharing round before anything is sent: the one older version every helper keeps besidesversion, or0for none. Resolve the newest version whoseSharingCompletereportedthreshold_met, or0before any did. A value>= versionfails the round withinvalid_keep_version. See Version retention.Share.subshares?: number | nullandShare.threshold?: number | nullare set by the library on owner-side shares only, and absent on a helper's share.UserSecrets.threshold?: number | nullis the threshold the next publish splits at. Persist each as given and return it unchanged;nullandundefinedboth mean none.Channel records are opaque bytes. Persist and return exactly the bytes
savereceived; never re-serialise a parsed record, becauseJSON.parserounds everyu64above 2^53. Parsing a helper record only to read itsweightis safe: take the channel id from the store call'schannelIdargument, never from the parsed object.
Transport
The library opens no socket. Every outbound envelope goes through your Transport:
endpoints is every endpoint the peer advertised, in the peer's order, already filtered by this node's transport policy. It is never empty and every entry addresses the same peer. The library does not rank the list: which endpoint to dial, and whether to fall back, is the transport's choice. Resolve on the first successful delivery; reject only when every endpoint failed. Sending to every endpoint delivers one message several times.
Prefer an adapter to writing send by hand. Write a SendOne — (endpoint, message) => Promise<void>, delivery to one endpoint — and wrap it:
sequentialFailover(dialer)— tries each endpoint in the peer's order and stops at the first success; throws the last error only when every endpoint failed. The right default.singleEndpointTransport(dialer)— uses the first endpoint only. Use it when failover was considered and declined; indexingendpoints[0]inline hides that decision.
A peer that cannot be addressed (a phone, a browser, anything behind NAT) cannot receive a pushed reply. See The transport is a mailbox.
Timeouts
withTimeouts configures four independent budgets. Every field is optional — omit one to keep the library default for it.
inbound_message_secs is a security boundary — it bounds how stale a message may be and still be accepted, so it has to tolerate transport latency and clock skew. A message older than it is dropped and reported as MessageIgnored with reason "Expired". The other three are liveness budgets. See Concurrency and scheduling and Timeouts and housekeeping.
tick()
Timeouts advance only inside process and tick. A publish whose peers all go quiet has nothing left to close it: the round stays open and no SharingComplete is ever emitted.
tick() is idempotent and safe on an idle protocol — with nothing in flight it touches no state and resolves to an empty array. A tick that overlaps a process call on the same instance queues behind it; see the next section. See Concurrency and scheduling.
Concurrency
Every method that touches protocol state returns a Promise and runs under one lock per instance. Overlapping calls on the same instance — a tick timer firing while process handles an inbound message — queue and run one at a time, in the order they were made. Distinct instances do not share the lock: two instances bound to the same secretId and the same stores must still be serialized by the application.
Lifetime
DeRecProtocol and DeRecProtocolBuilder hold memory inside the WASM module that the JavaScript garbage collector does not reclaim in time to rely on. Call free() when done with an instance; it also drops the instance's references to the stores and transport. free() is safe to call more than once; any other method called afterwards throws, as does calling free() while a call is in flight.
Both classes implement [Symbol.dispose](), so using works where the runtime supports explicit resource management:
build() releases the builder itself. Call free() on a builder only when discarding it unbuilt.
Protocol Flows
The SDK exposes every DeRec flow through a single protocol.start(flowKind, params) entry point plus the inbound process / accept loop. FlowKind has nine members: Pairing, Discovery, ProtectSecret, VerifyShares, RecoverSecret, Unpair, UpdateChannelInfo, ReplicaDiscovery and UnpairReplica. The chapters below cover all of them; the protocol-level description lives in Protocol Specification / Flows.
Two FlowKinds are replica-only and require withReplicaId:
Establish secure communication between two participants — Owner ↔ Helper, or Replica pairings
Split the Secret and distribute shares to Helpers; sync the full Secret to every member of the replica group
Verify Helpers still hold shares
Discover versions, recover shares, reconstruct the Secret, and restore
Unpair, UpdateChannelInfo, ReplicaDiscovery, UnpairReplica, rejecting requests, auto-accept, timeouts
Each flow follows the same shape: the initiator calls protocol.start(FlowKind.X, params); the library produces outbound envelopes through your Transport.send; the responder feeds inbound envelopes to protocol.process and consents to any { type: "ActionRequired" } event via protocol.accept(action), or refuses it via protocol.reject(action, status, memo).
Every start call that sends requests draws one correlation token and reports it as trace_id on its *Started events; the peer echoes it, and the receiving side sees it on ActionRequired.trace_id. Role mismatches and invalid parameters throw from start before any request goes out; they are not reported as *Failed events.
Matching responses to requests is the application's job. { type: "ShareConfirmed" }, { type: "ShareRejected" }, { type: "SecretsDiscovered" }, { type: "ChannelInfoUpdated" }, { type: "ChannelInfoUpdateRejected" } and { type: "ErrorResponseReceived" } are reported as responses arrive, without being matched to a request this device sent. Record what you started and match each event against it, by trace_id where you need an exact pairing. Decide which versions committed from SharingComplete.threshold_met, never by counting ShareConfirmed. See Matching responses to requests.
Message Model
The SDK operates on serialized protocol envelopes rather than exposing protobuf types directly on the public API.
Inbound and outbound envelopes are plain
Uint8Arraybuffers on both sides of the orchestratorThese bytes represent:
A serialized
DeRecMessageenvelope, orA plain serialized
ContactMessage(the out-of-band bootstrap, see Pairing)
For encrypted protocol exchanges, the
DeRecMessageenvelope contains an encrypted inner protobuf message — the library performs the encryption, decryption, and framing for you
This design ensures:
Transport-agnostic usage (HTTPS, gRPC, a mailbox relay, etc.)
Language-agnostic interoperability with the Rust, .NET, Go, and React Native SDKs
Clear separation between protocol and transport layers
Applications are responsible for:
Delivering outbound
Uint8Arrayenvelopes — the library passes them toTransport.send(endpoints, message)— to the counterpartyReceiving inbound
Uint8Arrayenvelopes and passing them back throughDeRecProtocol.process(...)
Numeric ids are u64 on the wire. On the input side the SDK takes a bigint (or a number where the declaration allows it), except where the declaration names a decimal string: UnpairParams.channel_id, UnpairReplicaParams.replica_id, and every id passed to a store callback. On event objects and errors, ids are always decimal strings, so JSON-serializable consumers can carry them across messaging boundaries without precision loss. Never round-trip an id through Number or JSON.parse: anything above 2^53 is silently rounded.
SenderKind, ContactMode, FlowKind and StatusEnum are frozen const objects plus a type of their values, not TypeScript enums. StatusEnum.Rejected works as a value and as a type. There is no reverse mapping: StatusEnum[8] does not compile (and never returned a name at run time), and assigning an arbitrary number to a StatusEnum does not compile. To show a name, keep your own lookup table.
Error Handling
All library-side errors surface as a thrown DeRecError:
DeRecError.category names the layer or flow that produced the error ("pairing", "sharing", "recovery", "verification", "discovery", "unpairing", "derec_message", "secret_store", "channel_store", "share_store", "state_store", "input", "protobuf", "invariant", "wasm"). code is a lower_snake name such as invalid_input, role_mismatch, channel_already_paired, replica_id_not_configured, replica_id_conflict, prepair_hash_mismatch, incompatible_parameter_range, no_usable_endpoint, already_restored, restore_conflict, invalid_threshold, invalid_weight (a weight outside 1 <= weight < threshold, or a key that is not a paired helper channel), too_many_subshares (a round above withMaxSubshares), invalid_keep_version (a keepVersion answer not below the version being shared), fingerprint_mismatch (from verifyFingerprint; the Pending pairing is revoked) or fingerprint_commitment_mismatch (a pair response whose nonce does not open the creator's commitment). Codes are global: one code means the same thing in every category, and the same (category, code) pair carries the same meaning in every language binding — see the cross-binding error catalog.
Errors raised by the JavaScript binding itself, before the library is reached — a malformed argument, an id that is not a valid u64 — carry category "wasm" and a binding code such as decode_error.
When process fails
process first settles any expired deadlines (sharing-round and unpair timeouts) and saves the result, then handles the message. If the message then fails, those deadlines stay settled and are never reported again, so the thrown error carries the events they produced:
DeRecError.events— every event the call produced before failing. Handle them exactly as a successful call's events, then handle the error.DeRecError.channel_id— the channel the failing message arrived on, as a decimal string. Absent when the bytes were not a decodable envelope.
A request that arrived on an authenticated channel and then failed does not make process or accept throw; it is a RequestFailed event (next section). The thrown error is left for what cannot be answered: an envelope that does not decode, a message that does not decrypt, a failure of the pairing handshake or of a response this device received.
See When process fails.
Failed requests
Every request that arrives on an authenticated channel is answered exactly once, even when handling it fails. The failure is reported as { type: "RequestFailed", channel_id, action_kind, responded, status, memo, error_code, message, action? }, and the call's other events, AutoAccepted included, are kept:
action_kindis thePendingActionKindof the failed request, or"Failed"when its body could not be decoded or is a request the channel cannot carry.statusandmemoare what was sent, or would have been.error_code(aDeRecErrorCode) andmessagedescribe the local error and never go on the wire.respondedistruewhen the library already sent the response;actionis then absent.With
responded: false,actionis a token of kind"Failed". Answer it withreject(action, status, memo): passing the event's ownstatusandmemosends exactly whatwithAutoRespondOnFailure(true)would have sent.acceptrefuses the token withinvalid_input, and noAutoAcceptPolicyfield covers it.
withAutoRespondOnFailure(true) makes the library answer: a failure with a protocol meaning keeps its status and memo (Rejected for a role mismatch, UnsupportedTransportProtocol, an invalid update, an unknown share version, every refusal), and anything else is Fail with the memo "request could not be processed". With it on, a token is still handed over when no reply target could be resolved. action is absent in two cases only: a request on a replica group channel that names no member and carries no replyTo, and, with the option off, a replica copy that hands this device the group key and fails before the key is stored.
The library never expires a pending action, so a token nobody answers leaves its sender to time out. It is also stateless: resolving each token once is the application's job, and rejecting the same token twice sends two responses.
Related events:
{ type: "ErrorResponseReceived", channel_id, status, memo }— the peer answered a message from this device with anErrorResponseMessage, typicallyFormatErrorwith memo"message body could not be decoded". Never answered. One from a 0.0.8 peer carries no timestamp and is ignored asMessageIgnoredwith reason"TimestampMismatch".{ type: "PairingRefused" },{ type: "ShareRefused" }and{ type: "ReplicaSecretRefused" }— protocol refusals, answered in both modes; see Parameter ranges, Helpers consent and Replica targets.
MessageIgnored.reason is "PendingVerification", "Expired", "TimestampMismatch" (the envelope and inner-message timestamps differ or are absent; a 0.0.8 peer's replies land here, so upgrade both sides together) or "StaleResponse" (a verification answer to a replaced challenge). See RequestFailed and ErrorResponseReceived.
Utilities
Both packages export a small set of functions alongside the orchestrator:
sequentialFailover(dialer) / singleEndpointTransport(dialer)
Build a Transport from a SendOne; see Transport.
generate_replica_id()
A fresh replica id as a bigint, never 0. Mint it once per device and persist it; see Pairing.
protocol_version()
{ major, minor } — the DeRec protocol version this build writes into every envelope (currently 0.0). Not the package version. See Versioning.
channelFilterMatches(filter, id, status, role)
Whether a row survives a HelperFilter / ReplicaFilter — for a ChannelStore that cannot express the filter as a query. See Channel filters.
advertisedEndpoints(message)
The endpoints a ContactMessage, PairRequestMessage or PrePairRequestMessage advertises, in the peer's order. Reports what was advertised; nothing is validated.
envelope.apply_trace_id(bytes, traceId) / envelope.read_trace_id(bytes)
Set or read the plaintext traceId on a DeRecMessage envelope without touching the encrypted payload. read_trace_id returns 0n when unset.
primitives
The stateless primitive layer: primitives.pairing, primitives.sharing, primitives.verification, primitives.discovery, primitives.recovery, primitives.unpairing.
primitives.* exposes each flow's request / response produce / extract / process functions for integrators who keep their own state instead of using DeRecProtocol. primitives.pairing also carries request.create_contact, request.encode_contact / decode_contact (contact serialization), the HashedKeys and NoKeys pre-pair functions, and fingerprint(sharedKey). primitives.sharing.request.split(channels, secret_id, version, secret_data, threshold) takes channels: WeightedChannel[], each a [channelId, weight] tuple (1 for an ordinary helper, every weight in 1 <= weight < threshold); it applies no subshare cap. Caller-held state, binding checks and persistence are the caller's at this layer. See Primitives and orchestrator.
API Reference
Each package ships its index.d.ts alongside the JavaScript so editors and type-checkers surface the full surface natively. The published types are the authoritative reference for every method, parameter, and DeRecEvent variant documented in this section.
SDK Architecture
The TypeScript packages provide the managed DeRecProtocol orchestrator surface — turning the WASM-exported functions into typed async methods, marshalling Uint8Array / bigint across the JS/WASM boundary, and shaping events into the DeRecEvent union. The WASM blob is the same compiled derec-library crate the Rust SDK consumes directly. Every binding is a thin translation over the same core.
Last updated