Skip to content

Building blocks

This content is for the 0.2.0-alpha.3 version. Switch to the latest version for up-to-date documentation.

The supported surface is the Client facade — client.auth, client.storage, client.message, client.space. This page catalogs the lower-level exports the SDK is composed from. They’re public so power users can compose their own flows, but you rarely need them directly, and their shapes can change between minor versions ahead of 1.0.

Raw WebSocket transport: owns the socket lifecycle, auto-reconnect, outbound frame buffering, and a ping/pong heartbeat. Frames are encrypted a layer up.

new WSTransport({
url: string;
autoReconnect?: boolean; // default true
reconnectDelay?: number; // ms, default 3000
maxReconnectAttempts?: number;// default 5 (0 = unlimited)
maxQueueSize?: number; // default 100
heartbeatInterval?: number; // ms, default 30000 (0 = off)
heartbeatTimeout?: number; // ms, default 10000
pingFrame?: string; // default "ping"
pongFrame?: string; // default "pong"
});
connect(): Promise<void>;
disconnect(): void;
send(frame: string): void;
isConnected(): boolean;
isConnecting(): boolean;
queuedFrames(): number;
reconnectAttemptCount(): number;
// extends EventCore: on/off/emit

Process-global event hub used internally for connection lifecycle. Events: connected, disconnected, reconnecting, error, data_received, data_sent, message, get_history, received_history (the EventCoreEvents enum).

EventCore.on(event: EventCoreEvents, handler): void;
EventCore.off(event: EventCoreEvents, handler): void;
EventCore.emit(event: EventCoreEvents, data: unknown): void;

A serializable message body with an id, timestamp, and auto-computed checksum.

new Message({ body, id?, status?, checksum? });
message.body; // get deserializes; set serializes + checksums
message.serialize(): string;
Message.deserialize(data: string): Message;
message.verifyChecksum(): void; // throws on mismatch

Routing envelope around a Message: subject, source, target, optional headers, ttl, and signature.

new Packet({ subject, source, target, message?, headers?, ttl?, signature? });
packet.serialize(): string;
Packet.deserialize(data: string): Packet;
packet.isExpired(): boolean;

Coordinates a WSTransport, an encrypted session, and packet (de)serialization, and exposes both WebSocket send and HTTP verbs. The Client builds these for you; construct one directly only for fully custom transports.

new Network({
url: string; clientId: string; serverId: string;
apiUrl?: string; sessionType?: "global" | "specific";
cipher?: PacketCipher; // defaults to a Double Ratchet cipher
frameTag?: string; // top-level frame discriminator, e.g. "payload"
// …reconnect / http retry / header options
});
connect(): Promise<void>;
disconnect(): void;
send(opts): Promise<boolean>;
get/post/put/delete/patch<T>(opts): Promise<HttpResponse<T>>;
isConnected(): boolean;

The pluggable encryption interface Network uses. Implementations: DoubleRatchetCipher (per-peer, forward-secret) and SpacePacketCipher (group-key sealing).

interface PacketCipher {
seal(serializedMessage: string, packet: Packet): Promise<SealedHeaders>;
handles(headers: PacketHeaders): boolean;
open(headers: PacketHeaders): Promise<string | null>; // null if not for us
}

These power client.space and the keeper-admitted, server-blind group-key distribution described in Spaces.

Holds per-epoch group keys and coordinates distribution: a newcomer posts a join request, a key-holder ECIES-wraps the key to the newcomer’s identity key, the newcomer unwraps it. The relay only ever sees opaque blobs.

const k = new SpaceKeyring({ spaceId, memberId, identityEcdhPub, ownPrivateKey, transport, … });
k.currentEpoch(): number;
k.keyForEpoch(epoch: number): Uint8Array | undefined;
k.bootstrapNew(): Promise<void>; // creator mints epoch-0 key
k.requestKey(desiredEpoch?: number): Promise<void>;
k.pullKeys(): Promise<number>; // unwrap blobs addressed to us
k.admit(memberId, identityEcdhPub): Promise<void>;
k.admitPending(): Promise<string[]>;
k.rotate(roster?): Promise<number>; // new epoch
k.invite(username): Promise<void>;
// KEEPER_MEMBER_ID — reserved id for the app's keeper member

HTTP implementation of the keyring transport (postJoinRequest, fetchBlobs, postWrappedKey, fetchPending, fetchRoster, rotate, invite, fetchMetadata).

new KeyringClient({ spaceId: string; httpBaseUrl: string; fetch: typeof fetch });

A PacketCipher that seals each message under the current epoch’s group key.

new SpacePacketCipher(keys: EpochKeyProvider, contentType?: string);

Pure crypto helpers for the space layer: generateSpaceKey(), generateSpaceIdentity(), ECDH public-key import/export, ECIES wrapSpaceKey / unwrapSpaceKey, message sealMessage / openMessage, and ECDSA signSpaceMessage / verifySpaceMessage.

The ZK-gated HTTP client backing client.storage. Each call fetches a challenge nonce, generates a Groth16 proof for the preimagePoK circuit, and sends it with the operation. Depends on snarkjs.

new PersonalSpaceClient({ baseUrl, commitment, secret, salt, ecdsaPub, ecdsaPubHash, circuits });
put(key: string, value: unknown): Promise<void>;
get<T>(key: string): Promise<T | null>;
delete(key: string): Promise<boolean>;
list(): Promise<string[]>;

An edge/serverless-compatible Groth16 verifier driving bn128.wasm directly (no snarkjs/ffjavascript). Exported from every build, including the edge/serverless one — it’s how proofs are verified at the edge.

initBn128Wasm(wasmModule?: WebAssembly.Module): Promise<Bn128WasmInstance>;
verifyGroth16(
instance: WebAssembly.Instance, memory: WebAssembly.Memory, initialPFree: number,
verificationKey: VerificationKey, proof: Groth16Proof, publicSignals: string[],
): Promise<boolean>; // false on structural failure; throws only on WASM faults
// PREIMAGE_POK_VERIFICATION_KEY — the verification key for the preimagePoK circuit

Logger plus byte/serialization helpers, exported from the package root.

new Logger(prefix?: string, level?: string, showCaller?: boolean);
// .info .warn .error .debug .verbose .success .setLevel(level)
generateId(): string; // base58-encoded UUID
serialize<T>(data: T): string; // base58
deserialize<T>(s: string): T;
// byte helpers
toHex / fromHex / toBase64 / fromBase64 / toBase64Url / fromBase64Url
concatBytes / utf8Encode / utf8Decode
// method decorators
Retry(retries?, delay?)
Ready(readyProp?)

Re-exported from the package root (and importable as types.*). Grouped by domain:

DomainTypes
IdentityZkIdentity, AuthUser, UserIdentity, Session, AuthType, OAuthProvider
PermissionsPermission, Role, ACL, ACLEntry, Participant, PermissionCheckRequest, PermissionCheckResult
CryptoKeypair, DehydratedKeypair, PublicKeyJWK, ECDHCurve
MessagingMessageEvent, Subscription, WSMessage, WSMessageType
Zero-knowledgeGroth16Proof, VerificationKey, CircuitUrls, PREIMAGE_POK_VERIFICATION_KEY
SpacesWrappedKey, SpaceMetadata, JoinRequest, RosterMember, HistoryPolicy
StorageFileManifest, ChunkManifest, FileStat