From e19797b4e43de0fa4cd31a1aea6a93ddf02652b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Thu, 19 Feb 2026 11:41:00 -0300 Subject: [PATCH] add WASM browser module and browser demo --- browser/demo/demo.js | 1118 ++++++++++++++++++++ browser/demo/index.html | 86 ++ browser/demo/zig-p2p.wasm | 1 + browser/host/file-host.js | 331 ++++++ browser/host/package.json | 16 + browser/host/platform-env.js | 66 ++ browser/host/signaling.js | 137 +++ browser/host/webrtc-host.js | 323 ++++++ browser/host/zig-p2p.js | 461 ++++++++ browser/signaling-server/package-lock.json | 36 + browser/signaling-server/package.json | 13 + browser/signaling-server/server.js | 212 ++++ src/wasm/main.zig | 571 ++++++++++ 13 files changed, 3371 insertions(+) create mode 100644 browser/demo/demo.js create mode 100644 browser/demo/index.html create mode 120000 browser/demo/zig-p2p.wasm create mode 100644 browser/host/file-host.js create mode 100644 browser/host/package.json create mode 100644 browser/host/platform-env.js create mode 100644 browser/host/signaling.js create mode 100644 browser/host/webrtc-host.js create mode 100644 browser/host/zig-p2p.js create mode 100644 browser/signaling-server/package-lock.json create mode 100644 browser/signaling-server/package.json create mode 100644 browser/signaling-server/server.js create mode 100644 src/wasm/main.zig diff --git a/browser/demo/demo.js b/browser/demo/demo.js new file mode 100644 index 0000000..4e90669 --- /dev/null +++ b/browser/demo/demo.js @@ -0,0 +1,1118 @@ +/** + * zig-p2p Browser Demo (v1 Protocol) + * + * Loads the WASM P2P library, connects to a signaling server, and allows + * connecting to desktop (or other browser) peers via WebRTC DataChannel. + * Messages are sent through the full zig-p2p stack: wire envelope + Noise. + * + * v1 Protocol Features: + * - Version byte in offer for forward compatibility + * - Transfer ID for multi-transfer routing + * - SHA-256 integrity verification + * - Timeout + cancellation + * - Path traversal protection (XSS-safe DOM rendering) + */ + +import { ZigP2P } from '../host/zig-p2p.js'; + +/** @type {ZigP2P | null} */ +let p2p = null; + +/** @type {Map} channel_id → 32-byte P2P PeerId */ +const channelPeerIds = new Map(); + +const statusText = document.getElementById('statusText'); +const peerIdSpan = document.getElementById('peerId'); +const channelsSpan = document.getElementById('channels'); +const connectBtn = document.getElementById('connectBtn'); +const disconnectBtn = document.getElementById('disconnectBtn'); +const peerBtn = document.getElementById('peerBtn'); +const sendBtn = document.getElementById('sendBtn'); + +function log(text, cls = 'info') { + const el = document.getElementById('log'); + const entry = document.createElement('div'); + entry.className = `log-entry ${cls}`; + const ts = new Date().toLocaleTimeString(); + entry.textContent = `[${ts}] ${text}`; + el.appendChild(entry); + el.scrollTop = el.scrollHeight; +} + +function updateStatus(text) { + statusText.textContent = text; +} + +function updateChannels() { + if (p2p) { + channelsSpan.textContent = p2p.channelCount; + } +} + +setInterval(updateChannels, 1000); + +// ============================================================ +// Wire Protocol v1 — App IDs and constants +// ============================================================ +const PROTOCOL_VERSION = 0x01; +const APP_ID_CHAT = 0x10; +const APP_ID_FILE_OFFER = 0x20; +const APP_ID_FILE_ACCEPT = 0x21; +const APP_ID_FILE_CHUNK = 0x22; +const APP_ID_FILE_COMPLETE = 0x23; +const APP_ID_FILE_CANCEL = 0x24; +const APP_ID_FILE_RESUME = 0x25; +const APP_ID_FILE_PAUSE = 0x26; +const CHUNK_SIZE = 64 * 1024; // 64KB — optimal for SCTP throughput +const MAX_BUFFERED_AMOUNT = 16 * 1024 * 1024; // 16MB — DataChannel send buffer threshold +const TRANSFER_TIMEOUT_MS = 120_000; // 2min inactivity timeout + +// ============================================================ +// Transfer state — keyed by transferId (BigInt) +// ============================================================ +/** @type {Map} */ +const pendingOffers = new Map(); + +/** @type {Map} */ +const incomingFiles = new Map(); + +/** @type {Map} */ +const outgoingFiles = new Map(); + +// ============================================================ +// Connection + messaging setup +// ============================================================ + +window.doConnect = async function doConnect() { + const signalingUrl = document.getElementById('signalingUrl').value.trim(); + if (!signalingUrl) return; + + updateStatus('Connecting...'); + connectBtn.disabled = true; + + try { + p2p = await ZigP2P.load('./zig-p2p.wasm', { + signalingUrl, + rtcConfig: { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }, + }); + + peerIdSpan.textContent = p2p.peerId; + updateStatus('Connected'); + disconnectBtn.disabled = false; + peerBtn.disabled = false; + sendBtn.disabled = false; + + p2p.onMessage((peerId, appId, data) => { + if (appId === APP_ID_CHAT) { + const text = new TextDecoder().decode(data); + log(`Received (app=0x${appId.toString(16)}): ${text}`, 'recv'); + } else if (appId === APP_ID_FILE_OFFER) { + handleFileOffer(peerId, data); + } else if (appId === APP_ID_FILE_ACCEPT) { + handleFileAccept(peerId, data); + } else if (appId === APP_ID_FILE_RESUME) { + handleFileResume(data); + } else { + const text = new TextDecoder().decode(data); + log(`Received (app=0x${appId.toString(16)}): ${text}`, 'recv'); + } + }); + + // Direct message handler — file chunks bypass WASM entirely + p2p.onDirectMessage((channelId, appId, payload) => { + if (appId === APP_ID_FILE_CHUNK) { + handleFileChunkDirect(channelId, payload); + } else if (appId === APP_ID_FILE_COMPLETE) { + handleFileCompleteDirect(channelId, payload); + } else if (appId === APP_ID_FILE_CANCEL) { + handleFileCancelDirect(channelId, payload); + } else if (appId === APP_ID_FILE_PAUSE) { + handleFilePauseDirect(channelId, payload); + } + }); + + p2p.onConnection((peerId, channelId) => { + log(`Peer connected (channel ${channelId})`, 'info'); + updateChannels(); + }); + + p2p.onFileEvent((event) => { + const fileStatus = document.getElementById('fileStatus'); + switch (event.type) { + case 'shared': + log(`File registered in WASM: ${event.path} (session ${event.sessionId})`, 'info'); + break; + case 'download_started': + log(`Download started: ${event.name}`, 'info'); + fileStatus.textContent = `Downloading: ${event.name}`; + break; + case 'download_completed': + log(`Download completed`, 'recv'); + fileStatus.textContent = `Download complete!`; + break; + case 'download_failed': + log(`Download failed`, 'error'); + fileStatus.textContent = `Download failed`; + break; + } + }); + + // Timeout checker + setInterval(checkTransferTimeouts, 5000); + + document.getElementById('shareBtn').disabled = false; + log(`Initialized. Peer ID: ${p2p.peerId}, WASM version: ${p2p.version}`, 'info'); + } catch (err) { + console.error('Connection failed:', err); + log(`Connection failed: ${err?.message ?? err}`, 'error'); + updateStatus('Failed'); + connectBtn.disabled = false; + } +}; + +window.doDisconnect = function doDisconnect() { + if (p2p) { + p2p.destroy(); + p2p = null; + } + channelPeerIds.clear(); + pendingOffers.clear(); + incomingFiles.clear(); + outgoingFiles.clear(); + updateStatus('Disconnected'); + peerIdSpan.textContent = '\u2014'; + channelsSpan.textContent = '0'; + connectBtn.disabled = false; + disconnectBtn.disabled = true; + peerBtn.disabled = true; + sendBtn.disabled = true; + document.getElementById('shareBtn').disabled = true; + log('Disconnected', 'info'); +}; + +window.doConnectPeer = async function doConnectPeer() { + const remotePeerId = document.getElementById('remotePeerId').value.trim(); + if (!remotePeerId || !p2p) return; + + try { + log(`Connecting to peer: ${remotePeerId}...`, 'info'); + const channelId = await p2p.connectToPeer(remotePeerId); + log(`WebRTC channel ${channelId} opened to ${remotePeerId}`, 'info'); + + // Get the 32-byte P2P PeerId for this channel from WASM + const peerIdBytes = p2p.getPeerIdForChannel(channelId); + if (peerIdBytes) { + channelPeerIds.set(channelId, peerIdBytes); + log(`P2P PeerId: ${Array.from(peerIdBytes.slice(0, 8)).map(b => b.toString(16).padStart(2, '0')).join('')}...`, 'info'); + } + updateChannels(); + } catch (err) { + log(`Peer connection failed: ${err.message}`, 'error'); + } +}; + +window.doSend = function doSend() { + const input = document.getElementById('msgInput'); + const text = input.value.trim(); + if (!text || !p2p) return; + + const data = new TextEncoder().encode(text); + let sent = false; + + // Send to all connected peers + for (const [, peerId] of channelPeerIds) { + if (p2p.send(peerId, APP_ID_CHAT, data)) { + sent = true; + } + } + + if (sent) { + log(`Sent: ${text}`, 'sent'); + } else { + log(`Send failed (no connected peers?)`, 'error'); + } + input.value = ''; +}; + +// ============================================================ +// Helpers +// ============================================================ + +/** Generate a random 64-bit transfer ID as BigInt */ +function generateTransferId() { + const bytes = crypto.getRandomValues(new Uint8Array(8)); + return new DataView(bytes.buffer).getBigUint64(0, true); +} + +/** Read a u64 LE from a DataView */ +function readU64LE(view, offset) { + const lo = view.getUint32(offset, true); + const hi = view.getUint32(offset + 4, true); + return BigInt(lo) + BigInt(hi) * 0x100000000n; +} + +/** Write a u64 LE into a Uint8Array at offset */ +function writeU64LE(arr, offset, val) { + const view = new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + view.setUint32(offset, Number(val & 0xFFFFFFFFn), true); + view.setUint32(offset + 4, Number((val >> 32n) & 0xFFFFFFFFn), true); +} + +/** Sanitize a filename — remove path separators, control chars */ +function sanitizeFilename(name) { + // Strip path separators and traversal + let sanitized = name.replace(/[/\\]/g, '_').replace(/\.\./g, '_'); + // Remove control characters + sanitized = sanitized.replace(/[\x00-\x1f\x7f]/g, ''); + // Ensure non-empty + return sanitized || 'unnamed_file'; +} + +/** + * Find the WebRTC channel ID for a given 32-byte P2P PeerId. + * @param {Uint8Array} peerId - 32-byte peer ID + * @returns {number | null} channel ID, or null if not found + */ +function channelIdForPeer(peerId) { + for (const [chId, pid] of channelPeerIds) { + if (pid.length === peerId.length && pid.every((b, i) => b === peerId[i])) { + return chId; + } + } + return null; +} + +// ============================================================ +// File Transfer — v1 Protocol +// ============================================================ + +window.doShareFile = async function doShareFile() { + const fileInput = document.getElementById('fileInput'); + const file = fileInput.files?.[0]; + if (!file || !p2p) return; + + try { + log(`Sharing file: ${file.name} (${formatSize(file.size)})...`, 'info'); + + // Register file (lazy for large files, materialized+hashed for small) + const { virtualPath, size } = await p2p.shareFile(file); + log(`File registered: ${virtualPath}`, 'sent'); + + // Compute SHA-256 of the file + const fileHash = await computeFileHash(file); + + // Send v1 file offer to each connected peer with a unique transfer ID + const nameBytes = new TextEncoder().encode(file.name); + let peerCount = 0; + + for (const [channelId, peerId] of channelPeerIds) { + const transferId = generateTransferId(); + const peerLabel = Array.from(peerId.slice(0, 4)).map(b => b.toString(16).padStart(2, '0')).join(''); + + // v1 offer: [ver:1][xfer_id:8LE][name_len:2LE][name:N][size:8LE][sha256:32] + const offer = new Uint8Array(1 + 8 + 2 + nameBytes.length + 8 + 32); + const offerView = new DataView(offer.buffer); + let pos = 0; + + offer[pos] = PROTOCOL_VERSION; + pos += 1; + writeU64LE(offer, pos, transferId); + pos += 8; + offerView.setUint16(pos, nameBytes.length, true); + pos += 2; + offer.set(nameBytes, pos); + pos += nameBytes.length; + writeU64LE(offer, pos, BigInt(size)); + pos += 8; + offer.set(new Uint8Array(fileHash), pos); + + outgoingFiles.set(transferId, { + name: file.name, + file, + channelId, + transferId, + offset: 0, + paused: false, + peerLabel, + startTime: performance.now(), + lastActivity: performance.now(), + }); + p2p.send(peerId, APP_ID_FILE_OFFER, offer); + updateTransferUI(transferId); + peerCount++; + } + log(`File offer sent to ${peerCount} peer(s)`, 'info'); + } catch (err) { + log(`File share failed: ${err.message}`, 'error'); + } +}; + +/** Compute SHA-256 hash of a File object */ +async function computeFileHash(file) { + // For files under 100MB, hash in one shot + if (file.size < 100 * 1024 * 1024) { + const buffer = await file.arrayBuffer(); + return crypto.subtle.digest('SHA-256', buffer); + } + // For larger files, stream the hash + const HASH_CHUNK = 4 * 1024 * 1024; // 4MB chunks + let offset = 0; + // Use a manual streaming approach since SubtleCrypto doesn't support streaming + // Fall back to single-shot for now (browser memory permits ~2GB) + const buffer = await file.arrayBuffer(); + return crypto.subtle.digest('SHA-256', buffer); +} + +/** + * Handle incoming file offer (v1 or legacy). + */ +function handleFileOffer(peerId, data) { + if (data.length < 1) return; + const version = data[0]; + + let transferId, name, size, hash; + + if (version === PROTOCOL_VERSION) { + // v1: [ver:1][xfer_id:8LE][name_len:2LE][name:N][size:8LE][sha256:32] + if (data.length < 1 + 8 + 2) return; + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + let pos = 1; + transferId = readU64LE(view, pos); + pos += 8; + const nameLen = view.getUint16(pos, true); + pos += 2; + if (data.length < pos + nameLen + 8 + 32) return; + name = new TextDecoder().decode(data.slice(pos, pos + nameLen)); + pos += nameLen; + size = Number(readU64LE(view, pos)); + pos += 8; + hash = data.slice(pos, pos + 32); + } else { + // Legacy: [name_len:2LE][name:N][size:8LE] + if (data.length < 10) return; + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + const nameLen = view.getUint16(0, true); + if (data.length < 2 + nameLen + 8) return; + name = new TextDecoder().decode(data.slice(2, 2 + nameLen)); + const sizeLo = view.getUint32(2 + nameLen, true); + const sizeHi = view.getUint32(2 + nameLen + 4, true); + size = sizeLo + sizeHi * 0x100000000; + transferId = generateTransferId(); + } + + // Sanitize filename for display + const safeName = sanitizeFilename(name); + + pendingOffers.set(transferId, { + size, + peerId: new Uint8Array(peerId), + hash: hash ? new Uint8Array(hash) : undefined, + transferId, + name: safeName, + rawName: name, + }); + log(`File offered: ${safeName} (${formatSize(size)}, xfer_id=${transferId.toString(16)})`, 'recv'); + + // Show in UI (XSS-safe: use textContent, not innerHTML) + showFileOffer(safeName, size, transferId); +} + +/** + * Show a file offer in the UI with Accept button (XSS-safe). + */ +function showFileOffer(name, size, transferId) { + const container = document.getElementById('fileOffers'); + const div = document.createElement('div'); + div.className = 'file-offer'; + div.id = `offer-${transferId}`; + + const nameEl = document.createElement('strong'); + nameEl.textContent = name; + div.appendChild(nameEl); + + const sizeEl = document.createTextNode(` (${formatSize(size)}) `); + div.appendChild(sizeEl); + + const btn = document.createElement('button'); + btn.textContent = 'Accept'; + btn.addEventListener('click', () => doAcceptFile(transferId)); + div.appendChild(btn); + + container.appendChild(div); +} + +/** + * Accept a file offer — send accept message to offering peer. + */ +window.doAcceptFile = function doAcceptFile(transferId) { + if (!p2p) return; + const offer = pendingOffers.get(transferId); + if (!offer) return; + + const peerLabel = Array.from(offer.peerId.slice(0, 4)).map(b => b.toString(16).padStart(2, '0')).join(''); + + // Prepare receiving buffer + incomingFiles.set(transferId, { + name: offer.name, + size: offer.size, + received: new Uint8Array(offer.size), + bytesReceived: 0, + startTime: performance.now(), + lastActivity: performance.now(), + senderDone: false, + hash: offer.hash, + transferId, + peerId: new Uint8Array(offer.peerId), + paused: false, + peerLabel, + }); + + // Send v1 accept: [xfer_id:8LE][name_len:2LE][name:N] + const nameBytes = new TextEncoder().encode(offer.rawName || offer.name); + const msg = new Uint8Array(8 + 2 + nameBytes.length); + writeU64LE(msg, 0, transferId); + new DataView(msg.buffer).setUint16(8, nameBytes.length, true); + msg.set(nameBytes, 10); + p2p.send(offer.peerId, APP_ID_FILE_ACCEPT, msg); + + log(`Accepted file: ${offer.name} (xfer_id=${transferId.toString(16)})`, 'sent'); + + // Remove offer UI and show transfer entry + const el = document.getElementById(`offer-${transferId}`); + if (el) el.remove(); + pendingOffers.delete(transferId); + updateTransferUI(transferId); +}; + +/** + * Handle file accept — start sending chunks via direct DataChannel path. + */ +function handleFileAccept(peerId, data) { + let transferId, name; + + if (data.length >= 10) { + // v1: [xfer_id:8LE][name_len:2LE][name:N] + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + transferId = readU64LE(view, 0); + const nameLen = view.getUint16(8, true); + if (data.length >= 10 + nameLen) { + name = new TextDecoder().decode(data.slice(10, 10 + nameLen)); + } + } else if (data.length >= 2) { + // Legacy: [name_len:2LE][name:N] + const nameLen = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, true); + if (data.length >= 2 + nameLen) { + name = new TextDecoder().decode(data.slice(2, 2 + nameLen)); + } + } + + // Find matching outgoing transfer + let outgoing = null; + if (transferId !== undefined) { + outgoing = outgoingFiles.get(transferId); + } + if (!outgoing && name) { + for (const [id, entry] of outgoingFiles) { + if (entry.name === name) { + outgoing = entry; + transferId = id; + break; + } + } + } + if (!outgoing) { + log(`Accept for unknown transfer`, 'error'); + return; + } + + const chId = channelIdForPeer(peerId); + if (chId !== null) { + outgoing.channelId = chId; + } + if (chId === null && outgoing.channelId === undefined) { + log(`Cannot send ${outgoing.name}: no channel found for peer`, 'error'); + return; + } + + log(`Peer accepted file: ${outgoing.name}, starting transfer (xfer_id=${transferId.toString(16)})...`, 'info'); + sendFileChunks(outgoing.channelId, outgoing.name, transferId); +} + +/** + * Handle file resume — seek and continue sending. + */ +function handleFileResume(data) { + if (data.length < 16) return; + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + const transferId = readU64LE(view, 0); + const lastOffset = Number(readU64LE(view, 8)); + + const outgoing = outgoingFiles.get(transferId); + if (!outgoing) { + log(`Resume for unknown transfer: xfer_id=${transferId.toString(16)}`, 'error'); + return; + } + + outgoing.offset = lastOffset; + outgoing.lastActivity = performance.now(); + log(`Resuming transfer ${outgoing.name} from offset ${formatSize(lastOffset)}`, 'info'); + sendFileChunks(outgoing.channelId, outgoing.name, transferId); +} + +/** + * Send file data in chunks via direct DataChannel path (bypasses WASM). + * v1 chunk format: [0xFF][0x22][xfer_id:8LE][offset:8LE][data:N] + */ +async function sendFileChunks(channelId, name, transferId) { + if (!p2p) return; + const outgoing = outgoingFiles.get(transferId); + if (!outgoing) return; + + const fileSize = outgoing.file.size; + let offset = outgoing.offset || 0; + const fileStatus = document.getElementById('fileStatus'); + const startTime = outgoing.startTime; + + // Wire format: [0xFF][0x22][xfer_id:8LE][offset:8LE][data:N] + const DIRECT_PREFIX = 0xFF; + let msgBuf = new Uint8Array(2 + 8 + 8 + CHUNK_SIZE); + msgBuf[0] = DIRECT_PREFIX; + msgBuf[1] = APP_ID_FILE_CHUNK; + writeU64LE(msgBuf, 2, transferId); + + while (offset < fileSize) { + // Check if paused or deleted — exit cleanly (doResumeTransfer re-enters) + const current = outgoingFiles.get(transferId); + if (!current || current.paused) return; + + // Flow control + while (p2p.totalBufferedAmount > MAX_BUFFERED_AMOUNT) { + await new Promise(r => setTimeout(r, 1)); + const still = outgoingFiles.get(transferId); + if (!still || still.paused) return; + } + + const len = Math.min(CHUNK_SIZE, fileSize - offset); + const chunk = await p2p.fileHost.readFileChunk(name, offset, len); + + writeU64LE(msgBuf, 10, BigInt(offset)); + msgBuf.set(chunk, 18); + + p2p.sendDirect(channelId, msgBuf.subarray(0, 18 + chunk.length)); + + offset += chunk.length; + outgoing.offset = offset; + outgoing.lastActivity = performance.now(); + + // Update progress every 64 chunks + if ((offset / CHUNK_SIZE | 0) % 64 === 0 || offset >= fileSize) { + updateTransferUI(transferId); + await new Promise(r => setTimeout(r, 0)); + } + } + + // Send v1 complete: [0xFF][0x23][xfer_id:8LE][name_len:2LE][name:N] + const nameBytes = new TextEncoder().encode(name); + const completeBuf = new Uint8Array(2 + 8 + 2 + nameBytes.length); + completeBuf[0] = DIRECT_PREFIX; + completeBuf[1] = APP_ID_FILE_COMPLETE; + writeU64LE(completeBuf, 2, transferId); + new DataView(completeBuf.buffer).setUint16(10, nameBytes.length, true); + completeBuf.set(nameBytes, 12); + p2p.sendDirect(channelId, completeBuf); + + const elapsed = (performance.now() - startTime) / 1000; + const speed = formatSize(fileSize / elapsed); + log(`File sent: ${name} (${elapsed.toFixed(1)}s, ${speed}/s, xfer_id=${transferId.toString(16)})`, 'sent'); + outgoingFiles.delete(transferId); + completeTransferUI(transferId, 'Sent', null); +} + +/** + * Handle incoming file chunk via direct DataChannel path. + * v1 payload: [xfer_id:8LE][offset:8LE][data:N] + * Legacy payload: [offset:8LE][data:N] + */ +function handleFileChunkDirect(channelId, payload) { + if (payload.length < 16) return; + const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); + + // Try v1 format first: check if first 8 bytes match a known transfer ID + const maybeTransferId = readU64LE(view, 0); + const file = incomingFiles.get(maybeTransferId); + + if (file) { + // v1 format: [xfer_id:8LE][offset:8LE][data:N] + const offset = Number(readU64LE(view, 8)); + const chunk = payload.subarray(16); + + if (offset + chunk.length <= file.size) { + file.received.set(chunk, offset); + file.bytesReceived += chunk.length; + file.lastActivity = performance.now(); + updateReceiveProgress(file); + } + return; + } + + // Legacy format: [offset:8LE][data:N] + const offsetLo = view.getUint32(0, true); + const offsetHi = view.getUint32(4, true); + const offset = offsetLo + offsetHi * 0x100000000; + const chunk = payload.subarray(8); + + for (const [, f] of incomingFiles) { + if (offset + chunk.length <= f.size) { + f.received.set(chunk, offset); + f.bytesReceived += chunk.length; + f.lastActivity = performance.now(); + updateReceiveProgress(f); + return; + } + } +} + +function updateReceiveProgress(file) { + if ((file.bytesReceived & 0x3FFFFF) < CHUNK_SIZE || file.bytesReceived >= file.size) { + updateTransferUI(file.transferId); + } + + if (file.bytesReceived >= file.size) { + finalizeFileDownload(file.transferId); + } +} + +/** + * Handle file transfer complete via direct DataChannel path. + * v1 payload: [xfer_id:8LE][name_len:2LE][name:N] + */ +function handleFileCompleteDirect(channelId, payload) { + let transferId = null; + + if (payload.length >= 8) { + const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); + const maybeId = readU64LE(view, 0); + if (incomingFiles.has(maybeId)) { + transferId = maybeId; + } + } + + if (transferId !== null) { + const file = incomingFiles.get(transferId); + if (file) { + file.senderDone = true; + if (file.bytesReceived >= file.size) { + finalizeFileDownload(transferId); + } else { + log(`Sender finished ${file.name} but only ${formatSize(file.bytesReceived)}/${formatSize(file.size)} received \u2014 waiting`, 'info'); + } + } + return; + } + + // Legacy: find by name + if (payload.length >= 2) { + const nameLen = new DataView(payload.buffer, payload.byteOffset, payload.byteLength).getUint16(0, true); + if (payload.length >= 2 + nameLen) { + const name = new TextDecoder().decode(payload.subarray(2, 2 + nameLen)); + for (const [id, file] of incomingFiles) { + if (file.name === name) { + file.senderDone = true; + if (file.bytesReceived >= file.size) { + finalizeFileDownload(id); + } + return; + } + } + } + } +} + +/** + * Handle cancel message from peer. + * v1 payload: [xfer_id:8LE][name_len:2LE][name:N] + */ +function handleFileCancelDirect(channelId, payload) { + if (payload.length < 8) return; + const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); + const transferId = readU64LE(view, 0); + + if (incomingFiles.has(transferId)) { + const file = incomingFiles.get(transferId); + log(`Transfer cancelled by peer: ${file.name}`, 'error'); + incomingFiles.delete(transferId); + removeTransferUI(transferId); + } + if (outgoingFiles.has(transferId)) { + const file = outgoingFiles.get(transferId); + log(`Transfer cancelled by peer: ${file.name}`, 'error'); + outgoingFiles.delete(transferId); + removeTransferUI(transferId); + } +} + +/** + * Check for timed-out transfers and cancel them. + */ +function checkTransferTimeouts() { + const now = performance.now(); + + for (const [id, file] of incomingFiles) { + if (file.paused) continue; + if (now - file.lastActivity > TRANSFER_TIMEOUT_MS) { + log(`Transfer timeout: ${file.name} (idle ${Math.round((now - file.lastActivity) / 1000)}s)`, 'error'); + incomingFiles.delete(id); + removeTransferUI(id); + } + } + + for (const [id, file] of outgoingFiles) { + if (file.paused) continue; + if (now - file.lastActivity > TRANSFER_TIMEOUT_MS) { + log(`Send timeout: ${file.name} (idle ${Math.round((now - file.lastActivity) / 1000)}s)`, 'error'); + outgoingFiles.delete(id); + removeTransferUI(id); + } + } +} + +/** + * Finalize a completed file download: verify hash, log, offer download link, clean up. + */ +async function finalizeFileDownload(transferId) { + const file = incomingFiles.get(transferId); + if (!file) return; + if (file.finalizing) return; // Guard against double call (async race) + file.finalizing = true; + + const elapsed = (performance.now() - file.startTime) / 1000; + const speed = elapsed > 0 ? formatSize(file.bytesReceived / elapsed) : '\u2014'; + + // SHA-256 verification + let hashStatus = ''; + if (file.hash && file.hash.length === 32) { + try { + const computed = await crypto.subtle.digest('SHA-256', file.received); + const computedBytes = new Uint8Array(computed); + const match = computedBytes.every((b, i) => b === file.hash[i]); + hashStatus = match ? ' \u2014 SHA-256 OK' : ' \u2014 SHA-256 MISMATCH!'; + if (!match) { + log(`INTEGRITY ERROR: ${file.name} \u2014 SHA-256 mismatch!`, 'error'); + } + } catch { + hashStatus = ' \u2014 SHA-256 check failed'; + } + } + + log(`File received: ${file.name} (${formatSize(file.bytesReceived)}, ${elapsed.toFixed(1)}s, ${speed}/s)${hashStatus}`, 'recv'); + + // Create download blob + const blob = new Blob([file.received]); + const url = URL.createObjectURL(blob); + + const fileName = sanitizeFilename(file.name); + const fileSize = file.size; + incomingFiles.delete(transferId); + completeTransferUI(transferId, hashStatus, url, fileName, fileSize); +} + +// ============================================================ +// Pause — handle incoming pause from desktop +// ============================================================ + +/** + * Handle pause message from peer (direct path). + * Payload: [xfer_id:8LE] + */ +function handleFilePauseDirect(channelId, payload) { + if (payload.length < 8) return; + const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); + const transferId = readU64LE(view, 0); + + const outgoing = outgoingFiles.get(transferId); + if (outgoing) { + outgoing.paused = true; + log(`Transfer paused by peer: ${outgoing.name}`, 'info'); + updateTransferUI(transferId); + return; + } + + const incoming = incomingFiles.get(transferId); + if (incoming) { + incoming.paused = true; + log(`Transfer paused by sender: ${incoming.name}`, 'info'); + updateTransferUI(transferId); + } +} + +// ============================================================ +// Pause / Resume / Cancel controls (browser-initiated) +// ============================================================ + +/** + * Pause a transfer. For incoming: sends pause message to sender. + * For outgoing: pauses locally (async loop exits). + */ +window.doPauseTransfer = function doPauseTransfer(transferId) { + const incoming = incomingFiles.get(transferId); + if (incoming && !incoming.paused) { + incoming.paused = true; + // Send pause to sender: [0xFF][0x26][xfer_id:8LE] + const msg = new Uint8Array(2 + 8); + msg[0] = 0xFF; + msg[1] = APP_ID_FILE_PAUSE; + writeU64LE(msg, 2, transferId); + if (incoming.peerId && p2p) { + const chId = channelIdForPeer(incoming.peerId); + if (chId !== null) { + const ok = p2p.sendDirect(chId, msg); + log(`Sent pause to peer (ch=${chId}, ok=${ok})`, 'info'); + } else { + log(`Pause failed: no channel for peer`, 'error'); + } + } else { + log(`Pause failed: no peerId or p2p`, 'error'); + } + log(`Paused receiving: ${incoming.name}`, 'info'); + updateTransferUI(transferId); + return; + } + + const outgoing = outgoingFiles.get(transferId); + if (outgoing && !outgoing.paused) { + outgoing.paused = true; + log(`Paused sending: ${outgoing.name}`, 'info'); + updateTransferUI(transferId); + } +}; + +/** + * Resume a transfer. For incoming: sends resume message to sender. + * For outgoing: clears paused flag and re-enters sendFileChunks. + */ +window.doResumeTransfer = function doResumeTransfer(transferId) { + const incoming = incomingFiles.get(transferId); + if (incoming && incoming.paused) { + incoming.paused = false; + incoming.lastActivity = performance.now(); + // Send resume to sender: [xfer_id:8LE][last_offset:8LE] + if (incoming.peerId && p2p) { + const msg = new Uint8Array(16); + writeU64LE(msg, 0, transferId); + writeU64LE(msg, 8, BigInt(incoming.bytesReceived)); + p2p.send(incoming.peerId, APP_ID_FILE_RESUME, msg); + } + log(`Resumed receiving: ${incoming.name}`, 'info'); + updateTransferUI(transferId); + return; + } + + const outgoing = outgoingFiles.get(transferId); + if (outgoing && outgoing.paused) { + outgoing.paused = false; + outgoing.lastActivity = performance.now(); + log(`Resumed sending: ${outgoing.name}`, 'info'); + updateTransferUI(transferId); + sendFileChunks(outgoing.channelId, outgoing.name, transferId); + } +}; + +/** + * Cancel a transfer. Sends cancel to peer and removes from maps + UI. + */ +window.doCancelTransfer = function doCancelTransfer(transferId) { + const incoming = incomingFiles.get(transferId); + if (incoming) { + // Send cancel to sender + if (incoming.peerId && p2p) { + const chId = channelIdForPeer(incoming.peerId); + if (chId !== null) { + const nameBytes = new TextEncoder().encode(incoming.name); + const msg = new Uint8Array(2 + 8 + 2 + nameBytes.length); + msg[0] = 0xFF; + msg[1] = APP_ID_FILE_CANCEL; + writeU64LE(msg, 2, transferId); + new DataView(msg.buffer).setUint16(10, nameBytes.length, true); + msg.set(nameBytes, 12); + p2p.sendDirect(chId, msg); + } + } + log(`Cancelled receiving: ${incoming.name}`, 'info'); + incomingFiles.delete(transferId); + removeTransferUI(transferId); + return; + } + + const outgoing = outgoingFiles.get(transferId); + if (outgoing) { + // Send cancel to receiver + if (p2p) { + const nameBytes = new TextEncoder().encode(outgoing.name); + const msg = new Uint8Array(2 + 8 + 2 + nameBytes.length); + msg[0] = 0xFF; + msg[1] = APP_ID_FILE_CANCEL; + writeU64LE(msg, 2, transferId); + new DataView(msg.buffer).setUint16(10, nameBytes.length, true); + msg.set(nameBytes, 12); + p2p.sendDirect(outgoing.channelId, msg); + } + log(`Cancelled sending: ${outgoing.name}`, 'info'); + outgoingFiles.delete(transferId); + removeTransferUI(transferId); + } +}; + +// ============================================================ +// Transfer List UI +// ============================================================ + +/** + * Create or update a transfer entry in the #transferList. + * Shows direction, peer label, file name, progress bar, speed, and controls. + */ +function updateTransferUI(transferId) { + const incoming = incomingFiles.get(transferId); + const outgoing = outgoingFiles.get(transferId); + const entry = incoming || outgoing; + if (!entry) return; + + const isIncoming = !!incoming; + const container = document.getElementById('transferList'); + const elId = `transfer-${transferId}`; + let div = document.getElementById(elId); + + const paused = entry.paused; + const name = entry.name || 'unknown'; + const peerLabel = entry.peerLabel || '????'; + const direction = isIncoming ? '\u2193 Receiving from' : '\u2191 Sending to'; + const size = entry.size || (entry.file ? entry.file.size : 0); + const progress = isIncoming ? entry.bytesReceived : (entry.offset || 0); + const pct = size > 0 ? Math.round((progress / size) * 100) : 0; + const elapsed = (performance.now() - entry.startTime) / 1000; + const speed = (!paused && elapsed > 0) ? formatSize(progress / elapsed) + '/s' : 'paused'; + + // First render: build the full DOM structure with stable sub-elements + if (!div) { + div = document.createElement('div'); + div.className = 'transfer-entry'; + div.id = elId; + + // Header row + const header = document.createElement('div'); + header.className = 'te-header'; + const label = document.createElement('span'); + label.className = 'te-label'; + header.appendChild(label); + const status = document.createElement('span'); + status.className = 'te-status'; + header.appendChild(status); + div.appendChild(header); + + // Info line + const info = document.createElement('div'); + info.className = 'te-info'; + div.appendChild(info); + + // Progress bar + const bar = document.createElement('div'); + bar.className = 'progress-bar'; + const fill = document.createElement('div'); + fill.className = 'progress-fill'; + bar.appendChild(fill); + div.appendChild(bar); + + // Controls — built once, buttons swapped only when paused state changes + const controls = document.createElement('div'); + controls.className = 'transfer-controls'; + + const pauseBtn = document.createElement('button'); + pauseBtn.textContent = 'Pause'; + pauseBtn.className = 'pause-btn'; + pauseBtn.addEventListener('click', () => doPauseTransfer(transferId)); + controls.appendChild(pauseBtn); + + const resumeBtn = document.createElement('button'); + resumeBtn.textContent = 'Resume'; + resumeBtn.className = 'resume-btn'; + resumeBtn.style.display = 'none'; + resumeBtn.addEventListener('click', () => doResumeTransfer(transferId)); + controls.appendChild(resumeBtn); + + const cancelBtn = document.createElement('button'); + cancelBtn.textContent = 'Cancel'; + cancelBtn.className = 'cancel-btn'; + cancelBtn.addEventListener('click', () => doCancelTransfer(transferId)); + controls.appendChild(cancelBtn); + + div.appendChild(controls); + container.appendChild(div); + } + + // Update in place — no DOM destruction, buttons stay clickable + div.querySelector('.te-label').textContent = `${direction} ${peerLabel}: ${name}`; + div.querySelector('.te-status').textContent = paused ? 'PAUSED' : ''; + div.querySelector('.te-info').textContent = `${formatSize(progress)} / ${formatSize(size)} (${pct}%) \u2014 ${speed}`; + const fill = div.querySelector('.progress-fill'); + fill.style.width = `${pct}%`; + fill.className = 'progress-fill' + (paused ? ' paused' : ''); + + // Toggle pause/resume button visibility (no destroy/recreate) + const pauseBtn = div.querySelector('.pause-btn'); + const resumeBtn = div.querySelector('.resume-btn'); + if (pauseBtn) pauseBtn.style.display = paused ? 'none' : ''; + if (resumeBtn) resumeBtn.style.display = paused ? '' : 'none'; +} + +/** + * Remove a transfer entry from the #transferList. + */ +function removeTransferUI(transferId) { + const el = document.getElementById(`transfer-${transferId}`); + if (el) el.remove(); +} + +/** + * Replace a transfer entry with a completed state (download link or sent status). + */ +function completeTransferUI(transferId, hashStatus, blobUrl, fileName, fileSize) { + const container = document.getElementById('transferList'); + const elId = `transfer-${transferId}`; + let div = document.getElementById(elId); + + if (!div) { + div = document.createElement('div'); + div.id = elId; + container.appendChild(div); + } + + div.className = 'transfer-entry completed'; + div.innerHTML = ''; + + if (blobUrl) { + // Completed receive — show download link + const check = document.createTextNode('\u2713 Received: '); + div.appendChild(check); + + const link = document.createElement('a'); + link.href = blobUrl; + link.download = fileName || 'download'; + link.textContent = fileName || 'Download'; + div.appendChild(link); + + const sizeText = document.createTextNode( + ` (${formatSize(fileSize || 0)})${hashStatus || ''}` + ); + div.appendChild(sizeText); + } else { + // Completed send + const check = document.createTextNode(`\u2713 ${hashStatus || 'Transfer complete'}`); + div.appendChild(check); + } +} + +function formatSize(bytes) { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`; +} diff --git a/browser/demo/index.html b/browser/demo/index.html new file mode 100644 index 0000000..8c1f6b9 --- /dev/null +++ b/browser/demo/index.html @@ -0,0 +1,86 @@ + + + + + + zig-p2p Browser Demo + + + +

zig-p2p Browser Demo

+ +
+ Status: Not connected | + Peer ID: — | + Channels: 0 +
+ +
+ + + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ + + +
+
+
+
+ +
+ +
+ + +
+ + + + diff --git a/browser/demo/zig-p2p.wasm b/browser/demo/zig-p2p.wasm new file mode 120000 index 0000000..56298ed --- /dev/null +++ b/browser/demo/zig-p2p.wasm @@ -0,0 +1 @@ +/Users/mdt./Projects/zig-p2p/zig-out/bin/zig-p2p.wasm \ No newline at end of file diff --git a/browser/host/file-host.js b/browser/host/file-host.js new file mode 100644 index 0000000..88153ba --- /dev/null +++ b/browser/host/file-host.js @@ -0,0 +1,331 @@ +/** + * File Host — provides extern "env" file I/O functions for WASM. + * + * Maps to `extern "env" fn js_file_*` declarations in + * src/files/filesystem.zig (WASM backend). + * + * Storage model: + * - Upload files: registered as browser File objects (lazy, no upfront copy) + * - Small files / WASM-created files: stored as Uint8Array in memory + * - Download files: accumulated in memory, retrieved via getFileBlob() + * - All files identified by virtual paths (string keys) + * + * For large uploads, the File object is kept as-is and sliced on demand. + * WASM extern "env" reads (js_file_read) work from in-memory data only, + * so files must be materialized before WASM can access them. For the + * JS-level transfer, we stream directly from the File object. + */ + +export class FileHost { + /** @type {Map} */ + #files = new Map(); + /** @type {number} */ + #nextId = 1; + /** @type {Map} virtual path -> materialized file data */ + #registered = new Map(); + /** @type {Map} virtual path -> browser File object (lazy, not loaded) */ + #browserFiles = new Map(); + /** @type {Set} virtual directory paths */ + #directories = new Set(); + /** @type {() => WebAssembly.Memory} */ + #getMemory; + + /** + * @param {() => WebAssembly.Memory} getMemory - Returns the WASM memory instance + */ + constructor(getMemory) { + this.#getMemory = getMemory; + } + + /** + * Register in-memory data for virtual file access (small files, WASM downloads). + * @param {string} virtualPath + * @param {Uint8Array} data + */ + registerFile(virtualPath, data) { + this.#registered.set(virtualPath, data); + } + + /** + * Register a browser File object for streaming access. + * Does NOT read the file into memory — stores the File handle for + * on-demand slice reads via readFileChunk(). + * @param {File} file + * @returns {string} virtual path + */ + registerBrowserFile(file) { + const virtualPath = file.name; + this.#browserFiles.set(virtualPath, file); + return virtualPath; + } + + /** + * Materialize a browser File into memory so WASM extern "env" can access it. + * Only needed if WASM-side code needs to read the file (hashing, etc.). + * For JS-level transfers, use readFileChunk() instead. + * @param {string} virtualPath + * @param {(loaded: number, total: number) => void} [onProgress] + * @returns {Promise} + */ + async materializeFile(virtualPath, onProgress) { + const file = this.#browserFiles.get(virtualPath); + if (!file) return; + if (this.#registered.has(virtualPath)) return; // already materialized + + const total = file.size; + const data = new Uint8Array(total); + const chunkSize = 4 * 1024 * 1024; // 4MB chunks + let offset = 0; + + while (offset < total) { + const end = Math.min(offset + chunkSize, total); + const slice = file.slice(offset, end); + const buf = await slice.arrayBuffer(); + data.set(new Uint8Array(buf), offset); + offset = end; + if (onProgress) onProgress(offset, total); + } + + this.#registered.set(virtualPath, data); + } + + /** + * Read a chunk from a browser File without loading the whole file. + * Returns a Uint8Array of the requested range. + * @param {string} virtualPath + * @param {number} offset + * @param {number} length + * @returns {Promise} + */ + async readFileChunk(virtualPath, offset, length) { + // Prefer in-memory data if available + const data = this.#registered.get(virtualPath); + if (data) { + const end = Math.min(offset + length, data.length); + return data.subarray(offset, end); + } + + // Stream from File object + const file = this.#browserFiles.get(virtualPath); + if (!file) throw new Error(`File not found: ${virtualPath}`); + const end = Math.min(offset + length, file.size); + const slice = file.slice(offset, end); + const buf = await slice.arrayBuffer(); + return new Uint8Array(buf); + } + + /** + * Get file size without loading into memory. + * @param {string} virtualPath + * @returns {number | null} + */ + getFileSize(virtualPath) { + const data = this.#registered.get(virtualPath); + if (data) return data.length; + const file = this.#browserFiles.get(virtualPath); + if (file) return file.size; + return null; + } + + /** + * Get a completed download as a Blob. + * @param {string} virtualPath + * @returns {Blob | null} + */ + getFileBlob(virtualPath) { + const data = this.#registered.get(virtualPath); + if (data) return new Blob([data]); + const file = this.#browserFiles.get(virtualPath); + if (file) return file; // File is already a Blob + return null; + } + + /** + * Check if a file is registered (either in-memory or as File handle). + * @param {string} virtualPath + * @returns {boolean} + */ + hasFile(virtualPath) { + return this.#registered.has(virtualPath) || this.#browserFiles.has(virtualPath); + } + + /** + * Get all registered file paths. + * @returns {string[]} + */ + listFiles() { + return [...new Set([...this.#registered.keys(), ...this.#browserFiles.keys()])]; + } + + // ============================================================ + // extern "env" implementations (work with in-memory data only) + // ============================================================ + + #readString(ptr, len) { + const bytes = new Uint8Array(this.#getMemory().buffer, ptr, len); + return new TextDecoder().decode(bytes); + } + + /** + * Open an existing file. Returns file_id >= 0 or -1 on error. + * Only works with materialized (in-memory) files. + */ + js_file_open(pathPtr, pathLen, readOnly) { + const path = this.#readString(pathPtr, pathLen); + const data = this.#registered.get(path); + if (!data) return -1; + + const fileId = this.#nextId++; + this.#files.set(fileId, { + data: readOnly ? data : new Uint8Array(data), // copy for writable + pos: 0, + name: path, + readOnly: readOnly === 1, + }); + return fileId; + } + + /** + * Create a new file. Returns file_id >= 0 or -1 on error. + */ + js_file_create(pathPtr, pathLen) { + const path = this.#readString(pathPtr, pathLen); + + const fileId = this.#nextId++; + const data = new Uint8Array(0); + this.#registered.set(path, data); + this.#files.set(fileId, { + data, + pos: 0, + name: path, + readOnly: false, + }); + return fileId; + } + + /** + * Read from file at offset. Returns bytes read or -1 on error. + */ + js_file_read(fileId, bufPtr, bufLen, offset) { + const file = this.#files.get(fileId); + if (!file) return -1; + + // Use BigInt-safe conversion (offset comes as i64 from WASM) + const off = Number(offset); + const available = Math.max(0, file.data.length - off); + const toRead = Math.min(bufLen, available); + if (toRead <= 0) return 0; + + const dest = new Uint8Array(this.#getMemory().buffer, bufPtr, toRead); + dest.set(file.data.subarray(off, off + toRead)); + return toRead; + } + + /** + * Write to file at offset. Returns bytes written or -1 on error. + */ + js_file_write(fileId, dataPtr, dataLen, offset) { + const file = this.#files.get(fileId); + if (!file || file.readOnly) return -1; + + const off = Number(offset); + const src = new Uint8Array(this.#getMemory().buffer, dataPtr, dataLen); + + // Grow file if needed + const needed = off + dataLen; + if (needed > file.data.length) { + const newData = new Uint8Array(needed); + newData.set(file.data); + file.data = newData; + // Update registered copy + this.#registered.set(file.name, file.data); + } + + file.data.set(src, off); + return dataLen; + } + + /** + * Get file size. Returns size >= 0 or -1 on error. + */ + js_file_get_size(fileId) { + const file = this.#files.get(fileId); + if (!file) return -1n; // BigInt for i64 return + return BigInt(file.data.length); + } + + /** + * Close a file handle. + */ + js_file_close(fileId) { + this.#files.delete(fileId); + } + + /** + * Check if a file exists. Returns 1 if exists, 0 if not. + */ + js_file_exists(pathPtr, pathLen) { + const path = this.#readString(pathPtr, pathLen); + return this.#registered.has(path) || this.#browserFiles.has(path) || this.#directories.has(path) ? 1 : 0; + } + + /** + * Delete a file. Returns 1 on success, 0 on failure. + */ + js_file_delete(pathPtr, pathLen) { + const path = this.#readString(pathPtr, pathLen); + const a = this.#registered.delete(path); + const b = this.#browserFiles.delete(path); + return (a || b) ? 1 : 0; + } + + /** + * Rename a file. Returns 1 on success, 0 on failure. + */ + js_file_rename(oldPtr, oldLen, newPtr, newLen) { + const oldPath = this.#readString(oldPtr, oldLen); + const newPath = this.#readString(newPtr, newLen); + const data = this.#registered.get(oldPath); + if (data) { + this.#registered.delete(oldPath); + this.#registered.set(newPath, data); + return 1; + } + const file = this.#browserFiles.get(oldPath); + if (file) { + this.#browserFiles.delete(oldPath); + this.#browserFiles.set(newPath, file); + return 1; + } + return 0; + } + + /** + * Create a directory (no-op in memory model, just track it). + * Returns 1 on success. + */ + js_file_mkdir(pathPtr, pathLen) { + const path = this.#readString(pathPtr, pathLen); + this.#directories.add(path); + return 1; + } + + /** + * Get the env bindings to merge into the WASM import object. + * @returns {Record} + */ + getEnvBindings() { + return { + js_file_open: (p, l, r) => this.js_file_open(p, l, r), + js_file_create: (p, l) => this.js_file_create(p, l), + js_file_read: (f, b, l, o) => this.js_file_read(f, b, l, o), + js_file_write: (f, d, l, o) => this.js_file_write(f, d, l, o), + js_file_get_size: (f) => this.js_file_get_size(f), + js_file_close: (f) => this.js_file_close(f), + js_file_exists: (p, l) => this.js_file_exists(p, l), + js_file_delete: (p, l) => this.js_file_delete(p, l), + js_file_rename: (op, ol, np, nl) => this.js_file_rename(op, ol, np, nl), + js_file_mkdir: (p, l) => this.js_file_mkdir(p, l), + }; + } +} diff --git a/browser/host/package.json b/browser/host/package.json new file mode 100644 index 0000000..f42b2d0 --- /dev/null +++ b/browser/host/package.json @@ -0,0 +1,16 @@ +{ + "name": "@zig-p2p/browser-host", + "version": "0.1.0", + "description": "Browser host for zig-p2p WASM module", + "type": "module", + "main": "zig-p2p.js", + "exports": { + ".": "./zig-p2p.js" + }, + "files": [ + "zig-p2p.js", + "platform-env.js", + "webrtc-host.js", + "signaling.js" + ] +} diff --git a/browser/host/platform-env.js b/browser/host/platform-env.js new file mode 100644 index 0000000..bfcb904 --- /dev/null +++ b/browser/host/platform-env.js @@ -0,0 +1,66 @@ +/** + * Platform environment — provides extern "env" functions for the WASM module. + * + * These map directly to the `extern "env" fn js_*` declarations in the Zig + * platform abstraction layer (src/platform/time.zig, random.zig, etc.). + */ + +/** + * Create the env import object for WASM instantiation. + * @param {() => WebAssembly.Memory} getMemory - Returns the WASM memory instance + * @returns {Record} env imports + */ +export function createPlatformEnv(getMemory) { + return { + // -- Time (src/platform/time.zig) -- + + /** @returns {bigint} milliseconds since epoch */ + js_timestamp_ms() { + return BigInt(Date.now()); + }, + + /** @returns {bigint} nanoseconds since epoch (ms precision in browser) */ + js_timestamp_ns() { + return BigInt(Date.now()) * 1_000_000n; + }, + + // -- Random (src/platform/random.zig) -- + + /** Fill buffer with cryptographically secure random bytes */ + js_random_bytes(ptr, len) { + const bytes = new Uint8Array(getMemory().buffer, ptr, len); + crypto.getRandomValues(bytes); + }, + + // -- Logging (src/wasm/main.zig) -- + + /** Log a message from WASM to the browser console */ + js_log(ptr, len) { + const bytes = new Uint8Array(getMemory().buffer, ptr, len); + const msg = new TextDecoder().decode(bytes); + console.log('[zig-p2p]', msg); + }, + + // -- WebRTC DataChannel (src/platform/webrtc_wasm.zig) -- + // These are called by the WASM transport when sending data. + // They are wired to the WebRTCHost by zig-p2p.js during initialization. + + /** Send data on a DataChannel. Returns 0 on success, -1 on error. */ + js_datachannel_send(channelId, dataPtr, dataLen) { + // Overridden by zig-p2p.js to route to WebRTCHost + console.warn('[zig-p2p] js_datachannel_send called before WebRTCHost wired'); + return -1; + }, + + /** Close a DataChannel */ + js_datachannel_close(channelId) { + // Overridden by zig-p2p.js to route to WebRTCHost + }, + + /** Get buffered amount for a DataChannel */ + js_datachannel_buffered_amount(channelId) { + // Overridden by zig-p2p.js to route to WebRTCHost + return 0; + }, + }; +} diff --git a/browser/host/signaling.js b/browser/host/signaling.js new file mode 100644 index 0000000..6f0acbb --- /dev/null +++ b/browser/host/signaling.js @@ -0,0 +1,137 @@ +/** + * WebSocket signaling client for WebRTC SDP/ICE exchange. + * + * Connects to the signaling server and relays offers, answers, and ICE + * candidates between peers. The signaling server is a simple JSON relay + * (see browser/signaling-server/server.js). + */ + +export class SignalingClient { + /** @type {WebSocket | null} */ + #ws = null; + /** @type {string} */ + #url; + /** @type {string} */ + #peerId; + /** @type {Map} */ + #handlers = new Map(); + /** @type {boolean} */ + #connected = false; + /** @type {number | null} */ + #heartbeatTimer = null; + + /** + * @param {string} url - WebSocket URL of the signaling server + * @param {string} peerId - This peer's unique ID + */ + constructor(url, peerId) { + this.#url = url; + this.#peerId = peerId; + } + + get connected() { + return this.#connected; + } + + get peerId() { + return this.#peerId; + } + + /** Connect to the signaling server. */ + connect() { + return new Promise((resolve, reject) => { + this.#ws = new WebSocket(this.#url); + + this.#ws.onopen = () => { + this.#connected = true; + // Register our peer ID with the server + this.#send({ type: 'register', peerId: this.#peerId }); + // Start heartbeat + this.#heartbeatTimer = setInterval(() => { + if (this.#connected) this.#send({ type: 'ping' }); + }, 30_000); + resolve(); + }; + + this.#ws.onmessage = (event) => { + try { + const msg = JSON.parse(event.data); + this.#dispatch(msg.type, msg); + } catch (e) { + console.warn('[signaling] Failed to parse message:', e); + } + }; + + this.#ws.onclose = () => { + this.#connected = false; + this.#stopHeartbeat(); + this.#dispatch('disconnect', {}); + }; + + this.#ws.onerror = (err) => { + if (!this.#connected) reject(err); + this.#dispatch('error', { error: err }); + }; + }); + } + + /** Disconnect from the signaling server. */ + disconnect() { + this.#stopHeartbeat(); + if (this.#ws) { + this.#ws.close(); + this.#ws = null; + } + this.#connected = false; + } + + /** Send an SDP offer to a remote peer. */ + sendOffer(to, sdp) { + this.#send({ type: 'offer', to, sdp }); + } + + /** Send an SDP answer to a remote peer. */ + sendAnswer(to, sdp) { + this.#send({ type: 'answer', to, sdp }); + } + + /** Send an ICE candidate to a remote peer. */ + sendCandidate(to, candidate, sdpMid) { + this.#send({ type: 'candidate', to, candidate, sdpMid }); + } + + /** + * Register an event handler. + * @param {'offer'|'answer'|'candidate'|'error'|'disconnect'} type + * @param {Function} handler + */ + on(type, handler) { + if (!this.#handlers.has(type)) this.#handlers.set(type, []); + this.#handlers.get(type).push(handler); + } + + /** Remove all handlers for a given event type. */ + off(type) { + this.#handlers.delete(type); + } + + #send(msg) { + if (this.#ws && this.#ws.readyState === WebSocket.OPEN) { + this.#ws.send(JSON.stringify(msg)); + } + } + + #dispatch(type, msg) { + const handlers = this.#handlers.get(type); + if (handlers) { + for (const handler of handlers) handler(msg); + } + } + + #stopHeartbeat() { + if (this.#heartbeatTimer !== null) { + clearInterval(this.#heartbeatTimer); + this.#heartbeatTimer = null; + } + } +} diff --git a/browser/host/webrtc-host.js b/browser/host/webrtc-host.js new file mode 100644 index 0000000..e129060 --- /dev/null +++ b/browser/host/webrtc-host.js @@ -0,0 +1,323 @@ +/** + * WebRTC host — manages RTCPeerConnection and DataChannel instances + * on behalf of the WASM module. + * + * The WASM side sees channels as integer IDs. This host maps those IDs + * to browser RTCDataChannel objects and routes events back to WASM via + * the exported callback functions. + */ + +export class WebRTCHost { + /** @type {Map} channel_id → DataChannel */ + #channels = new Map(); + /** @type {Map} channelId → true if we created the offer */ + #channelRoles = new Map(); + /** @type {Map} remote_peer_id → PeerConnection */ + #peerConnections = new Map(); + /** @type {number} next channel ID to assign */ + #nextChannelId = 1; + /** @type {RTCConfiguration} */ + #rtcConfig; + /** @type {object | null} WASM exports (set after load) */ + #wasm = null; + /** @type {number} WASM instance ID */ + #instanceId = 0; + /** @type {import('./signaling.js').SignalingClient | null} */ + #signaling = null; + /** @type {Array<(channelId: number, appId: number, payload: Uint8Array) => void>} */ + #directHandlers = []; + /** Direct message prefix byte — distinguishes from P2P-framed messages */ + static DIRECT_PREFIX = 0xFF; + + /** + * @param {RTCConfiguration} [rtcConfig] - ICE server configuration + */ + constructor(rtcConfig) { + this.#rtcConfig = rtcConfig || { + iceServers: [{ urls: 'stun:stun.l.google.com:19302' }], + }; + } + + /** + * Bind to WASM exports so we can call back into the module. + * @param {object} wasmExports - The WASM module's exports + * @param {number} instanceId - The P2P instance ID in WASM + */ + bind(wasmExports, instanceId) { + this.#wasm = wasmExports; + this.#instanceId = instanceId; + } + + /** + * Bind to a signaling client for SDP/ICE exchange. + * @param {import('./signaling.js').SignalingClient} signaling + */ + bindSignaling(signaling) { + this.#signaling = signaling; + + signaling.on('offer', (msg) => this.handleOffer(msg.from, msg.sdp)); + signaling.on('answer', (msg) => this.handleAnswer(msg.from, msg.sdp)); + signaling.on('candidate', (msg) => + this.handleCandidate(msg.from, msg.candidate, msg.sdpMid) + ); + } + + /** + * Initiate a WebRTC connection to a remote peer. + * @param {string} remotePeerId - The remote peer's signaling ID + * @returns {Promise} The channel ID assigned to this connection + */ + async connectToPeer(remotePeerId) { + const pc = this.#createPeerConnection(remotePeerId); + const dc = pc.createDataChannel('zig-p2p', { + protocol: 'zig-p2p', + ordered: true, + }); + + const channelId = this.#registerChannel(dc); + this.#channelRoles.set(channelId, true); // outbound = initiator + this.#setupDataChannel(dc, channelId); + + const offer = await pc.createOffer(); + await pc.setLocalDescription(offer); + + this.#signaling?.sendOffer(remotePeerId, pc.localDescription.sdp); + return channelId; + } + + /** + * Handle an incoming SDP offer from a remote peer. + * @param {string} fromPeerId + * @param {string} sdp + */ + async handleOffer(fromPeerId, sdp) { + const pc = this.#createPeerConnection(fromPeerId); + + pc.ondatachannel = (event) => { + const dc = event.channel; + const channelId = this.#registerChannel(dc); + this.#channelRoles.set(channelId, false); // inbound = responder + this.#setupDataChannel(dc, channelId); + }; + + await pc.setRemoteDescription({ type: 'offer', sdp }); + const answer = await pc.createAnswer(); + await pc.setLocalDescription(answer); + + this.#signaling?.sendAnswer(fromPeerId, pc.localDescription.sdp); + } + + /** + * Handle an incoming SDP answer. + * @param {string} fromPeerId + * @param {string} sdp + */ + async handleAnswer(fromPeerId, sdp) { + const pc = this.#peerConnections.get(fromPeerId); + if (!pc) { + console.warn('[webrtc] Got answer from unknown peer:', fromPeerId); + return; + } + await pc.setRemoteDescription({ type: 'answer', sdp }); + } + + /** + * Handle an incoming ICE candidate. + * @param {string} fromPeerId + * @param {string} candidate + * @param {string} sdpMid + */ + async handleCandidate(fromPeerId, candidate, sdpMid) { + const pc = this.#peerConnections.get(fromPeerId); + if (!pc) return; + await pc.addIceCandidate({ candidate, sdpMid }); + } + + /** + * Send data on a channel (called by WASM via extern "env"). + * @param {number} channelId + * @param {Uint8Array} data + * @returns {number} 0 on success, -1 on error + */ + send(channelId, data) { + const dc = this.#channels.get(channelId); + if (!dc || dc.readyState !== 'open') return -1; + try { + dc.send(data); + return 0; + } catch { + return -1; + } + } + + /** + * Close a channel (called by WASM via extern "env"). + * @param {number} channelId + */ + closeChannel(channelId) { + const dc = this.#channels.get(channelId); + if (dc) { + dc.close(); + this.#channels.delete(channelId); + } + } + + /** + * Get buffered amount for a channel (called by WASM via extern "env"). + * @param {number} channelId + * @returns {number} + */ + bufferedAmount(channelId) { + const dc = this.#channels.get(channelId); + return dc ? dc.bufferedAmount : 0; + } + + /** Close all connections and clean up. */ + destroy() { + for (const dc of this.#channels.values()) { + dc.close(); + } + this.#channels.clear(); + this.#channelRoles.clear(); + for (const pc of this.#peerConnections.values()) { + pc.close(); + } + this.#peerConnections.clear(); + } + + /** @returns {number} Number of active channels */ + get channelCount() { + return this.#channels.size; + } + + /** @returns {number[]} All active channel IDs */ + getChannelIds() { + return [...this.#channels.keys()]; + } + + /** + * Get total buffered amount across all channels (for flow control). + * @returns {number} Sum of all DataChannel bufferedAmount values + */ + get totalBufferedAmount() { + let total = 0; + for (const dc of this.#channels.values()) { + total += dc.bufferedAmount; + } + return total; + } + + /** + * Send a pre-formatted direct message on a DataChannel. + * The caller must include the [0xFF][app_id] prefix in the data. + * This avoids an extra copy for large payloads. + * @param {number} channelId + * @param {Uint8Array} data - Complete message including 0xFF prefix + * @returns {boolean} true on success + */ + sendDirect(channelId, data) { + const dc = this.#channels.get(channelId); + if (!dc || dc.readyState !== 'open') return false; + try { + dc.send(data); + return true; + } catch { + return false; + } + } + + /** + * Register a handler for direct messages (0xFF-prefixed). + * Handler receives (channelId, appId, payload). + * @param {(channelId: number, appId: number, payload: Uint8Array) => void} handler + */ + registerDirectHandler(handler) { + this.#directHandlers.push(handler); + } + + // -- Private helpers -- + + #createPeerConnection(remotePeerId) { + // Close existing connection to same peer if any + const existing = this.#peerConnections.get(remotePeerId); + if (existing) existing.close(); + + const pc = new RTCPeerConnection(this.#rtcConfig); + this.#peerConnections.set(remotePeerId, pc); + + pc.onicecandidate = (event) => { + if (event.candidate) { + this.#signaling?.sendCandidate( + remotePeerId, + event.candidate.candidate, + event.candidate.sdpMid + ); + } + }; + + pc.onconnectionstatechange = () => { + if (pc.connectionState === 'failed' || pc.connectionState === 'closed') { + this.#peerConnections.delete(remotePeerId); + } + }; + + return pc; + } + + #registerChannel(dc) { + const channelId = this.#nextChannelId++; + this.#channels.set(channelId, dc); + return channelId; + } + + #setupDataChannel(dc, channelId) { + dc.binaryType = 'arraybuffer'; + + dc.onopen = () => { + const isInitiator = this.#channelRoles.get(channelId) ?? false; + this.#wasm?.wasm_on_datachannel_open(this.#instanceId, channelId, isInitiator ? 1 : 0); + }; + + dc.onmessage = (event) => { + const data = new Uint8Array(event.data); + + // Direct message path: 0xFF prefix → JS handlers only, never enters WASM. + // This eliminates 3 alloc+copy cycles per message through the WASM stack. + if (data.length >= 2 && data[0] === WebRTCHost.DIRECT_PREFIX) { + const appId = data[1]; + const payload = data.subarray(2); + for (const handler of this.#directHandlers) { + try { handler(channelId, appId, payload); } catch {} + } + return; + } + + // P2P-framed message → route through WASM + if (!this.#wasm) return; + const ptr = this.#wasm.wasm_alloc(data.length); + if (!ptr) { + console.warn('[webrtc] Failed to allocate WASM memory for message'); + return; + } + const wasmBuf = new Uint8Array(this.#wasm.memory.buffer, ptr, data.length); + wasmBuf.set(data); + this.#wasm.wasm_on_datachannel_message( + this.#instanceId, + channelId, + ptr, + data.length + ); + this.#wasm.wasm_free(ptr, data.length); + }; + + dc.onclose = () => { + this.#wasm?.wasm_on_datachannel_close(this.#instanceId, channelId); + this.#channels.delete(channelId); + this.#channelRoles.delete(channelId); + }; + + dc.onerror = () => { + this.#wasm?.wasm_on_datachannel_error(this.#instanceId, channelId); + }; + } +} diff --git a/browser/host/zig-p2p.js b/browser/host/zig-p2p.js new file mode 100644 index 0000000..29bfdfd --- /dev/null +++ b/browser/host/zig-p2p.js @@ -0,0 +1,461 @@ +/** + * zig-p2p Browser Host + * + * Loads the WASM module, provides platform APIs, and manages WebRTC + * connections. The entire P2P protocol (Noise, DHT, messaging, wire + * envelope) runs inside WASM — this is a thin glue layer. + * + * Usage: + * import { ZigP2P } from './zig-p2p.js'; + * + * const p2p = await ZigP2P.load('/zig-p2p.wasm', { + * signalingUrl: 'ws://localhost:8080', + * iceServers: [{ urls: 'stun:stun.l.google.com:19302' }], + * }); + * + * p2p.onMessage((peerId, appId, data) => { ... }); + * await p2p.connectToPeer('remote-peer-id'); + * p2p.send(peerId, 0x03, new Uint8Array([1, 2, 3])); + */ + +import { createPlatformEnv } from './platform-env.js'; +import { WebRTCHost } from './webrtc-host.js'; +import { SignalingClient } from './signaling.js'; +import { FileHost } from './file-host.js'; + +export class ZigP2P { + /** @type {WebAssembly.Instance} */ + #wasmInstance; + /** @type {WebAssembly.Memory} */ + #memory; + /** @type {object} WASM exports */ + #exports; + /** @type {number} WASM P2P instance ID */ + #instanceId; + /** @type {WebRTCHost} */ + #webrtcHost; + /** @type {SignalingClient} */ + #signaling; + /** @type {number | null} update interval handle */ + #updateTimer = null; + /** @type {Function[]} message handlers */ + #messageHandlers = []; + /** @type {Function[]} connection handlers */ + #connectionHandlers = []; + /** @type {Function[]} file event handlers */ + #fileEventHandlers = []; + /** @type {FileHost} */ + #fileHost; + /** @type {boolean} */ + #destroyed = false; + /** @type {number} WASM pointer for event polling buffer */ + #eventBufPtr = 0; + /** @type {number} */ + #eventBufLen = 0; + /** @type {Map} channelId → channelId (identity, for reverse lookup from peerId) */ + #peerIdToChannel = new Map(); // peerId hex → channelId + + /** + * Load the WASM module and initialize the P2P library. + * + * @param {string | URL | ArrayBuffer} wasmSource - URL to .wasm file, or raw bytes + * @param {object} config + * @param {string} config.signalingUrl - WebSocket URL of the signaling server + * @param {string} [config.peerId] - Peer ID for signaling (random if not set) + * @param {number} [config.listenPort=0] - Port (unused in browser, passed to WASM init) + * @param {RTCConfiguration} [config.rtcConfig] - WebRTC ICE configuration + * @param {number} [config.updateIntervalMs=16] - How often to call wasm_p2p_update + * @returns {Promise} + */ + static async load(wasmSource, config) { + const instance = new ZigP2P(); + await instance.#init(wasmSource, config); + return instance; + } + + async #init(wasmSource, config) { + const { + signalingUrl, + peerId = crypto.randomUUID(), + listenPort = 0, + rtcConfig, + updateIntervalMs = 16, + } = config; + + // 1. Create WebRTC host and file host + this.#webrtcHost = new WebRTCHost(rtcConfig); + let memory; + this.#fileHost = new FileHost(() => memory); + + // 2. Create platform env with WebRTC + file wiring + const env = { + ...createPlatformEnv(() => memory), + ...this.#fileHost.getEnvBindings(), + }; + + // Wire datachannel extern "env" functions to the WebRTC host + env.js_datachannel_send = (channelId, dataPtr, dataLen) => { + const data = new Uint8Array(memory.buffer, dataPtr, dataLen); + return this.#webrtcHost.send(channelId, data); + }; + env.js_datachannel_close = (channelId) => { + this.#webrtcHost.closeChannel(channelId); + }; + env.js_datachannel_buffered_amount = (channelId) => { + return this.#webrtcHost.bufferedAmount(channelId); + }; + + // 3. Load WASM module + let wasmBytes; + if (wasmSource instanceof ArrayBuffer) { + wasmBytes = wasmSource; + } else { + const response = await fetch(wasmSource); + wasmBytes = await response.arrayBuffer(); + } + + const { instance } = await WebAssembly.instantiate(wasmBytes, { env }); + this.#wasmInstance = instance; + this.#exports = instance.exports; + memory = instance.exports.memory; + this.#memory = memory; + + // 4. Initialize P2P instance in WASM + this.#instanceId = this.#exports.wasm_p2p_init(listenPort); + if (this.#instanceId < 0) { + throw new Error('Failed to initialize P2P instance in WASM'); + } + + // 5. Bind WebRTC host to WASM exports + this.#webrtcHost.bind( + { ...this.#exports, memory: this.#memory }, + this.#instanceId + ); + + // 6. Connect to signaling server + this.#signaling = new SignalingClient(signalingUrl, peerId); + this.#webrtcHost.bindSignaling(this.#signaling); + await this.#signaling.connect(); + + // 7. Allocate event polling buffer (reused every tick) + // 2MB to support large file chunks (up to 1MB+ per message) + this.#eventBufPtr = this.#exports.wasm_alloc(2097152); + this.#eventBufLen = 2097152; + + // 8. Start update loop + this.#updateTimer = setInterval(() => { + if (!this.#destroyed) { + this.#exports.wasm_p2p_update(this.#instanceId); + this.#drainEvents(); + } + }, updateIntervalMs); + } + + /** + * Connect to a remote peer via WebRTC (through signaling server). + * @param {string} remotePeerId - The remote peer's signaling ID + * @returns {Promise} Channel ID + */ + async connectToPeer(remotePeerId) { + return this.#webrtcHost.connectToPeer(remotePeerId); + } + + /** + * Get the 32-byte P2P PeerId for a given WebRTC channel. + * @param {number} channelId - The WebRTC channel ID + * @returns {Uint8Array | null} 32-byte PeerId, or null on failure + */ + getPeerIdForChannel(channelId) { + if (this.#destroyed) return null; + const outPtr = this.#exports.wasm_alloc(32); + if (!outPtr) return null; + try { + const result = this.#exports.wasm_get_peer_id_for_channel( + this.#instanceId, + channelId, + outPtr + ); + if (result !== 0) return null; + const bytes = new Uint8Array(32); + bytes.set(new Uint8Array(this.#memory.buffer, outPtr, 32)); + return bytes; + } finally { + this.#exports.wasm_free(outPtr, 32); + } + } + + /** + * Send a message to a peer. + * @param {Uint8Array} peerId - 32-byte peer ID + * @param {number} appId - Application ID byte + * @param {Uint8Array} data - Message payload + * @returns {boolean} true on success + */ + send(peerId, appId, data) { + if (this.#destroyed) return false; + + // Allocate WASM memory for peer ID + data + const peerPtr = this.#exports.wasm_alloc(peerId.length); + const dataPtr = this.#exports.wasm_alloc(data.length); + if (!peerPtr || !dataPtr) return false; + + try { + new Uint8Array(this.#memory.buffer, peerPtr, peerId.length).set(peerId); + new Uint8Array(this.#memory.buffer, dataPtr, data.length).set(data); + const result = this.#exports.wasm_p2p_send( + this.#instanceId, + peerPtr, + appId, + dataPtr, + data.length + ); + return result === 0; + } finally { + this.#exports.wasm_free(peerPtr, peerId.length); + this.#exports.wasm_free(dataPtr, data.length); + } + } + + /** + * Register a message handler. + * @param {(peerId: Uint8Array, appId: number, data: Uint8Array) => void} handler + */ + onMessage(handler) { + this.#messageHandlers.push(handler); + } + + /** + * Register a connection handler. + * @param {(peerId: string, channelId: number) => void} handler + */ + onConnection(handler) { + this.#connectionHandlers.push(handler); + } + + /** + * Send a pre-formatted direct message on a DataChannel, bypassing WASM. + * The data must include the [0xFF][app_id] prefix. Use for high-throughput + * data (file chunks) where WASM alloc/copy overhead is wasteful. + * @param {number} channelId - The WebRTC channel ID + * @param {Uint8Array} data - Complete message including 0xFF prefix + * @returns {boolean} true on success + */ + sendDirect(channelId, data) { + if (this.#destroyed) return false; + return this.#webrtcHost.sendDirect(channelId, data); + } + + /** + * Register a handler for direct messages (bypasses WASM). + * @param {(channelId: number, appId: number, payload: Uint8Array) => void} handler + */ + onDirectMessage(handler) { + this.#webrtcHost.registerDirectHandler(handler); + } + + /** + * Get all active channel IDs. + * @returns {number[]} + */ + getChannelIds() { + return this.#webrtcHost.getChannelIds(); + } + + /** @returns {number} Library version from WASM */ + get version() { + return this.#exports.wasm_version(); + } + + /** @returns {string} This peer's signaling ID */ + get peerId() { + return this.#signaling.peerId; + } + + /** @returns {boolean} Whether connected to signaling server */ + get signalingConnected() { + return this.#signaling.connected; + } + + /** @returns {number} Number of active WebRTC channels */ + get channelCount() { + return this.#webrtcHost.channelCount; + } + + /** @returns {number} Total buffered bytes across all DataChannels (for flow control) */ + get totalBufferedAmount() { + return this.#webrtcHost.totalBufferedAmount; + } + + /** Drain pending events from the WASM P2P event queue. */ + #drainEvents() { + if (!this.#eventBufPtr) return; + for (let i = 0; i < 4096; i++) { + const n = this.#exports.wasm_poll_event( + this.#instanceId, + this.#eventBufPtr, + this.#eventBufLen + ); + if (n <= 0) break; + + const buf = new Uint8Array(this.#memory.buffer, this.#eventBufPtr, n); + const eventType = buf[0]; + + if (eventType === 1 && n >= 34) { + // message_received: [1][app_id:1][peer_id:32][data:N] + const appId = buf[1]; + const peerId = new Uint8Array(buf.slice(2, 34)); + const data = new Uint8Array(buf.slice(34, n)); + for (const handler of this.#messageHandlers) { + try { handler(peerId, appId, data); } catch {} + } + } else if (eventType === 2 && n >= 33) { + // peer_connected: [2][peer_id:32] + const peerId = new Uint8Array(buf.slice(1, 33)); + const peerHex = Array.from(peerId.slice(0, 8)) + .map((b) => b.toString(16).padStart(2, '0')) + .join(''); + for (const handler of this.#connectionHandlers) { + try { handler(peerHex, 0); } catch {} + } + } + // type 3 (peer_disconnected) — not wired yet + else if (eventType === 4 && n >= 13) { + // file_shared: [4][session_id:8 LE][path_len:4 LE][path:N] + const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n); + const sessionId = view.getBigUint64(1, true); + const pathLen = view.getUint32(9, true); + const path = new TextDecoder().decode(buf.slice(13, 13 + pathLen)); + for (const handler of this.#fileEventHandlers) { + try { handler({ type: 'shared', sessionId, path }); } catch {} + } + } else if (eventType === 5 && n >= 13) { + // file_download_started: [5][session_id:8 LE][name_len:4 LE][name:N] + const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n); + const sessionId = view.getBigUint64(1, true); + const nameLen = view.getUint32(9, true); + const name = new TextDecoder().decode(buf.slice(13, 13 + nameLen)); + for (const handler of this.#fileEventHandlers) { + try { handler({ type: 'download_started', sessionId, name }); } catch {} + } + } else if (eventType === 6 && n >= 9) { + // file_download_completed: [6][session_id:8 LE] + const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n); + const sessionId = view.getBigUint64(1, true); + for (const handler of this.#fileEventHandlers) { + try { handler({ type: 'download_completed', sessionId }); } catch {} + } + } else if (eventType === 7 && n >= 9) { + // file_download_failed: [7][session_id:8 LE] + const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n); + const sessionId = view.getBigUint64(1, true); + for (const handler of this.#fileEventHandlers) { + try { handler({ type: 'download_failed', sessionId }); } catch {} + } + } + } + } + + // ============================================================ + // File Transfer API + // ============================================================ + + /** + * Register a file event handler. + * @param {(event: { type: string, sessionId: bigint, path?: string, name?: string }) => void} handler + */ + onFileEvent(handler) { + this.#fileEventHandlers.push(handler); + } + + /** + * Share a file with connected peers. + * + * For small files (<50MB): materializes into WASM memory and registers + * with the Zig file manager (full hashing + session management). + * + * For large files: registers the File handle for streaming JS-level + * transfer (no WASM hashing, no full memory copy). + * + * @param {File} file - Browser File object to share + * @returns {Promise<{ virtualPath: string, size: number }>} + */ + async shareFile(file) { + if (this.#destroyed) throw new Error('Instance destroyed'); + + const MATERIALIZE_THRESHOLD = 50 * 1024 * 1024; // 50MB + const virtualPath = this.#fileHost.registerBrowserFile(file); + + if (file.size <= MATERIALIZE_THRESHOLD) { + // Small file: materialize and register with WASM file manager + await this.#fileHost.materializeFile(virtualPath); + const pathBytes = new TextEncoder().encode(virtualPath); + const pathPtr = this.#exports.wasm_alloc(pathBytes.length); + if (!pathPtr) throw new Error('WASM alloc failed'); + + try { + new Uint8Array(this.#memory.buffer, pathPtr, pathBytes.length).set(pathBytes); + const sessionId = this.#exports.wasm_file_share( + this.#instanceId, + pathPtr, + pathBytes.length + ); + // wasm_file_share returns -1n (i64) on error; valid session IDs are + // u64 values that may appear negative in signed BigInt when > 2^63. + if (sessionId === -1n) throw new Error('Failed to share file'); + } finally { + this.#exports.wasm_free(pathPtr, pathBytes.length); + } + } + // Large files: File handle is stored in FileHost for streaming reads. + // The JS-level transfer (demo.js) reads via fileHost.readFileChunk(). + + return { virtualPath, size: file.size }; + } + + /** + * Get a completed download as a Blob for saving. + * @param {string} name - File name (virtual path) + * @returns {Blob | null} + */ + getDownloadBlob(name) { + return this.#fileHost.getFileBlob(name); + } + + /** + * Trigger a browser download for a completed file. + * @param {string} name - File name + */ + downloadToDesktop(name) { + const blob = this.#fileHost.getFileBlob(name); + if (!blob) return; + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = name; + a.click(); + URL.revokeObjectURL(url); + } + + /** @returns {FileHost} The file host for advanced use */ + get fileHost() { + return this.#fileHost; + } + + /** Shut down everything. */ + destroy() { + this.#destroyed = true; + if (this.#updateTimer !== null) { + clearInterval(this.#updateTimer); + this.#updateTimer = null; + } + this.#webrtcHost.destroy(); + this.#signaling.disconnect(); + if (this.#instanceId >= 0) { + this.#exports.wasm_p2p_deinit(this.#instanceId); + } + if (this.#eventBufPtr) { + this.#exports.wasm_free(this.#eventBufPtr, this.#eventBufLen); + this.#eventBufPtr = 0; + } + } +} diff --git a/browser/signaling-server/package-lock.json b/browser/signaling-server/package-lock.json new file mode 100644 index 0000000..e752602 --- /dev/null +++ b/browser/signaling-server/package-lock.json @@ -0,0 +1,36 @@ +{ + "name": "@zig-p2p/signaling-server", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@zig-p2p/signaling-server", + "version": "0.1.0", + "dependencies": { + "ws": "^8.18.0" + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/browser/signaling-server/package.json b/browser/signaling-server/package.json new file mode 100644 index 0000000..358d861 --- /dev/null +++ b/browser/signaling-server/package.json @@ -0,0 +1,13 @@ +{ + "name": "@zig-p2p/signaling-server", + "version": "0.1.0", + "description": "WebSocket signaling relay for zig-p2p WebRTC connections", + "type": "module", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "ws": "^8.18.0" + } +} diff --git a/browser/signaling-server/server.js b/browser/signaling-server/server.js new file mode 100644 index 0000000..161b0fe --- /dev/null +++ b/browser/signaling-server/server.js @@ -0,0 +1,212 @@ +/** + * zig-p2p Signaling Server + * + * Simple WebSocket relay that routes SDP offers/answers and ICE candidates + * between peers by peerId. No authentication — the Noise handshake over + * the resulting WebRTC DataChannel provides mutual authentication. + * + * Protocol (JSON over WebSocket): + * + * Client → Server: + * { "type": "register", "peerId": "abc123" } + * { "type": "offer", "to": "xyz789", "sdp": "v=0..." } + * { "type": "answer", "to": "abc123", "sdp": "v=0..." } + * { "type": "candidate", "to": "xyz789", "candidate": "...", "sdpMid": "0" } + * { "type": "ping" } + * + * Server → Client: + * { "type": "registered", "peerId": "abc123" } + * { "type": "offer", "from": "abc123", "sdp": "v=0..." } + * { "type": "answer", "from": "xyz789", "sdp": "v=0..." } + * { "type": "candidate", "from": "abc123", "candidate": "...", "sdpMid": "0" } + * { "type": "error", "message": "peer not found" } + * { "type": "pong" } + * + * Usage: + * npm install + * node server.js [--port 8080] [--host 0.0.0.0] + */ + +import { WebSocketServer } from 'ws'; + +// -- Configuration -- + +const args = process.argv.slice(2); +function getArg(name, defaultVal) { + const idx = args.indexOf(name); + return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : defaultVal; +} + +const PORT = parseInt(getArg('--port', '8080'), 10); +const HOST = getArg('--host', '0.0.0.0'); +const HEARTBEAT_INTERVAL_MS = 30_000; +const STALE_TIMEOUT_MS = 90_000; +const MAX_MESSAGE_RATE = 100; // messages per second per client +const MAX_MESSAGE_SIZE = 65536; // 64KB max message + +// -- State -- + +/** @type {Map} peerId → WebSocket */ +const peers = new Map(); + +/** @type {Map} */ +const state = new Map(); + +/** + * @typedef {object} PeerState + * @property {string} peerId + * @property {number} lastActivity - timestamp ms + * @property {number} messageCount - messages in current window + * @property {number} windowStart - start of rate limit window + */ + +// -- Server -- + +const wss = new WebSocketServer({ + port: PORT, + host: HOST, + maxPayload: MAX_MESSAGE_SIZE, +}); + +console.log(`[signaling] Listening on ws://${HOST}:${PORT}`); + +wss.on('connection', (ws) => { + state.set(ws, { + peerId: null, + lastActivity: Date.now(), + messageCount: 0, + windowStart: Date.now(), + }); + + ws.on('message', (raw) => { + const s = state.get(ws); + if (!s) return; + + // Rate limiting + const now = Date.now(); + if (now - s.windowStart > 1000) { + s.messageCount = 0; + s.windowStart = now; + } + s.messageCount++; + if (s.messageCount > MAX_MESSAGE_RATE) { + send(ws, { type: 'error', message: 'rate limit exceeded' }); + return; + } + s.lastActivity = now; + + let msg; + try { + msg = JSON.parse(raw.toString()); + } catch { + send(ws, { type: 'error', message: 'invalid JSON' }); + return; + } + + handleMessage(ws, s, msg); + }); + + ws.on('close', () => { + const s = state.get(ws); + if (s?.peerId) { + peers.delete(s.peerId); + console.log(`[signaling] Peer disconnected: ${s.peerId} (${peers.size} online)`); + } + state.delete(ws); + }); + + ws.on('error', () => { + // Handled by 'close' event + }); +}); + +// -- Message handling -- + +function handleMessage(ws, s, msg) { + switch (msg.type) { + case 'register': { + const { peerId } = msg; + if (!peerId || typeof peerId !== 'string') { + send(ws, { type: 'error', message: 'peerId required' }); + return; + } + // Disconnect existing peer with same ID + const existing = peers.get(peerId); + if (existing && existing !== ws) { + send(existing, { type: 'error', message: 'replaced by new connection' }); + existing.close(); + } + s.peerId = peerId; + peers.set(peerId, ws); + send(ws, { type: 'registered', peerId }); + console.log(`[signaling] Peer registered: ${peerId} (${peers.size} online)`); + break; + } + + case 'offer': + case 'answer': + case 'candidate': { + if (!s.peerId) { + send(ws, { type: 'error', message: 'must register first' }); + return; + } + const { to } = msg; + if (!to || typeof to !== 'string') { + send(ws, { type: 'error', message: '"to" field required' }); + return; + } + const target = peers.get(to); + if (!target) { + send(ws, { type: 'error', message: 'peer not found' }); + return; + } + // Forward with "from" field added + const forwarded = { ...msg, from: s.peerId }; + delete forwarded.to; + send(target, forwarded); + break; + } + + case 'ping': + send(ws, { type: 'pong' }); + break; + + default: + send(ws, { type: 'error', message: `unknown type: ${msg.type}` }); + } +} + +function send(ws, msg) { + if (ws.readyState === ws.OPEN) { + ws.send(JSON.stringify(msg)); + } +} + +// -- Heartbeat / stale cleanup -- + +const heartbeatTimer = setInterval(() => { + const now = Date.now(); + for (const [ws, s] of state) { + if (now - s.lastActivity > STALE_TIMEOUT_MS) { + console.log(`[signaling] Dropping stale peer: ${s.peerId}`); + ws.terminate(); + } + } +}, HEARTBEAT_INTERVAL_MS); + +// -- Graceful shutdown -- + +function shutdown() { + console.log('[signaling] Shutting down...'); + clearInterval(heartbeatTimer); + for (const ws of state.keys()) { + ws.close(); + } + wss.close(() => { + console.log('[signaling] Closed.'); + process.exit(0); + }); +} + +process.on('SIGINT', shutdown); +process.on('SIGTERM', shutdown); diff --git a/src/wasm/main.zig b/src/wasm/main.zig new file mode 100644 index 0000000..f4bf45b --- /dev/null +++ b/src/wasm/main.zig @@ -0,0 +1,571 @@ +//! WASM Entry Point for zig-p2p +//! +//! Exports functions callable from the JavaScript host. The entire P2P protocol +//! (Noise handshake, wire envelope, DHT, messaging) runs in WASM — the JS side +//! is a thin glue layer that provides platform APIs (time, random, WebRTC). +//! +//! Memory layout: WASM linear memory managed by Zig's page_allocator. +//! JS interacts via exported pointer+length pairs. + +const std = @import("std"); +const builtin = @import("builtin"); +const p2p_lib = @import("p2p"); +const core = @import("core"); +const network = @import("network"); +const noise = @import("noise"); +const files = @import("files"); + +const webrtc_wasm = @import("platform").webrtc_wasm; +const WasmChannelManager = webrtc_wasm.WasmChannelManager; +const SecureConnection = network.SecureConnection; +const FileSharingManager = files.manager.FileSharingManager; +const FileMetadata = files.hash.FileMetadata; + +extern "env" fn js_log(ptr: [*]const u8, len: u32) void; + +/// Override std.log for WASM: route to JS console via extern "env" js_log. +pub const std_options: std.Options = .{ + .logFn = wasmLog, +}; + +fn wasmLog( + comptime level: std.log.Level, + comptime _: @Type(.enum_literal), + comptime fmt: []const u8, + args: anytype, +) void { + // Format into a stack buffer and send to JS + var buf: [1024]u8 = undefined; + const prefix = switch (level) { + .err => "[ERR] ", + .warn => "[WARN] ", + .info => "[INFO] ", + .debug => "[DBG] ", + }; + var stream = std.io.fixedBufferStream(&buf); + stream.writer().writeAll(prefix) catch return; + stream.writer().print(fmt, args) catch return; + const written = stream.pos; + if (written > 0) { + js_log(&buf, @intCast(written)); + } +} + +const P2P = p2p_lib.P2P; +const P2PConfig = p2p_lib.P2PConfig; +const Error = core.errors.Error; +const NetworkManager = network.network_manager.NetworkManager; + +/// Lightweight WASM init: sets up only the subsystems needed for transport-based messaging. +/// Full start() would try to create POSIX sockets, discovery, TURN, etc. +fn wasmStartEssentials(p2p: *P2P) Error!void { + // 1. NetworkManager — drives transport I/O in update loop + const nm = allocator.create(NetworkManager) catch return Error.SystemError; + nm.* = NetworkManager.init(allocator, &p2p.peer_connections); + // Larger receive buffer for big file chunks (up to 2MB per message) + nm.config.receive_buffer_size = 2 * 1024 * 1024; + nm.setSocketMutex(&p2p.peer_connections_mutex); + p2p.network_manager = nm; + + // 2. Wire message callback so received messages become events + nm.setMessageCallback(p2p_lib.messaging.handleNetworkMessageImpl, p2p); + + // 3. Skip HandlerRegistry — it pulls in file/protocol code with POSIX deps. + // handleNetworkMessageImpl has a WASM-specific path that skips replay + // protection when handler_registry is null (see messaging.zig). + p2p.handler_registry = null; + + // 4. Initialize file sharing manager (uses FileSystem abstraction for WASM file I/O) + const fm_ptr = allocator.create(FileSharingManager) catch return Error.SystemError; + fm_ptr.* = FileSharingManager.init(p2p.config.file_sharing, allocator) catch { + allocator.destroy(fm_ptr); + return Error.SystemError; + }; + p2p.file_manager = fm_ptr; + + // Wire file transfer sender + const file_ops = p2p_lib.file_ops; + const sender = allocator.create(files.manager.NetworkSender) catch return Error.SystemError; + sender.* = file_ops.createFileTransferSenderImpl(p2p); + fm_ptr.setNetworkSender(sender); + fm_ptr.p2p_context = p2p; + + // 5. Mark as running so update() processes I/O + p2p.running.store(true, .release); + + std.log.info("WASM P2P initialized with file transfer support", .{}); +} + +// Use a GPA for fine-grained allocation +var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init; +const allocator = gpa.allocator(); + +// ============================================================ +// Instance Storage (P2P + per-instance channel manager) +// ============================================================ + +const MAX_INSTANCES = 4; + +const PendingWasmHandshake = struct { + channel_id: u32, + peer_id: network.peer.PeerId, + transport_ptr: *webrtc_wasm.WasmWebRTCTransport, + secure: *SecureConnection, +}; + +const WasmInstance = struct { + p2p: *P2P, + channels: WasmChannelManager, + pending_handshakes: [webrtc_wasm.MAX_CHANNELS]?PendingWasmHandshake = + .{null} ** webrtc_wasm.MAX_CHANNELS, +}; + +var instances: [MAX_INSTANCES]?WasmInstance = .{null} ** MAX_INSTANCES; + +fn getInstance(id: i32) ?*WasmInstance { + if (id < 0 or id >= MAX_INSTANCES) return null; + const idx: usize = @intCast(id); + if (instances[idx] != null) return &instances[idx].?; + return null; +} + +// ============================================================ +// Memory Management Exports +// ============================================================ + +/// Allocate `size` bytes of WASM memory. Returns pointer or null on failure. +/// JS should call this to allocate buffers before passing data to WASM. +export fn wasm_alloc(size: usize) ?[*]u8 { + const slice = allocator.alloc(u8, size) catch return null; + return slice.ptr; +} + +/// Free a previously allocated buffer. +export fn wasm_free(ptr: [*]u8, size: usize) void { + allocator.free(ptr[0..size]); +} + +// ============================================================ +// Library Info +// ============================================================ + +/// Returns the library version (for JS host compatibility checks). +export fn wasm_version() u32 { + return 2; // Phase 2: WebRTC transport support +} + +// ============================================================ +// P2P Lifecycle +// ============================================================ + +/// Initialize a new P2P instance. Returns instance ID (0..3) or -1 on error. +export fn wasm_p2p_init(listen_port: u16) i32 { + for (&instances, 0..) |*slot, i| { + if (slot.* == null) { + const p2p_ptr = allocator.create(P2P) catch return -1; + + var config = P2PConfig.default(); + config.network.listen_port = listen_port; + // Enable Noise encryption for secure WebRTC channels + config.network.enable_noise_encryption = true; + // Larger event queue for file transfer (many chunks in flight) + config.events.max_event_queue = 100_000; + + p2p_ptr.* = P2P.init(allocator, config) catch { + allocator.destroy(p2p_ptr); + return -1; + }; + // Lightweight WASM start: init only the subsystems needed for messaging. + // We can't call p2p.start() because it initializes POSIX-dependent + // components (sockets, discovery, TURN, etc.). + wasmStartEssentials(p2p_ptr) catch { + p2p_ptr.deinit(); + allocator.destroy(p2p_ptr); + return -1; + }; + slot.* = .{ + .p2p = p2p_ptr, + .channels = WasmChannelManager.init(allocator), + }; + return @intCast(i); + } + } + return -1; +} + +/// Process pending network I/O. Must be called from JS setInterval (~16ms). +export fn wasm_p2p_update(instance_id: i32) void { + const inst = getInstance(instance_id) orelse return; + inst.p2p.update() catch {}; + + // Advance pending Noise handshakes + for (&inst.pending_handshakes) |*slot| { + const hs = slot.* orelse continue; + + const result = hs.secure.advanceHandshake() catch |err| { + std.log.warn("Noise handshake failed for channel {d}: {} — registering without Noise", .{ hs.channel_id, err }); + hs.secure.cleanupHandshake(); + allocator.destroy(hs.secure); + inst.p2p.addPeerConnectionWithTransport(hs.peer_id, hs.transport_ptr.transport()) catch {}; + slot.* = null; + continue; + }; + + switch (result) { + .complete => { + // Handshake done — register with Noise encryption + inst.p2p.addPeerConnectionWithTransportSecure( + hs.peer_id, + hs.transport_ptr.transport(), + hs.secure, + ) catch |err| { + std.log.err("Failed to register Noise-encrypted channel {d}: {}", .{ hs.channel_id, err }); + hs.secure.cleanupHandshake(); + allocator.destroy(hs.secure); + inst.p2p.addPeerConnectionWithTransport(hs.peer_id, hs.transport_ptr.transport()) catch {}; + }; + std.log.info("WebRTC channel {d} Noise handshake completed", .{hs.channel_id}); + slot.* = null; + }, + .progress, .would_block => {}, // Will retry next tick + } + } +} + +/// Shut down and free a P2P instance. +export fn wasm_p2p_deinit(instance_id: i32) void { + if (instance_id < 0 or instance_id >= MAX_INSTANCES) return; + const idx: usize = @intCast(instance_id); + if (instances[idx]) |*inst| { + // Clean up pending handshakes + for (&inst.pending_handshakes) |*slot| { + if (slot.*) |hs| { + hs.secure.cleanupHandshake(); + allocator.destroy(hs.secure); + slot.* = null; + } + } + inst.channels.deinit(); + inst.p2p.deinit(); + allocator.destroy(inst.p2p); + instances[idx] = null; + } +} + +// ============================================================ +// Messaging +// ============================================================ + +/// Send a message to a peer. Returns 0 on success, -1 on error. +/// peer_id_ptr points to a 32-byte PeerId in WASM memory. +export fn wasm_p2p_send( + instance_id: i32, + peer_id_ptr: [*]const u8, + app_id: u8, + data_ptr: [*]const u8, + data_len: usize, +) i32 { + if (getInstance(instance_id)) |inst| { + const pid = network.peer.PeerId{ .bytes = peer_id_ptr[0..32].* }; + _ = inst.p2p.sendMessage(pid, app_id, data_ptr[0..data_len]) catch return -1; + return 0; + } + return -1; +} + +// ============================================================ +// WebRTC DataChannel Callbacks (JS → WASM) +// +// These are called by the JS host when WebRTC DataChannel events occur. +// Routes to WasmChannelManager which manages per-channel transports. +// ============================================================ + +/// Called when a DataChannel opens (connection established). +/// Starts a Noise handshake if encryption is enabled, otherwise registers directly. +/// is_initiator: 1 if this peer created the WebRTC offer, 0 if responder. +export fn wasm_on_datachannel_open(instance_id: i32, channel_id: u32, is_initiator: u32) void { + const inst = getInstance(instance_id) orelse return; + const transport_ptr = inst.channels.onChannelOpen(channel_id) orelse return; + const peer_id = peerIdFromChannelId(channel_id); + + // Try Noise handshake if keypair available + const keypair = inst.p2p.getNoiseKeyPair() orelse { + // No Noise keypair — register directly (DTLS-only) + inst.p2p.addPeerConnectionWithTransport(peer_id, transport_ptr.transport()) catch |err| { + std.log.err("Failed to register WebRTC channel {d}: {}", .{ channel_id, err }); + return; + }; + std.log.info("WebRTC channel {d} registered (DTLS only)", .{channel_id}); + return; + }; + + // Allocate SecureConnection and start non-blocking handshake + const secure = allocator.create(SecureConnection) catch { + std.log.err("Failed to allocate SecureConnection for channel {d}", .{channel_id}); + inst.p2p.addPeerConnectionWithTransport(peer_id, transport_ptr.transport()) catch {}; + return; + }; + secure.initWithTransport(transport_ptr.transport(), keypair, allocator); + + const role: noise.Role = if (is_initiator != 0) .initiator else .responder; + secure.startHandshake(role) catch |err| { + std.log.err("Failed to start Noise handshake for channel {d}: {}", .{ channel_id, err }); + allocator.destroy(secure); + inst.p2p.addPeerConnectionWithTransport(peer_id, transport_ptr.transport()) catch {}; + return; + }; + + // Store pending handshake — will be advanced in wasm_p2p_update + for (&inst.pending_handshakes) |*slot| { + if (slot.* == null) { + slot.* = .{ + .channel_id = channel_id, + .peer_id = peer_id, + .transport_ptr = transport_ptr, + .secure = secure, + }; + std.log.info("WebRTC channel {d} Noise handshake started (initiator={})", .{ channel_id, is_initiator != 0 }); + return; + } + } + + // No slots available — fall back to DTLS-only + std.log.warn("No pending handshake slots for channel {d}, registering without Noise", .{channel_id}); + secure.cleanupHandshake(); + allocator.destroy(secure); + inst.p2p.addPeerConnectionWithTransport(peer_id, transport_ptr.transport()) catch {}; +} + +fn peerIdFromChannelId(channel_id: u32) network.peer.PeerId { + const Blake2b256 = std.crypto.hash.blake2.Blake2b256; + var input: [4]u8 = @bitCast(channel_id); + var hash: [32]u8 = undefined; + Blake2b256.hash(&input, &hash, .{}); + return network.peer.PeerId{ .bytes = hash }; +} + +/// Called when a message arrives on a DataChannel. +export fn wasm_on_datachannel_message( + instance_id: i32, + channel_id: u32, + data_ptr: [*]const u8, + data_len: usize, +) void { + if (getInstance(instance_id)) |inst| { + inst.channels.onChannelMessage(channel_id, data_ptr[0..data_len]); + } +} + +/// Called when a DataChannel closes. +export fn wasm_on_datachannel_close(instance_id: i32, channel_id: u32) void { + const inst = getInstance(instance_id) orelse return; + + // Cancel any pending handshake for this channel + cancelPendingHandshake(inst, channel_id); + + inst.channels.onChannelClose(channel_id); +} + +/// Called when a DataChannel encounters an error. +export fn wasm_on_datachannel_error(instance_id: i32, channel_id: u32) void { + const inst = getInstance(instance_id) orelse return; + + // Cancel any pending handshake for this channel + cancelPendingHandshake(inst, channel_id); + + inst.channels.onChannelError(channel_id); +} + +fn cancelPendingHandshake(inst: *WasmInstance, channel_id: u32) void { + for (&inst.pending_handshakes) |*slot| { + if (slot.*) |hs| { + if (hs.channel_id == channel_id) { + hs.secure.cleanupHandshake(); + allocator.destroy(hs.secure); + slot.* = null; + return; + } + } + } +} + +// ============================================================ +// Channel Query (JS → WASM) +// ============================================================ + +/// Returns the number of active channels for an instance. +export fn wasm_channel_count(instance_id: i32) i32 { + if (getInstance(instance_id)) |inst| { + var count: i32 = 0; + for (inst.channels.channels) |slot| { + if (slot != null) count += 1; + } + return count; + } + return 0; +} + +/// Get the P2P PeerId bytes for a given channel ID. +/// Writes 32 bytes to out_ptr. Returns 0 on success, -1 if channel not found. +export fn wasm_get_peer_id_for_channel(instance_id: i32, channel_id: u32, out_ptr: [*]u8) i32 { + _ = instance_id; + const peer_id = peerIdFromChannelId(channel_id); + @memcpy(out_ptr[0..32], &peer_id.bytes); + return 0; +} + +// ============================================================ +// Event Polling (WASM → JS) +// +// JS calls this in its update loop to drain events from the P2P library. +// Events are serialized as: [type:1][payload_len:4 LE][payload:N] +// Returns the total bytes written, or 0 if no events pending. +// ============================================================ + +/// Poll for the next event. Returns bytes written to buf, or 0 if none. +/// +/// Event format: [event_type:1][payload...] +/// message_received (type=1): [1][app_id:1][peer_id:32][data:N] +/// peer_connected (type=2): [2][peer_id:32] +/// peer_disconnected(type=3): [3][peer_id:32] +export fn wasm_poll_event(instance_id: i32, buf_ptr: [*]u8, buf_len: usize) i32 { + if (getInstance(instance_id)) |inst| { + var evt = inst.p2p.getNextEvent() orelse return 0; + defer evt.deinit(); + + const buf = buf_ptr[0..buf_len]; + + switch (evt.data) { + .message_received => |msg| { + // [type:1][app_id:1][peer_id:32][data:N] + const header_len: usize = 1 + 1 + 32; + const total = header_len + msg.data.len; + if (total > buf.len) { + std.log.warn("wasm_poll_event: message_received event too large ({} > {}), dropping", .{ total, buf.len }); + return 0; // buffer too small — event is lost (already dequeued) + } + buf[0] = 1; // event type: message_received + buf[1] = msg.message_type; + @memcpy(buf[2..34], &msg.source.bytes); + @memcpy(buf[34..][0..msg.data.len], msg.data); + return @intCast(total); + }, + .peer_connected => |pc| { + if (buf.len < 33) return 0; + buf[0] = 2; + @memcpy(buf[1..33], &pc.peer_id.bytes); + return 33; + }, + .peer_disconnected => |pd| { + if (buf.len < 33) return 0; + buf[0] = 3; + @memcpy(buf[1..33], &pd.peer_id.bytes); + return 33; + }, + .file_shared => |fs_evt| { + // [type:4][session_id:8 LE][path_len:4 LE][path:N] + const path = fs_evt.file_path; + const total = 1 + 8 + 4 + path.len; + if (total > buf.len) return 0; + buf[0] = 4; // event type: file_shared + std.mem.writeInt(u64, buf[1..9], fs_evt.session_id, .little); + std.mem.writeInt(u32, buf[9..13], @intCast(path.len), .little); + @memcpy(buf[13..][0..path.len], path); + return @intCast(total); + }, + .file_download_started => |ds_evt| { + // [type:5][session_id:8 LE][name_len:4 LE][name:N] + const name = ds_evt.file_name; + const total = 1 + 8 + 4 + name.len; + if (total > buf.len) return 0; + buf[0] = 5; // event type: file_download_started + std.mem.writeInt(u64, buf[1..9], ds_evt.session_id, .little); + std.mem.writeInt(u32, buf[9..13], @intCast(name.len), .little); + @memcpy(buf[13..][0..name.len], name); + return @intCast(total); + }, + .file_download_completed => |dc_evt| { + // [type:6][session_id:8 LE] + if (buf.len < 9) return 0; + buf[0] = 6; // event type: file_download_completed + std.mem.writeInt(u64, buf[1..9], dc_evt.session_id, .little); + return 9; + }, + .file_download_failed => |df_evt| { + // [type:7][session_id:8 LE] + if (buf.len < 9) return 0; + buf[0] = 7; // event type: file_download_failed + std.mem.writeInt(u64, buf[1..9], df_evt.session_id, .little); + return 9; + }, + else => return 0, // skip events we don't serialize + } + } + return 0; +} + +// ============================================================ +// File Transfer (JS → WASM) +// ============================================================ + +/// Share a file (make it available for peers to download). +/// path_ptr/path_len: virtual file path in the WASM filesystem. +/// Returns session_id (>0) on success, -1 on error. +export fn wasm_file_share(instance_id: i32, path_ptr: [*]const u8, path_len: usize) i64 { + if (getInstance(instance_id)) |inst| { + const path = path_ptr[0..path_len]; + std.log.info("wasm_file_share: sharing '{s}' (len={})", .{ path, path_len }); + const session_id = inst.p2p.addFile(path) catch |err| { + std.log.err("wasm_file_share: addFile failed: {}", .{err}); + return -1; + }; + std.log.info("wasm_file_share: addFile ok, session_id={}", .{session_id}); + inst.p2p.startSharing(session_id) catch |err| { + std.log.err("wasm_file_share: startSharing failed: {}", .{err}); + return -1; + }; + return @intCast(session_id); + } + return -1; +} + +/// Accept a file and start downloading. +/// name_ptr/name_len: file name. +/// size: total file size. +/// piece_count: number of pieces. +/// output_ptr/output_len: output virtual path. +/// Returns session_id (>0) on success, -1 on error. +export fn wasm_file_download( + instance_id: i32, + name_ptr: [*]const u8, + name_len: usize, + size: u64, + piece_count: u32, + output_ptr: [*]const u8, + output_len: usize, +) i64 { + if (getInstance(instance_id)) |inst| { + const metadata = FileMetadata{ + .name = name_ptr[0..name_len], + .size = size, + .piece_count = piece_count, + .piece_hashes = &.{}, // Populated by protocol exchange + .created_at = 0, + .modified_at = 0, + }; + const output_path = output_ptr[0..output_len]; + const session_id = inst.p2p.downloadFile(metadata, output_path) catch return -1; + return @intCast(session_id); + } + return -1; +} + +/// Stop sharing a file session. +/// Returns 0 on success, -1 on error. +export fn wasm_file_stop(instance_id: i32, session_id: u64) i32 { + if (getInstance(instance_id)) |inst| { + inst.p2p.stopSharing(session_id) catch return -1; + return 0; + } + return -1; +}