Files
zigp2p/browser/demo/demo.js

1119 lines
37 KiB
JavaScript

/**
* 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<number, Uint8Array>} 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<bigint, { size: number, peerId: Uint8Array, hash?: Uint8Array, transferId: bigint }>} */
const pendingOffers = new Map();
/** @type {Map<bigint, { name: string, size: number, received: Uint8Array, bytesReceived: number, startTime: number, lastActivity: number, senderDone: boolean, hash?: Uint8Array, transferId: bigint }>} */
const incomingFiles = new Map();
/** @type {Map<bigint, { name: string, file: File, channelId: number, transferId: bigint, offset: number, startTime: number, lastActivity: number }>} */
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`;
}