{"project":{"name":"Dropspace","package":"dropspace","tagline":"Self-Hostable Device Pairing, P2P DataChannels & CRDT Sync","subtitle":"Connect browsers, phones, and servers directly over WebRTC without centralized file storage. Pair trusted devices via single-use QR invites, stream files in bounded memory, and sync offline-first state.","protocolVersion":1,"wireMagicByte":"0xD5","defaultChunkSize":"48 KiB","maxTotalFrameBytes":"64 KiB","license":"MIT","contactEmail":"iamaroott@gmail.com","repository":"https://github.com/indatawetrust/dropspace-server"},"useCases":[{"id":"airdrop","badge":"File Sharing","title":"Direct Device-to-Device File Transfer","description":"Send files directly from laptop to phone or colleague over WebRTC DataChannels. Files stream in bounded-memory chunks into OPFS (origin-private storage) or File System Access API with SHA-256 verification and same-page pause/resume — without centralized file storage."},{"id":"local-first","badge":"Collaboration","title":"Offline-First Notes & Shared State","description":"Keep editing in IndexedDB when Wi-Fi drops. As soon as two paired devices reconnect, Automerge CRDT character-level diffs converge automatically over a direct P2P DataChannel."},{"id":"companion","badge":"Device Pairing","title":"Phone-to-Desktop Companion Pairing","description":"Scan a single-use QR invite (with the bearer secret in the URL #fragment) to link a mobile browser to your desktop app. Approve via visual SHA-256 fingerprint comparison, grant scoped permissions, and revoke access anytime."}],"features":[{"id":"identity","badge":"Security","title":"Cryptographically Authenticated Identity","description":"Each device generates a non-extractable ECDSA P-256 or Ed25519 keypair in IndexedDB and verifies SHA-256 fingerprints visually before trusting a peer.","highlights":["ECDSA P-256 & Ed25519","Non-extractable WebCrypto keys","Per-space permission scopes"]},{"id":"pairing","badge":"Onboarding","title":"Smart QR & Token Pairing","description":"Create time-bounded, single-use invite tokens (inv_...) with scoped permissions. Approve or reject devices explicitly in real time.","highlights":["Single-use high-entropy tokens","Explicit fingerprint approval","Real-time revocation for online peers"]},{"id":"framing","badge":"Transport","title":"Multiplexed 0xD5 Wire Protocol","description":"Traffic over the dropspace-v1 DataChannel uses a 6-byte prefix + UTF-8 JSON header + raw payload, with priority queuing so bulk chunks do not starve ACKs or chat.","highlights":["0xD5 binary framing","Priority-queued virtual channels","Bounded reassembly & backpressure"]},{"id":"files","badge":"Storage","title":"Bounded-Memory File Transfer & OPFS","description":"Stream files in slices without loading whole files into RAM, with streaming SHA-256 verification and same-page checkpoint resume.","highlights":["Bounded-memory slice streaming","Streaming SHA-256 verification","OPFS & File System Access export"]},{"id":"crdt","badge":"CRDT Sync","title":"Offline-First Automerge Sync","description":"Bind Automerge.next documents with character-level text editing (updateText) to paired peer sessions. Edits persist in IndexedDB and converge on reconnect.","highlights":["Automerge.next text CRDT","IndexedDB persistence adapter","Conflict-free offline merges"]},{"id":"self-host","badge":"Self-Hosted","title":"Lightweight BEAM Core & Optional Hub","description":"The signaling coordinator runs on Gleam (Erlang/OTP) with SQLite persistence and ephemeral HMAC TURN credentials.","highlights":["Gleam / Erlang OTP core","Ephemeral coturn credentials","Optional Elixir WebRTC hub"]}],"packages":[{"name":"dropspace","layer":"TypeScript SDK","description":"Subpath exports: \"dropspace\", \"dropspace/files\", \"dropspace/automerge\", and \"dropspace/protocol\"."},{"name":"dropspace_core","layer":"Gleam / BEAM Server","description":"Self-hosted signaling server, challenge-response auth, pairing state machine, and TURN issuer."},{"name":"dropspace_server_peer","layer":"Elixir OTP Integration","description":"Headless WebRTC DataChannel node (ex_webrtc / ex_sctp) for automated testing and hub relay."}],"examples":[{"id":"connect-pair","tabLabel":"1. Quick Start (A + B)","title":"Complete Two-Device Pairing, Messaging & Cleanup","summary":"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.","packageName":"dropspace","lang":"typescript","code":"import { DropspaceClient, IndexedDbIdentityStorageAdapter } from \"dropspace\";\n\n// 1. Setup Device A & Device B (in separate browsers/devices)\nconst deviceA = new DropspaceClient({\n  coreHttpUrl: \"https://dropspace.app\",\n  identityStorage: new IndexedDbIdentityStorageAdapter(\"app_device_a\"),\n  deviceLabel: \"Laptop-A\",\n});\nconst deviceB = new DropspaceClient({\n  coreHttpUrl: \"https://dropspace.app\",\n  identityStorage: new IndexedDbIdentityStorageAdapter(\"app_device_b\"),\n  deviceLabel: \"Phone-B\",\n});\n\n// 2. Register listeners BEFORE sharing invites, then connect to Core\ndeviceA.events.on(\"pairingAwaitingApproval\", async (req) => {\n  // Compare req.claimerFingerprint visually before approving\n  await deviceA.pairing.approve(req.pairingId, [\"connect\", \"messaging\", \"files\", \"crdt\"]);\n});\ndeviceB.events.on(\"message\", (msg) => {\n  console.log(\"Device B received:\", msg.json);\n});\n\nawait Promise.all([deviceA.start(), deviceB.start()]);\nconst spaceId = deviceA.getSessionInfo().defaultSpaceId!;\n\n// 3. Device A creates a single-use invite (connect permission required for WebRTC)\nconst invite = await deviceA.pairing.createInvite({\n  spaceId,\n  permissions: [\"connect\", \"messaging\", \"files\", \"crdt\"],\n  ttlMs: 300_000,\n});\n\n// 4. Device B claims the invite & subscribes to the space\nconst claimed = await deviceB.pairing.claimInvite(invite.inviteToken);\nawait deviceB.devices.subscribeSpace(claimed.spaceId);\n\n// 5. Wait for P2P connection (after Device A's explicit approval above)\nconst peerBId = deviceB.getIdentity().deviceId;\nawait deviceA.connect(peerBId, { spaceId, waitForOpen: true });\n\n// 6. Send an ACKed P2P message (\"received\" = delivered to peer, not read)\nconst receipt = await deviceA.channels.sendJson(\n  peerBId,\n  { text: \"Hello from Laptop-A!\" },\n  { channel: \"chat\", ack: \"received\" },\n);\nconsole.log(\"Delivery ACK:\", receipt.ackSemantics);\n\n// 7. Cleanup\ndeviceA.close();\ndeviceB.close();"},{"id":"messaging","tabLabel":"2. P2P Messaging","title":"Peer Selection & Priority-Queued Messaging with ACKs","summary":"Select the best online peer in a space deterministically and send JSON or binary payloads over the multiplexed dropspace-v1 DataChannel.","packageName":"dropspace","lang":"typescript","code":"const spaceId = client.getSessionInfo().defaultSpaceId!;\nconst best = client.devices.selectPeer({\n  spaceId,\n  requiredCapabilities: [\"messaging\"],\n  requiredPermissions: [\"messaging\"],\n});\n\nif (best.selectedDeviceId) {\n  await client.connect(best.selectedDeviceId, { spaceId, waitForOpen: true });\n\n  client.events.on(\"message\", (msg) => {\n    if (msg.channel === \"chat\") {\n      console.log(`[${msg.messageId}] from ${msg.peerDeviceId}:`, msg.json);\n    }\n  });\n\n  const receipt = await client.channels.sendJson(\n    best.selectedDeviceId,\n    { text: \"Hello over direct P2P DataChannel!\" },\n    { channel: \"chat\", ack: \"received\" },\n  );\n  console.log(\"Delivery confirmed:\", receipt.ackSemantics);\n}"},{"id":"file-transfer","tabLabel":"3. Resumable Files","title":"Bounded-Memory Resumable File Transfer into OPFS","summary":"Stream files in bounded-memory chunks with per-chunk & end-to-end SHA-256 verification. Note: OPFS is origin-private storage, not a normal user-visible folder; export completed files via File System Access API or Blob download.","packageName":"dropspace/files","lang":"typescript","code":"import { FileTransferManager, createBlobFileSource } from \"dropspace/files\";\nimport { OpfsBinaryStagingAdapter } from \"dropspace\";\n\nconst files = new FileTransferManager({\n  client,\n  storage: new OpfsBinaryStagingAdapter(),\n  policy: {\n    autoAccept: false,\n    onIncomingOffer: async (manifest) => {\n      return confirm(`Accept ${manifest.fileName} (${manifest.totalBytes} B)?`);\n    },\n  },\n});\n\nfiles.events.on(\"progress\", (ev) => {\n  const pct = ev.totalBytes > 0 ? Math.round((ev.transferredBytes / ev.totalBytes) * 100) : 100;\n  console.log(`[${ev.direction}] ${ev.fileName}: ${pct}% (${ev.state})`);\n});\n\nfiles.events.on(\"completed\", ({ manifest }) => {\n  console.log(`Verified SHA-256 (${manifest.fileSha256}) for ${manifest.fileName}`);\n});\n\n// Stream a File from <input type=\"file\"> in bounded memory\nconst source = createBlobFileSource(fileInput.files![0]);\nconst manifest = await files.sendFile(peerDeviceId, source, { waitForCompletion: false });\n\n// Same-page pause & resume from the last verified chunk checkpoint\nawait files.pauseTransfer(manifest.transferId);\nawait files.resumeTransfer(manifest.transferId);"},{"id":"crdt-sync","tabLabel":"4. Automerge CRDT","title":"Offline-First Collaborative Document Sync","summary":"Use Automerge.next character-level text editing (updateTextField) with IndexedDB persistence. Only the creator initializes content so joiners do not create competing root histories.","packageName":"dropspace/automerge","lang":"typescript","code":"import {\n  DropspaceAutomergeManager,\n  IndexedDbCrdtStorageAdapter,\n  type DropspaceNoteDoc,\n} from \"dropspace/automerge\";\n\nconst crdt = new DropspaceAutomergeManager<DropspaceNoteDoc>({\n  client,\n  storage: new IndexedDbCrdtStorageAdapter(\"my-app-crdt\"),\n});\n\n// Creator initializes; joiners call openOrCreateDocument(\"shared-note\") without initialValue\nawait crdt.openOrCreateDocument(\"shared-note\", {\n  title: \"Architecture Notes\",\n  body: \"\",\n  updatedAt: Date.now(),\n  updatedBy: client.getIdentity().deviceId,\n  attachments: [],\n});\n\ncrdt.events.on(\"documentUpdated\", ({ doc, source }) => {\n  if (source === \"remote\") {\n    console.log(\"Remote merge:\", doc.title, doc.body);\n  }\n});\n\n// Character-level collaborative edit (Automerge.next.updateText)\nawait crdt.updateTextField(\"shared-note\", \"body\", \"Updated collaboratively over WebRTC.\");"},{"id":"self-host","tabLabel":"5. Self-Host Core","title":"Run the Gleam Signaling Core & Demo","summary":"Start the Gleam OTP signaling server locally, or deploy the production Erlang shipment behind Caddy/Nginx and Coturn.","packageName":"dropspace_core","lang":"bash","code":"# Option A: Run local Gleam signaling core + Vite interactive demo\npnpm run dev:core   # Starts dropspace_core on http://127.0.0.1:4000\npnpm run dev:demo   # Starts browser P2P workbench on http://localhost:5173\n\n# Option B: Build production Erlang shipment\ncd apps/core\ngleam export erlang-shipment\n\nDROPSPACE_HOST=127.0.0.1 \\\nDROPSPACE_PORT=4000 \\\nDROPSPACE_DB_PATH=/var/www/dropspace-server/dropspace.sqlite3 \\\nDROPSPACE_ALLOWED_ORIGINS=\"https://dropspace.app\" \\\n./build/erlang-shipment/entrypoint.sh run"}],"wireLayout":[{"bytes":"Byte 0","field":"Magic Byte (0xD5)","detail":"Fixed prefix identifying Dropspace v1 binary framing"},{"bytes":"Byte 1","field":"Frame Type (0x01–0x07)","detail":"CONTROL_JSON, MESSAGE_JSON, MESSAGE_BINARY, TRANSFER_CONTROL, TRANSFER_CHUNK, CRDT_SYNC, HUB_RELAY"},{"bytes":"Bytes 2..5","field":"Header Length (uint32 BE)","detail":"Big-endian byte length of UTF-8 JSON header (1..16,384 bytes)"},{"bytes":"Bytes 6..(6+N-1)","field":"WireFrameHeader (JSON)","detail":"Strict UTF-8 JSON: messageId, channel, timestamp, ackMode, transferId, documentId, hopCount"},{"bytes":"Bytes (6+N)..End","field":"Raw Binary Payload","detail":"Uint8Array slice; totalFrameBytes = 6 + headerBytes + payloadBytes (<= 64 KiB baseline)"}]}