webrtc-transport #6

Open
mdt wants to merge 13 commits from webrtc-transport into main
111 changed files with 18459 additions and 1374 deletions
Showing only changes of commit e19797b4e4 - Show all commits

1118
browser/demo/demo.js Normal file

File diff suppressed because it is too large Load Diff

86
browser/demo/index.html Normal file
View File

@@ -0,0 +1,86 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>zig-p2p Browser Demo</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: system-ui, sans-serif; max-width: 720px; margin: 2rem auto; padding: 0 1rem; }
h1 { margin-bottom: 1rem; }
.section { margin-bottom: 1.5rem; }
label { font-weight: 600; display: block; margin-bottom: .25rem; }
input, button { font-size: .95rem; padding: .4rem .6rem; }
input[type="text"] { width: 100%; margin-bottom: .5rem; }
button { cursor: pointer; margin-right: .5rem; }
#status { padding: .5rem; border-radius: 4px; background: #f0f0f0; font-family: monospace; font-size: .85rem; }
#log { height: 300px; overflow-y: auto; border: 1px solid #ccc; border-radius: 4px; padding: .5rem; font-family: monospace; font-size: .82rem; background: #fafafa; }
.log-entry { padding: 2px 0; border-bottom: 1px solid #eee; }
.log-entry.sent { color: #0066cc; }
.log-entry.recv { color: #009900; }
.log-entry.info { color: #666; }
.log-entry.error { color: #cc0000; }
#transferList { margin-top: .75rem; }
.transfer-entry { border: 1px solid #ddd; border-radius: 6px; padding: .6rem .8rem; margin-bottom: .5rem; background: #fafafa; }
.transfer-entry .te-header { display: flex; justify-content: space-between; align-items: center; font-size: .85rem; margin-bottom: .25rem; }
.transfer-entry .te-header .te-label { font-weight: 600; }
.transfer-entry .te-header .te-status { color: #e67e00; font-weight: 600; }
.transfer-entry .te-info { font-family: monospace; font-size: .82rem; color: #555; margin-bottom: .3rem; }
.progress-bar { height: 14px; background: #e0e0e0; border-radius: 7px; overflow: hidden; }
.progress-fill { height: 100%; background: #4caf50; border-radius: 7px; transition: width .15s; }
.progress-fill.paused { background: #e67e00; }
.progress-fill.completed { background: #2196f3; }
.transfer-controls { margin-top: .35rem; }
.transfer-controls button { font-size: .8rem; padding: .2rem .5rem; margin-right: .3rem; cursor: pointer; }
.cancel-btn { color: #cc0000; border-color: #cc0000; }
.transfer-entry.completed { background: #f0f8f0; border-color: #a0d0a0; }
.transfer-entry.completed a { color: #0066cc; font-weight: 600; }
</style>
</head>
<body>
<h1>zig-p2p Browser Demo</h1>
<div class="section" id="status">
Status: <span id="statusText">Not connected</span> |
Peer ID: <span id="peerId">—</span> |
Channels: <span id="channels">0</span>
</div>
<div class="section">
<label>Signaling Server</label>
<input type="text" id="signalingUrl" value="ws://localhost:8080">
<button id="connectBtn" onclick="doConnect()">Connect</button>
<button id="disconnectBtn" onclick="doDisconnect()" disabled>Disconnect</button>
</div>
<div class="section">
<label>Connect to Peer</label>
<input type="text" id="remotePeerId" placeholder="Enter remote peer ID">
<button id="peerBtn" onclick="doConnectPeer()" disabled>Connect to Peer</button>
</div>
<div class="section">
<label>Send Message</label>
<input type="text" id="msgInput" placeholder="Type a message..." onkeydown="if(event.key==='Enter')doSend()">
<button id="sendBtn" onclick="doSend()" disabled>Send</button>
</div>
<div class="section">
<label>File Transfer</label>
<input type="file" id="fileInput">
<button id="shareBtn" onclick="doShareFile()" disabled>Share File</button>
<div id="fileStatus" style="margin-top:.5rem;font-family:monospace;font-size:.85rem"></div>
<div id="fileOffers" style="margin-top:.5rem"></div>
<div id="transferList"></div>
</div>
<div class="section">
<label>Log</label>
<div id="log"></div>
<button onclick="document.getElementById('log').innerHTML=''" style="margin-top:.5rem">Clear</button>
<button onclick="navigator.clipboard.writeText(document.getElementById('log').innerText).then(()=>{this.textContent='Copied!';setTimeout(()=>this.textContent='Copy',1500)})" style="margin-top:.5rem">Copy</button>
</div>
<script type="module" src="demo.js"></script>
</body>
</html>

1
browser/demo/zig-p2p.wasm Symbolic link
View File

@@ -0,0 +1 @@
/Users/mdt./Projects/zig-p2p/zig-out/bin/zig-p2p.wasm

331
browser/host/file-host.js Normal file
View File

@@ -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<number, { data: Uint8Array, pos: number, name: string, readOnly: boolean }>} */
#files = new Map();
/** @type {number} */
#nextId = 1;
/** @type {Map<string, Uint8Array>} virtual path -> materialized file data */
#registered = new Map();
/** @type {Map<string, File>} virtual path -> browser File object (lazy, not loaded) */
#browserFiles = new Map();
/** @type {Set<string>} 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<void>}
*/
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<Uint8Array>}
*/
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<string, Function>}
*/
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),
};
}
}

16
browser/host/package.json Normal file
View File

@@ -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"
]
}

View File

@@ -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<string, Function>} 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;
},
};
}

137
browser/host/signaling.js Normal file
View File

@@ -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<string, Function[]>} */
#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;
}
}
}

323
browser/host/webrtc-host.js Normal file
View File

@@ -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<number, RTCDataChannel>} channel_id → DataChannel */
#channels = new Map();
/** @type {Map<number, boolean>} channelId → true if we created the offer */
#channelRoles = new Map();
/** @type {Map<string, RTCPeerConnection>} 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<number>} 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);
};
}
}

461
browser/host/zig-p2p.js Normal file
View File

@@ -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<number, number>} 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<ZigP2P>}
*/
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<number>} 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;
}
}
}

View File

@@ -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
}
}
}
}
}

View File

@@ -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"
}
}

View File

@@ -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<string, WebSocket>} peerId → WebSocket */
const peers = new Map();
/** @type {Map<WebSocket, PeerState>} */
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);

571
src/wasm/main.zig Normal file
View File

@@ -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;
}