Documentation & SDK Reference

SDK Guides, Wire Framing & Security Model

Install dropspace and import only the subpaths you need (dropspace, dropspace/files, dropspace/automerge, dropspace/protocol).

Usage Examples

Step-by-Step TypeScript SDK Guides

From cryptographic device pairing to resumable OPFS file transfers, Automerge CRDT synchronization, and self-hosting.

dropspace

Complete Two-Device Pairing, Messaging & Cleanup

End-to-end Device A and Device B flow: install, connect to Core, create invite, claim invite, explicit fingerprint approval, P2P connect, ACKed messaging, and cleanup.

import { DropspaceClient, IndexedDbIdentityStorageAdapter } from "dropspace";

// 1. Setup Device A & Device B (in separate browsers/devices)
const deviceA = new DropspaceClient({
  coreHttpUrl: "https://dropspace.app",
  identityStorage: new IndexedDbIdentityStorageAdapter("app_device_a"),
  deviceLabel: "Laptop-A",
});
const deviceB = new DropspaceClient({
  coreHttpUrl: "https://dropspace.app",
  identityStorage: new IndexedDbIdentityStorageAdapter("app_device_b"),
  deviceLabel: "Phone-B",
});

// 2. Register listeners BEFORE sharing invites, then connect to Core
deviceA.events.on("pairingAwaitingApproval", async (req) => {
  // Compare req.claimerFingerprint visually before approving
  await deviceA.pairing.approve(req.pairingId, ["connect", "messaging", "files", "crdt"]);
});
deviceB.events.on("message", (msg) => {
  console.log("Device B received:", msg.json);
});

await Promise.all([deviceA.start(), deviceB.start()]);
const spaceId = deviceA.getSessionInfo().defaultSpaceId!;

// 3. Device A creates a single-use invite (connect permission required for WebRTC)
const invite = await deviceA.pairing.createInvite({
  spaceId,
  permissions: ["connect", "messaging", "files", "crdt"],
  ttlMs: 300_000,
});

// 4. Device B claims the invite & subscribes to the space
const claimed = await deviceB.pairing.claimInvite(invite.inviteToken);
await deviceB.devices.subscribeSpace(claimed.spaceId);

// 5. Wait for P2P connection (after Device A's explicit approval above)
const peerBId = deviceB.getIdentity().deviceId;
await deviceA.connect(peerBId, { spaceId, waitForOpen: true });

// 6. Send an ACKed P2P message ("received" = delivered to peer, not read)
const receipt = await deviceA.channels.sendJson(
  peerBId,
  { text: "Hello from Laptop-A!" },
  { channel: "chat", ack: "received" },
);
console.log("Delivery ACK:", receipt.ackSemantics);

// 7. Cleanup
deviceA.close();
deviceB.close();
Data Plane

Binary Wire Frame Layout (Magic Byte 0xD5)

Every WebRTC DataChannel packet uses a deterministic 6-byte prefix followed by a UTF-8 JSON header and raw binary payload.

Binary Frame Structure Big-Endian
+------------------+-------------------+---------------------------+------------------------+-----------------------+
| Byte 0           | Byte 1            | Bytes 2..5 (uint32 BE)    | Bytes 6..(6+N-1)       | Remaining Bytes       |
+------------------+-------------------+---------------------------+------------------------+-----------------------+
| Magic: 0xD5      | FrameType (1..7)  | Header Byte Length (N)    | UTF-8 JSON FrameHeader | Raw Binary Payload    |
+------------------+-------------------+---------------------------+------------------------+-----------------------+
Hex Frame Type Description
0x01 CONTROL_JSON End-to-end ACK frames (received, persisted, processed), ping/pong, and channel control.
0x02 MESSAGE_JSON Structured UTF-8 JSON application messages scoped by logical channel name.
0x03 MESSAGE_BINARY Raw Uint8Array binary payloads with optional chunking and ACK correlation.
0x04 TRANSFER_CONTROL File transfer offer, accept, pause, resume byte offset, cancel, and verification status.
0x05 TRANSFER_CHUNK 64 KiB streaming file slice carrying transferId, byteOffset, and per-chunk SHA-256 hash.
0x06 CRDT_SYNC Automerge incremental binary sync messages scoped by documentId.
0x07 HUB_RELAY Explicit 1-hop store-and-forward frame routed through an authorized_hub peer with messageId deduplication.
Control Plane

Core Server HTTP & WebSocket Endpoints

Served by apps/core (Gleam + Mist on BEAM) with SQLite persistence.

Method Endpoint Purpose
GET /healthz Liveness check returning status and protocol version.
GET /metrics JSON operational counters for active sessions, spaces, pairings, and relayed messages.
POST /api/v1/auth/challenge Issues a single-use cryptographic challenge nonce for device signature authentication.
POST /api/v1/auth/verify Verifies ECDSA_P256_SHA256 or ED25519 signature over the canonical challenge and issues a session token.
GET /api/v1/spaces/:spaceId/devices Lists trusted paired devices and their granted permission scopes in the space.
WS /ws Real-time signaling WebSocket for presence, pairing invites, TURN credentials, and WebRTC SDP/ICE exchange.
Least-Privilege Trust

Space & Permission Model

Each authenticated device receives an implicit defaultSpaceId (space_<deviceId>) and can subscribe to additional spaces via client.devices.subscribeSpace(spaceId). Peer selection, presence, and permissions are scoped per spaceId. The connect permission is required by Core for WebRTC signaling, and receiving peers also enforce messaging, files, and crdt permissions on incoming DataChannel frames.

connect

Establish WebRTC PeerConnections and exchange ICE/SDP with the peer.

messaging

Send and receive JSON and binary messages on logical channels.

files

Offer, accept, and resume chunked file transfers.

crdt

Synchronize shared Automerge CRDT documents.

hub_relay

Relay 1-hop frames through an opted-in authorized hub peer when direct P2P fails.

admin

Manage space topology and revoke compromised peer pairings.

Architecture, Security & Quotas

Three Modes, Auth Separation, CORS/WS Policy & TURN vs Hub

Dropspace separates Developer/Admin accounts, App Backend API keys, and Device cryptographic keys across App → Spaces → Memberships / Pairings / Sessions.

appId Is Not a Secret

appId is a public tenant identifier. In public_client mode, any client can register a device under that appId (origin lists only govern browser CORS, not non-browser clients). For strict access control, use backend_authorized and mint short-lived JWT accessTickets on your backend via POST /api/v1/apps/:appId/tickets (or sign EdDSA JWTs externally) — never embed dsk_... secrets in browser code.

CORS & WebSocket Origin

HTTP CORS validates exact scheme/host/port (with strict *.domain subdomain matching, separate dev localhost rules, null origin rejected, and Vary: Origin). WebSocket upgrades validate Origin separately (allowing absent Origin for native/CLI clients) and authenticate via the first WS message (never URL query secrets).

TURN vs Hub & Limits

Coturn 4.6.2 enforces global/per-user allocation and bandwidth quotas (user-quota, total-quota, max-bps, bps-capacity); Core enforces credential issuance rate limits and turnEnabled. Note: expired TURN credentials prevent new allocations, while existing Coturn allocations live until max-allocate-lifetime. Public playground disables the Application Hub by default. Browser tabs suspended in background may drop P2P connections.

Self-Hosting

Run Core & Coturn Independently

Set DROPSPACE_MODE=self_host, DROPSPACE_PUBLIC_PLAYGROUND_ENABLED=false, DROPSPACE_ALLOWED_ORIGINS, DROPSPACE_TURN_SECRET, and DROPSPACE_ADMIN_TOKEN. Existing v0 SQLite databases automatically migrate to app_self_host_default without data loss.

Protocol & Transport Limits

0xD5 Framing, Reassembly & Public Core Policy

Every frame satisfies totalFrameBytes = 6 + encodedHeaderBytes + payloadBytes. Header limit is 16 KiB, default total frame limit is 64 KiB (or negotiated SCTP limit), and chunked reassembly is bounded to 2048 chunks, 16 MiB total buffer, and 30s timeout.

Public Core (dropspace.app)

https://dropspace.app hosts the demo and public signaling endpoint for allowed origins (configured via DROPSPACE_ALLOWED_ORIGINS). Ephemeral TURN credentials are issued only to authenticated WebSocket sessions. For production apps, self-host apps/core and set coreHttpUrl to your own domain.

OPFS & Resume Levels

OPFS is origin-private storage, not a normal user-visible folder; use Save / Export (showSaveFilePicker or Blob download) to write to disk. Same-page network drops resume automatically via chunk bitmap; page refresh requires re-selecting the source file and verifying SHA-256.

Command-Line Interface

Dropspace CLI (npx dropspace)

Manage device identities, save default server/space settings per profile, create or claim pairing invites, inspect space peers, and stream signaling events directly from Node.js.

# Save default Core URL, space, appId, or device label (~/.dropspace/default.config.json)
npx dropspace config set --url https://dropspace.app --space space_demo_sandbox --label "My-CLI"
npx dropspace config get

# Check server health & local ECDSA P-256 identity (~/.dropspace/default.json)
npx dropspace health
npx dropspace identity

# Create or claim a single-use pairing invite
npx dropspace invite create --ttl 300 --permissions chat,files,sync
npx dropspace invite claim "<token-or-deep-link>"

# List peers, stream live events, or relay JSON via a space hub
npx dropspace peers
npx dropspace listen --auto-approve
npx dropspace send --to dev_... --via-hub dev_hub_... --text "Hello from CLI"