Add file transfer PoC with manual and tracker signaling
- Core in src/main.ts: manual SDP copy/paste exchange (default, no tracker) and optional WebTorrent tracker signaling, STUN opt-out - Fingerprint security check, sender confirms before sending - ICE gathering stops after the first STUN result (5 s hard cap) - Receiver writes to OPFS via an inline dedicated worker instead of RAM - Playwright e2e suite across Chromium/Firefox and all signaling modes, opt-in 2.5 GiB transfer test (pnpm test:large) - TODO.md with review findings and the service worker plan Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
24307eb96a
commit
aea75fff92
8 files changed
+670
-4
No files matched your search
+116
-2
@@ -1,10 +1,124 @@
|
||||
<script setup lang="ts">
|
||||
const message = 'Hello, world!';
|
||||
import { reactive, ref } from 'vue';
|
||||
import {
|
||||
answerOffer,
|
||||
createOffer,
|
||||
receiveViaTracker,
|
||||
sendViaTracker,
|
||||
settings as coreSettings,
|
||||
type Check,
|
||||
type Events,
|
||||
} from './main';
|
||||
|
||||
// Same object as the core's, so the core sees every change.
|
||||
const settings = reactive(coreSettings);
|
||||
|
||||
const file = ref<File>();
|
||||
const offer = ref('');
|
||||
const answerInput = ref('');
|
||||
const sendCode = ref('');
|
||||
|
||||
const offerInput = ref('');
|
||||
const answer = ref('');
|
||||
const receiveCode = ref('');
|
||||
|
||||
const check = ref<Check>();
|
||||
const confirmSend = ref<() => void>();
|
||||
const download = ref<{ name: string; url: string }>();
|
||||
const log = ref<string[]>([]);
|
||||
|
||||
const events: Events = {
|
||||
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
|
||||
file: (name, url) => (download.value = { name, url }),
|
||||
check: (result, confirm) => {
|
||||
check.value = result;
|
||||
confirmSend.value = confirm;
|
||||
},
|
||||
};
|
||||
|
||||
function onConfirm() {
|
||||
confirmSend.value?.();
|
||||
confirmSend.value = undefined;
|
||||
}
|
||||
|
||||
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
||||
|
||||
function onPick(event: Event) {
|
||||
file.value = (event.target as HTMLInputElement).files?.[0];
|
||||
}
|
||||
|
||||
async function onCreateOffer() {
|
||||
const result = await createOffer(file.value!, events);
|
||||
offer.value = result.offer;
|
||||
acceptAnswer = result.accept;
|
||||
}
|
||||
|
||||
function onAcceptAnswer() {
|
||||
acceptAnswer?.(answerInput.value);
|
||||
}
|
||||
|
||||
async function onCreateAnswer() {
|
||||
answer.value = await answerOffer(offerInput.value, events);
|
||||
}
|
||||
|
||||
async function onShare() {
|
||||
sendCode.value = await sendViaTracker(file.value!, events);
|
||||
}
|
||||
|
||||
function onReceive() {
|
||||
receiveViaTracker(receiveCode.value, events);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main>
|
||||
<h1>HellCon</h1>
|
||||
<p>{{ message }}</p>
|
||||
|
||||
<label>
|
||||
<input id="stun" v-model="settings.stun" type="checkbox" />
|
||||
Use STUN
|
||||
</label>
|
||||
|
||||
<h2>Send</h2>
|
||||
<input type="file" @change="onPick" />
|
||||
|
||||
<h3>Manual</h3>
|
||||
<button id="create-offer" :disabled="!file" @click="onCreateOffer">Create offer</button>
|
||||
<template v-if="offer">
|
||||
<p>Offer, send this to the receiver:</p>
|
||||
<textarea id="offer" readonly :value="offer"></textarea>
|
||||
<p>Answer from the receiver:</p>
|
||||
<textarea id="answer-input" v-model="answerInput"></textarea>
|
||||
<button id="accept-answer" @click="onAcceptAnswer">Connect</button>
|
||||
</template>
|
||||
|
||||
<h3>Tracker (optional)</h3>
|
||||
<button id="share" :disabled="!file" @click="onShare">Share via tracker</button>
|
||||
<p v-if="sendCode">Code: <output id="send-code">{{ sendCode }}</output></p>
|
||||
|
||||
<h2>Receive</h2>
|
||||
|
||||
<h3>Manual</h3>
|
||||
<textarea id="offer-input" v-model="offerInput" placeholder="offer"></textarea>
|
||||
<button id="create-answer" @click="onCreateAnswer">Create answer</button>
|
||||
<template v-if="answer">
|
||||
<p>Answer, send this back to the sender:</p>
|
||||
<textarea id="answer" readonly :value="answer"></textarea>
|
||||
</template>
|
||||
|
||||
<h3>Tracker (optional)</h3>
|
||||
<input id="receive-code" v-model="receiveCode" placeholder="code" />
|
||||
<button id="receive" @click="onReceive">Receive</button>
|
||||
|
||||
<p v-if="check">
|
||||
Security check, you: <output id="check-local">{{ check.local }}</output>, peer:
|
||||
<output id="check-remote">{{ check.remote }}</output>. The other side must show the same two codes swapped.
|
||||
<button v-if="confirmSend" id="confirm" @click="onConfirm">Codes match, send</button>
|
||||
</p>
|
||||
|
||||
<p v-if="download"><a id="download" :href="download.url" :download="download.name">{{ download.name }}</a></p>
|
||||
|
||||
<h2>Log</h2>
|
||||
<pre id="log">{{ log.join('\n') }}</pre>
|
||||
</main>
|
||||
</template>
|
||||
+294
@@ -2,4 +2,298 @@ import { createApp } from 'vue';
|
||||
import App from './App.vue';
|
||||
import './style.css';
|
||||
|
||||
export const TRACKERS = ['wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com'];
|
||||
|
||||
export const STUN_SERVERS = [
|
||||
'stun:stun.pagequit.net:3478',
|
||||
'stun:stun.cloudflare.com:3478',
|
||||
'stun:stun.l.google.com:19302',
|
||||
'stun:stun.nextcloud.com:443',
|
||||
];
|
||||
|
||||
// Without STUN only local addresses are offered: works on the same network or VPN, contacts nobody.
|
||||
export const settings = { stun: true };
|
||||
|
||||
const CHUNK_SIZE = 16 * 1024;
|
||||
const MAX_BUFFERED = 1024 * 1024;
|
||||
const ICE_GRACE = 300;
|
||||
const ICE_TIMEOUT = 5000;
|
||||
|
||||
export type Check = { local: string; remote: string };
|
||||
|
||||
export type Events = {
|
||||
log: (message: string) => void;
|
||||
file: (name: string, url: string) => void;
|
||||
// confirm is only passed on the sender side, the file is sent once it is called.
|
||||
check: (check: Check, confirm?: () => void) => void;
|
||||
};
|
||||
|
||||
function createPeerConnection() {
|
||||
return new RTCPeerConnection({ iceServers: settings.stun ? [{ urls: STUN_SERVERS }] : [] });
|
||||
}
|
||||
|
||||
function randomBinary(length: number) {
|
||||
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
|
||||
}
|
||||
|
||||
function randomCode() {
|
||||
return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 1_000_000).padStart(6, '0');
|
||||
}
|
||||
|
||||
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code.
|
||||
async function infoHash(code: string) {
|
||||
const digest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`hellcon:${code}`));
|
||||
return String.fromCharCode(...new Uint8Array(digest));
|
||||
}
|
||||
|
||||
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
action: 'announce',
|
||||
info_hash: hash,
|
||||
peer_id: peerId,
|
||||
numwant: 0,
|
||||
uploaded: 0,
|
||||
downloaded: 0,
|
||||
...params,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// The SDP is exchanged only once, so it has to carry the candidates. Gathering only completes after
|
||||
// every STUN server answered or timed out (40 s in Chromium for a silent one), but they all report
|
||||
// the same public address: the first one plus a short grace for the other IP family is enough.
|
||||
async function gatherIce(pc: RTCPeerConnection) {
|
||||
if (pc.iceGatheringState === 'complete') return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(resolve, ICE_TIMEOUT);
|
||||
const done = () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
};
|
||||
pc.addEventListener('icegatheringstatechange', () => {
|
||||
if (pc.iceGatheringState === 'complete') done();
|
||||
});
|
||||
pc.addEventListener('icecandidate', ({ candidate }) => {
|
||||
if (candidate?.type === 'srflx') setTimeout(done, ICE_GRACE);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Anti-MITM check: the first 5 bytes of both DTLS certificate fingerprints. My local code must
|
||||
// equal the peer's remote code and vice versa, otherwise someone interposed on the signaling.
|
||||
function securityCheck(pc: RTCPeerConnection): Check {
|
||||
const short = (sdp = '') =>
|
||||
sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 5).join(' ') ?? '?';
|
||||
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
|
||||
}
|
||||
|
||||
// With confirm, resolves once the user compared the codes, so nothing is sent to a man in the middle.
|
||||
function connected(pc: RTCPeerConnection, via: string, events: Events, confirm = false) {
|
||||
events.log(`connected via ${via}`);
|
||||
if (confirm) events.log('waiting for the security check');
|
||||
return new Promise<void>((resolve) => events.check(securityCheck(pc), confirm ? resolve : undefined));
|
||||
}
|
||||
|
||||
async function sendFile(channel: RTCDataChannel, file: File, events: Events) {
|
||||
if (channel.readyState !== 'open') {
|
||||
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
|
||||
}
|
||||
events.log(`sending ${file.name} (${file.size} bytes)`);
|
||||
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||
channel.send(JSON.stringify({ name: file.name, size: file.size }));
|
||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||
if (channel.bufferedAmount > MAX_BUFFERED) {
|
||||
await new Promise((resolve) => channel.addEventListener('bufferedamountlow', resolve, { once: true }));
|
||||
}
|
||||
channel.send(await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer());
|
||||
}
|
||||
events.log('sent');
|
||||
}
|
||||
|
||||
// Runs in a dedicated worker, because OPFS sync access handles only exist there. It is started from
|
||||
// a Blob URL so the app stays one script, which means it must not use anything outside its body.
|
||||
function storageWorker() {
|
||||
type SyncHandle = { write(data: ArrayBuffer, options: { at: number }): number; flush(): void; close(): void };
|
||||
let handle: SyncHandle;
|
||||
let offset = 0;
|
||||
let queue = Promise.resolve();
|
||||
|
||||
// Opening is async, the queue keeps chunks from overtaking it and each other.
|
||||
self.onmessage = ({ data }: MessageEvent) => {
|
||||
queue = queue
|
||||
.then(async () => {
|
||||
if (data.open) {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
const file = await root.getFileHandle(data.open, { create: true });
|
||||
handle = await (file as unknown as { createSyncAccessHandle(): Promise<SyncHandle> }).createSyncAccessHandle();
|
||||
} else if (data.chunk) {
|
||||
// Over quota some browsers write less instead of throwing.
|
||||
const written = handle.write(data.chunk, { at: offset });
|
||||
offset += written;
|
||||
if (written !== data.chunk.byteLength) throw new Error(`storage full after ${offset} bytes`);
|
||||
} else {
|
||||
handle.flush();
|
||||
handle.close();
|
||||
self.postMessage({ done: true });
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
self.postMessage({ error: String(error) });
|
||||
self.close();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const STORAGE_WORKER = URL.createObjectURL(new Blob([`(${storageWorker})()`], { type: 'text/javascript' }));
|
||||
|
||||
// Received files are written to OPFS instead of RAM and stay there until the next visit, because the
|
||||
// download link reads from them.
|
||||
async function clearStorage() {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
for await (const name of root.keys()) await root.removeEntry(name);
|
||||
}
|
||||
|
||||
function receiveFile(channel: RTCDataChannel, events: Events) {
|
||||
const id = crypto.randomUUID();
|
||||
let meta: { name: string; size: number } | undefined;
|
||||
let worker: Worker | undefined;
|
||||
let received = 0;
|
||||
|
||||
async function stored() {
|
||||
worker!.terminate();
|
||||
const root = await navigator.storage.getDirectory();
|
||||
const file = await (await root.getFileHandle(id)).getFile();
|
||||
events.log('received');
|
||||
events.file(meta!.name, URL.createObjectURL(file));
|
||||
}
|
||||
|
||||
channel.binaryType = 'arraybuffer';
|
||||
channel.onmessage = ({ data }) => {
|
||||
if (typeof data === 'string') {
|
||||
meta = JSON.parse(data);
|
||||
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`);
|
||||
worker = new Worker(STORAGE_WORKER);
|
||||
worker.onmessage = ({ data }) => (data.error ? events.log(`storage failed: ${data.error}`) : stored());
|
||||
worker.postMessage({ open: id });
|
||||
} else {
|
||||
received += data.byteLength;
|
||||
worker!.postMessage({ chunk: data }, [data]);
|
||||
}
|
||||
if (meta && received === meta.size) worker!.postMessage({ done: true });
|
||||
};
|
||||
}
|
||||
|
||||
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
|
||||
// The sender offers, the receiver answers, no tracker involved.
|
||||
export async function createOffer(file: File, events: Events) {
|
||||
const pc = createPeerConnection();
|
||||
const channel = pc.createDataChannel('file');
|
||||
channel.onopen = async () => {
|
||||
await connected(pc, 'manual exchange', events, true);
|
||||
sendFile(channel, file, events);
|
||||
};
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
|
||||
return {
|
||||
offer: btoa(pc.localDescription!.sdp),
|
||||
accept: (answer: string) => pc.setRemoteDescription({ type: 'answer', sdp: atob(answer.trim()) }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function answerOffer(offer: string, events: Events) {
|
||||
const pc = createPeerConnection();
|
||||
pc.ondatachannel = ({ channel }) => {
|
||||
connected(pc, 'manual exchange', events);
|
||||
receiveFile(channel, events);
|
||||
};
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) });
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
|
||||
return btoa(pc.localDescription!.sdp);
|
||||
}
|
||||
|
||||
// Tracker signaling (optional): sender joins the swarm on every tracker and answers the first offer.
|
||||
export async function sendViaTracker(file: File, events: Events) {
|
||||
const code = randomCode();
|
||||
const hash = await infoHash(code);
|
||||
const peerId = randomBinary(20);
|
||||
let pc: RTCPeerConnection | undefined;
|
||||
|
||||
for (const url of TRACKERS) {
|
||||
const ws = new WebSocket(url);
|
||||
ws.onopen = () => {
|
||||
announce(ws, hash, peerId, { left: 0, event: 'started' });
|
||||
events.log(`waiting on ${url}`);
|
||||
};
|
||||
ws.onmessage = async (event) => {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (!msg.offer || pc) return;
|
||||
events.log(`offer via ${url}`);
|
||||
const peer = (pc = createPeerConnection());
|
||||
peer.ondatachannel = async ({ channel }) => {
|
||||
await connected(peer, url, events, true);
|
||||
sendFile(channel, file, events);
|
||||
};
|
||||
await peer.setRemoteDescription(msg.offer);
|
||||
await peer.setLocalDescription();
|
||||
await gatherIce(peer);
|
||||
announce(ws, hash, peerId, {
|
||||
left: 0,
|
||||
to_peer_id: msg.peer_id,
|
||||
offer_id: msg.offer_id,
|
||||
answer: peer.localDescription,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
// Receiver sends one offer per tracker; the first data channel that opens wins.
|
||||
export async function receiveViaTracker(code: string, events: Events) {
|
||||
const hash = await infoHash(code);
|
||||
const peerId = randomBinary(20);
|
||||
let isConnected = false;
|
||||
|
||||
for (const url of TRACKERS) {
|
||||
const pc = createPeerConnection();
|
||||
const channel = pc.createDataChannel('file');
|
||||
const offerId = randomBinary(20);
|
||||
channel.onopen = () => {
|
||||
if (isConnected) return pc.close();
|
||||
isConnected = true;
|
||||
connected(pc, url, events);
|
||||
};
|
||||
receiveFile(channel, events);
|
||||
|
||||
pc.setLocalDescription()
|
||||
.then(() => gatherIce(pc))
|
||||
.then(() => {
|
||||
const ws = new WebSocket(url);
|
||||
ws.onopen = () => {
|
||||
announce(ws, hash, peerId, {
|
||||
left: 1,
|
||||
numwant: 1,
|
||||
event: 'started',
|
||||
offers: [{ offer_id: offerId, offer: pc.localDescription }],
|
||||
});
|
||||
events.log(`looking on ${url}`);
|
||||
};
|
||||
ws.onmessage = (event) => {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.answer && msg.offer_id === offerId) {
|
||||
events.log(`answer via ${url}`);
|
||||
pc.setRemoteDescription(msg.answer);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
clearStorage();
|
||||
|
||||
// Mounted last: App.vue imports the core from this module.
|
||||
createApp(App).mount('#app');
|
||||
Reference in new issue
Block a user