add missing ws.js and introduce save check for both sides

This commit is contained in:
Schluffe committed 2026-10-22 23:29:55 +02:00
1 parent ff7b84af02
commit 1bfeb9843a
4 files changed
+189 -37

No files matched your search

+42 -25
View File
@@ -29,8 +29,8 @@ export type Check = { local: string; remote: string };
export type Events = {
log: (message: string) => void;
// confirm is only passed on the sender side, the file is sent once it is called.
check: (check: Check, confirm?: () => void) => void;
// Called on both sides, confirm once the user compared the codes and they match.
check: (check: Check, confirm: () => void) => void;
};
function createPeerConnection() {
@@ -93,20 +93,30 @@ function securityCheck(pc: RTCPeerConnection): Check {
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) {
// Resolves once the user compared the codes. Both sides wait for it: the sender sends nothing to a man
// in the middle, the receiver accepts no file from one.
function connected(pc: RTCPeerConnection, via: string, events: Events) {
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));
events.log('waiting for the security check');
return new Promise<void>((resolve) => events.check(securityCheck(pc), resolve));
}
// The receiver answers with { read } progress, { done } once the download manager read the last
// byte, or { error } when its download was cancelled or failed.
async function sendFile(pc: RTCPeerConnection, channel: RTCDataChannel, file: File, events: Events) {
// Sends once checked resolved and the receiver confirmed its own check with { ok }. Then it answers
// with { read } progress, { done } once the download manager read the last byte, or { error } when
// its download was cancelled or failed.
async function sendFile(
pc: RTCPeerConnection,
channel: RTCDataChannel,
file: File,
events: Events,
checked: Promise<void>,
) {
if (channel.readyState !== 'open') {
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
}
let read = 0;
let accepted = false;
let sending = false;
let stopped = false;
// Every event the send loop can wait for calls this.
let wake = () => {};
@@ -118,6 +128,9 @@ async function sendFile(pc: RTCPeerConnection, channel: RTCDataChannel, file: Fi
};
channel.onmessage = ({ data }) => {
const message = JSON.parse(data);
if (message.ok) accepted = true;
// Before that, nothing else can come from a receiver that passed its check.
else if (!sending) return;
if (message.read) read = message.read;
if (message.done) {
events.log('delivered');
@@ -132,6 +145,12 @@ async function sendFile(pc: RTCPeerConnection, channel: RTCDataChannel, file: Fi
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && stop('connection lost'));
channel.addEventListener('bufferedamountlow', () => wake());
await checked;
if (!accepted && !stopped) events.log("waiting for the receiver's security check");
while (!stopped && !accepted) await new Promise<void>((resolve) => (wake = resolve));
if (stopped) return;
sending = true;
events.log(`sending ${file.name} (${file.size} bytes)`);
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
@@ -188,11 +207,13 @@ async function holdWorker() {
return { frame, worker };
}
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events) {
// Accepts nothing until checked resolved, then tells the sender with { ok }.
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, checked: Promise<void>) {
const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = [];
let meta: { name: string; size: number } | undefined;
let received = 0;
let confirmed = false;
let ended = false;
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
let worker: Promise<ServiceWorker | void> = Promise.resolve();
@@ -257,9 +278,15 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
}, (error) => fail(String(error)));
}
checked.then(() => {
confirmed = true;
reply({ ok: true });
events.log('waiting for the sender');
});
channel.binaryType = 'arraybuffer';
channel.onmessage = ({ data }) => {
if (ended) return;
if (ended || !confirmed) return;
if (typeof data === 'string') {
meta = JSON.parse(data);
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`);
@@ -287,10 +314,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
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(pc, channel, file, events);
};
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, 'manual exchange', events));
await pc.setLocalDescription();
await gatherIce(pc);
@@ -303,10 +327,7 @@ export async function createOffer(file: File, events: Events) {
export async function answerOffer(offer: string, events: Events) {
await downloadsReady(events);
const pc = createPeerConnection();
pc.ondatachannel = ({ channel }) => {
connected(pc, 'manual exchange', events);
receiveFile(pc, channel, events);
};
pc.ondatachannel = ({ channel }) => receiveFile(pc, channel, events, connected(pc, 'manual exchange', events));
await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) });
await pc.setLocalDescription();
await gatherIce(pc);
@@ -332,10 +353,7 @@ export async function sendViaTracker(file: File, events: Events) {
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(peer, channel, file, events);
};
peer.ondatachannel = ({ channel }) => sendFile(peer, channel, file, events, connected(peer, url, events));
await peer.setRemoteDescription(msg.offer);
await peer.setLocalDescription();
await gatherIce(peer);
@@ -365,9 +383,8 @@ export async function receiveViaTracker(code: string, events: Events) {
channel.onopen = () => {
if (isConnected) return pc.close();
isConnected = true;
connected(pc, url, events);
receiveFile(pc, channel, events, connected(pc, url, events));
};
receiveFile(pc, channel, events);
pc.setLocalDescription()
.then(() => gatherIce(pc))