WIP improve UX [snapshot task 2]

This commit is contained in:
Schluffe committed 2026-10-16 15:39:31 +02:00
1 parent 3ae47dde8e
commit cd66321ea6
13 files changed
+703 -87

No files matched your search

+13
View File
@@ -1,5 +1,18 @@
# Changelog # Changelog
## Unreleased
- Keep verified sessions open for “Send another file”, with separate acceptance
and storage for each file.
- Preserve the previous memory download until the next file is accepted.
- Add bounded queues (32 files per side), sending in both directions, per-file
progress and results, queue removal, and incoming-file decline.
- Add explicit Disconnect; setup roles stay locked while connected. Disconnect
aborts unfinished writes while preserving the last completed memory download.
- Upgrade connection/session framing to v3 with per-file identifiers. Both peers
must update; v2 codes are rejected before connection setup.
- Document the hosted-first, serverless UX roadmap.
## [0.0.4] - 2026-10-16 ## [0.0.4] - 2026-10-16
### Added ### Added
+32 -14
View File
@@ -10,7 +10,7 @@ explicit opt-in by both people; no relay is configured automatically.
## How it works ## How it works
1. The sender picks one file and configures STUN (PageQuit by default, Google, 1. The person starting the connection selects one or more files and configures STUN (PageQuit by default, Google,
Cloudflare, a custom provider, or None). They create a code and send it Cloudflare, a custom provider, or None). They create a code and send it
privately to the intended receiver through an authenticated channel. Normal privately to the intended receiver through an authenticated channel. Normal
messenger copy/paste is supported; there is no need to transcribe codes. messenger copy/paste is supported; there is no need to transcribe codes.
@@ -40,22 +40,34 @@ explicit opt-in by both people; no relay is configured automatically.
available storage limits apply. Byte counts must remain safe JavaScript integers available storage limits apply. Byte counts must remain safe JavaScript integers
(at most 2^53 − 1 bytes). Files above 120 MiB have not been tested end to end. (at most 2^53 − 1 bytes). Files above 120 MiB have not been tested end to end.
Cancel, reset, changing the selected file, or switching Send/Receive closes the Once both people verify, either person can add files without new codes or another
connection and aborts unfinished disk writes. Keep the tab open until receipt is fingerprint comparison. Each side can queue up to 32 files (including its active
confirmed. A completed memory download is discarded when you reset or switch. outgoing file). Each direction transfers one file at a time; sending and receiving
Switching browser tabs or apps to copy/paste does not explicitly cancel the can happen simultaneously. Each file has its own progress, receipt and explicit
session, although a browser or mobile OS can suspend a background page. receiver acceptance. **Remove** drops a waiting local queue item; **Decline file**
rejects an incoming offer and lets the sender's queue continue.
**Disconnect** ends the entire session, drops waiting files and aborts unfinished
disk writes. To cancel an already active transfer, disconnect; cancelling only an
active file is not supported. Completed memory downloads remain available after
disconnect. Save a previous memory download before accepting another file;
acceptance replaces it. **Reset** discards the memory download and returns to
setup. Send/Receive chooses who starts the connection and is locked during the
session. Both people can send using the session's file picker.
Keep both tabs open. Switching browser tabs or apps does not explicitly cancel
the session, although browsers and mobile operating systems can suspend pages.
Pending verification/acceptance expires after five minutes; stalled transfers Pending verification/acceptance expires after five minutes; stalled transfers
expire after one minute. The two peers must use this protocol version (v2); expire after one minute. Idle verified sessions stay open. Lost connections need
legacy connection codes are rejected. fresh codes. Both peers must use protocol **v3**; older connection codes are
rejected before connecting. The local HTML supports the same manual flow.
If an answer is rejected as invalid, correct the pasted answer and click Connect If an answer is rejected as invalid, correct the pasted answer and click Connect
again; the sender keeps its existing offer while it is still awaiting an answer. again; the sender keeps its existing offer while it is still awaiting an answer.
After a connection actually closes or fails, use Reset and exchange a **new offer After a connection actually closes or fails, use Reset and exchange a **new offer
and new answer**. Old codes refer to the closed connection and cannot reopen it. and new answer**. Old codes refer to the closed connection and cannot reopen it.
Reset returns the page to its initial ready state. For a local test, open two Reset returns the page to its initial ready state. For a local test, open two
separate browser tabs or windows; switching Send/Receive inside one page cancels separate browser tabs or windows; use Disconnect before changing the setup role. Use the specific error shown in red to diagnose
that page's previous connection. Use the specific error shown in red to diagnose
failures; if a configured STUN server is unreachable, try None for a local test. failures; if a configured STUN server is unreachable, try None for a local test.
### Connection diagnostics and first-version comparison ### Connection diagnostics and first-version comparison
@@ -115,7 +127,7 @@ different relay manually.
TURN credentials stay in the current component's memory; the app does not persist TURN credentials stay in the current component's memory; the app does not persist
them or include them in codes. The relay receives its authentication exchange and them or include them in codes. The relay receives its authentication exchange and
can observe addresses, timing and traffic volume, and may charge for bandwidth. can observe addresses, timing and traffic volume, and may charge for bandwidth.
Resetting, cancelling, completing or failing a connection clears TURN consent; Resetting, cancelling or ending a connection clears TURN consent;
check the option again before creating another relayed connection. check the option again before creating another relayed connection.
File traffic remains DTLS encrypted through the relay. The web host, DNS resolver, File traffic remains DTLS encrypted through the relay. The web host, DNS resolver,
and code-exchange service are also relevant third parties. and code-exchange service are also relevant third parties.
@@ -136,8 +148,9 @@ The app does not upload files to its web host in this implementation; that is a
property of this code, not a guarantee against a host serving different code. property of this code, not a guarantee against a host serving different code.
The protocol accepts one ordered, reliable data channel, bounded metadata and The protocol accepts one ordered, reliable data channel, bounded metadata and
messages, an exact declared byte count, and a single file. It rejects unexpected messages, exact declared byte counts, and at most one accepted file per direction.
states, excess data and duplicate metadata. An acknowledged 1 MiB send window Monotonic per-direction file IDs bind offers, data, and receipts to their files. It rejects unexpected
states, excess data and duplicate metadata. An acknowledged 1 MiB send window per transfer
and a bounded receive queue limit buffering during disk writes. Files are treated and a bounded receive queue limit buffering during disk writes. Files are treated
as opaque downloads; metadata is not rendered as HTML. Encryption does not make as opaque downloads; metadata is not rendered as HTML. Encryption does not make
a file safe to open. These limits reduce denial-of-service exposure but do not a file safe to open. These limits reduce denial-of-service exposure but do not
@@ -208,7 +221,7 @@ bun run dev # open the printed localhost URL in two tabs
Pick a file in the sender tab, choose Receive in the other, and check **Allow a Pick a file in the sender tab, choose Receive in the other, and check **Allow a
TURN relay** in both tabs. Leave **Use the configured relay with temporary TURN relay** in both tabs. Leave **Use the configured relay with temporary
credentials** checked. Exchange codes and compare fingerprints as usual. Reset, credentials** checked. Exchange codes and compare fingerprints as usual. Reset,
failure or completion clears consent, so check it again for each connection. failure or disconnect clears consent, so check it again for each connection.
STUN defaults to the local server; TURN remains opt-in, with direct routes preferred. STUN defaults to the local server; TURN remains opt-in, with direct routes preferred.
```sh ```sh
@@ -308,3 +321,8 @@ Browser compatibility, network connectivity and storage availability vary.
## License ## License
MIT — see `LICENSE`. MIT — see `LICENSE`.
## UX roadmap
See [the hosted-first UX roadmap](docs/ux-roadmap.md) for repeat transfers, file
queues and bidirectional sessions, remembered devices, invitations, and guided setup.
+101
View File
@@ -0,0 +1,101 @@
# Serverless UX roadmap
The hosted HTTPS app is the primary experience. The downloadable HTML must keep
working for basic manual connection and file transfer; it need not match hosted
conveniences. No signaling backend, peer presence service, automatic offline-peer
reconnection, or silent TURN fallback is in scope.
## 1. Send another file on a verified connection — implemented first
Keep the reliable data channel open after a successful receipt. The sender can
choose or drop another file without exchanging codes or confirming fingerprints
again. Require explicit receiver acceptance for each file. Reset counters,
metadata, and storage per file while retaining connection verification. Preserve
a completed memory download until the receiver accepts its replacement or resets.
Keep network settings fixed for the session; relay consent applies to that
connection until disconnect. Reset, disconnect, errors, and tab closure end
the session. Idle completed sessions remain open while both tabs remain available;
a lost connection requires fresh codes.
The first implementation negotiated repeat support within v2. Phase 2 supersedes
that compatibility path with protocol v3; both peers now need the current build.
## 2. Multiple files and transfers in either direction — implemented
Session ownership is independent of the initial Send/Receive setup choice. Setup
tabs stay locked while a session exists. Both people can select or drop multiple
files and add more while transferring. Each local queue is capped at 32 including
its active outgoing file; a rolling list retains the last 50 results.
The arbitration decision is one sequential queue per direction, permitting two
active files total. Simultaneous offers therefore never compete for one global
slot. Monotonic odd/even IDs identify files by originating peer; control frames
and binary chunks carry these IDs. Each file uses the existing bounded window,
receive queue, receipt validation, and storage limits. The receiver accepts or
declines every file separately. Only one incoming memory file is retained.
Remove affects only a waiting local item. Decline rejects an incoming offer before
acceptance and advances the peer's queue. Disconnect cancels the whole session,
clears queues, and aborts unfinished writes in either direction. Cancellation of
an individual active file is intentionally not provided. Completed memory downloads
survive disconnect until Reset or the next acceptance.
Protocol v3 rejects old connection codes before setup. Tests cover simultaneous
queues, empty files, separate acceptance, removal, decline, stale IDs/receipts,
queue caps, storage cancellation, and verification gates. Browser checks exercise
both directions, real bytes, accessibility, streaming downloads, and the local HTML.
## 3. Remember trusted devices
Add opt-in local device identity and a contact list on the hosted app, backed by
browser storage. After authenticated first pairing, offer “Remember this device”
and a local nickname. Store public identities for contacts and protect the local
private identity using available browser cryptographic storage; this does not
protect against compromised app JavaScript. Temporary sessions remain available.
Specify and review mutual proof of identity bound to fresh session information,
both DTLS fingerprints, participant roles, and replay protection before building
automatic verification. Never infer trust from a nickname or saved connection
code. Changed identities require explicit re-verification. Continue requiring
file acceptance. Add contact removal, identity reset, storage-unavailable behavior,
and password-encrypted identity export/import with a reviewed backup format.
Test impersonation, replay, identity changes, wrong backup passwords, storage
loss, and mixed-version peers. Local HTML may remain temporary/manual; do not
block delivery on persistent identity support for file URLs.
## 4. Shareable invitations
For HTTPS, encode fresh offers in URL fragments with an explicit Share/Copy link
action and an import preview. Keep connection details out of query strings and
server paths. Fragments still expose their contents to link recipients and any
service carrying the full link; explain that invitations are private. Clear the
fragment after import. Provide a similarly convenient answer handoff; an answer
exchange remains necessary. Keep pasteable codes as the universal fallback.
Bound and validate payloads, handle stale/incompatible links, and test practical
URL limits across messengers and mobile browsers. Do not promise a short link
without a storage service. Consider compressed payloads and QR only after checking
real payload sizes and decoding limits. Local HTML only needs manual codes.
## 5. Guided connection flow
Present one primary next action across Choose files → Share invitation → Connect
→ Verify → Transfer. Collapse completed setup steps, expose advanced network
settings on demand, and keep relay consent explicit. Show session state separately
from file progress. Distinguish connected, awaiting acceptance, saving, completed,
and disconnected. Provide recovery actions tailored to the actual failure.
Prefer the hosted streaming-download path when supported, retain native disk and
bounded memory fallbacks, and explain browser download completion accurately.
Use accessible focus management, keyboard controls, live status announcements,
and mobile layouts. Validate both first-time and remembered-peer paths, denied
permissions, clipboard/share fallback, browser suspension, and reconnect guidance.
## Delivery order and gates
Deliver in the order above, with a build and relevant protocol/browser checks per
phase. Small contextual UI improvements can accompany each phase. Treat identity
authentication and bidirectional framing as explicit design/review milestones.
No new persistent data or backend is needed for phase 1. Deployments are separate
from implementation; this document is the plan for the remaining phases.
+60 -8
View File
@@ -167,11 +167,14 @@ try {
const downloads = join(profile, 'downloads'); const downloads = join(profile, 'downloads');
await mkdir(downloads); await mkdir(downloads);
await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads }); await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads });
const sender = await page(); const sender = await page(), receiver = await page();
await click(receiver, 'Receive');
for (const size of [0, 1024 * 1024 + 7, 120 * 1024 * 1024]) { for (const size of [0, 1024 * 1024 + 7, 120 * 1024 * 1024]) {
const receiver = await page(); if (size === 0) await connect(sender, receiver, size);
await click(receiver, 'Receive'); else {
await connect(sender, receiver, size); await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size);
await wait(receiver, () => !!document.querySelector('.incoming'));
}
assert.equal(await evaluate(receiver, () => typeof window.showSaveFilePicker), 'undefined'); assert.equal(await evaluate(receiver, () => typeof window.showSaveFilePicker), 'undefined');
await click(receiver, `Receive as download (${size === 0 ? '0 B' : (size / 1024 ** 2).toFixed(1) + ' MiB'})`); await click(receiver, `Receive as download (${size === 0 ? '0 B' : (size / 1024 ** 2).toFixed(1) + ' MiB'})`);
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file')); await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
@@ -190,7 +193,6 @@ try {
} }
assert.equal(bytes, size); assert.equal(bytes, size);
await rm(destination); await rm(destination);
await click(sender, 'Reset');
console.log(`PASS: hosted app streams ${size} bytes to a real browser download without the native save picker; exact file bytes verified.`); console.log(`PASS: hosted app streams ${size} bytes to a real browser download without the native save picker; exact file bytes verified.`);
} }
assert.deepEqual(browserErrors, []); assert.deepEqual(browserErrors, []);
@@ -246,6 +248,53 @@ try {
assert.doesNotMatch(diagnostics, /browser-test\.bin|a=candidate:|a=ice-pwd:|a=fingerprint:|\.local\b/); assert.doesNotMatch(diagnostics, /browser-test\.bin|a=candidate:|a=ice-pwd:|a=fingerprint:|\.local\b/);
console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt.'); console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt.');
console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.'); console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.');
const originalFingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
for (const size of [0, 4097]) {
const previousDownload = await evaluate(receiver, () => window.__hellcon.element<HTMLAnchorElement>('a.download').href);
await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'another.bin'), size);
await wait(receiver, () => !!document.querySelector('.incoming'));
assert.equal(await evaluate(receiver, () => window.__hellcon.element<HTMLAnchorElement>('a.download').href), previousDownload);
assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Waiting for the receiver to accept the file…');
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)), originalFingerprints);
await click(receiver, 'Receive in memory (up to 64 MiB)');
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
const next = await evaluate(receiver, async () => {
const link = window.__hellcon.element<HTMLAnchorElement>('a.download');
const bytes = new Uint8Array(await (await fetch(link.href)).arrayBuffer());
return { name: link.download, length: bytes.length, valid: bytes.every(byte => byte === 123) };
});
assert.deepEqual(next, { name: 'another.bin', length: size, valid: true });
}
console.log('PASS: consecutive files including an empty file reuse fingerprints, require acceptance, and preserve the previous download until acceptance.');
// Queue two files and send back simultaneously, on the same peer connection.
await evaluate(sender, () => {
const input = window.__hellcon.element<HTMLInputElement>('#file-input');
const files = new DataTransfer();
for (const name of ['decline-me.bin', 'queued.bin', 'remove-me.bin']) files.items.add(new File([new Uint8Array(1024).fill(123)], name));
input.files = files.files; input.dispatchEvent(new Event('change', { bubbles: true }));
});
await evaluate(sender, () => window.__hellcon.element<HTMLButtonElement>('button[aria-label="Remove remove-me.bin"]').click());
await evaluate(receiver, () => window.__hellcon.chooseFile(8193, 'return.bin'));
await wait(sender, () => !!document.querySelector('.incoming'));
await wait(receiver, () => !!document.querySelector('.incoming'));
await click(receiver, 'Decline file');
await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('queued.bin'));
await click(sender, 'Receive in memory (up to 64 MiB)');
await click(receiver, 'Receive in memory (up to 64 MiB)');
await wait(sender, () => document.querySelector<HTMLAnchorElement>('a.download')?.download === 'return.bin');
await wait(receiver, () => document.querySelector<HTMLAnchorElement>('a.download')?.download === 'queued.bin');
for (const [session, size] of [[sender, 8193], [receiver, 1024]] as const) {
const received = await evaluate(session, async () => {
const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
return { length: bytes.length, valid: bytes.every(byte => byte === 123) };
});
assert.deepEqual(received, { length: size, valid: true });
await checkAccessibility(session, 'Bidirectional session');
}
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.tabs button')].every(button => (button as HTMLButtonElement).disabled)), true);
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)), originalFingerprints);
console.log('PASS: simultaneous bidirectional transfers, multiple-file queue, removal, decline, exact bytes, and locked setup tabs.');
await click(sender, 'Reset'); await click(receiver, 'Reset'); await click(sender, 'Reset'); await click(receiver, 'Reset');
assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Choose a file to start.'); assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Choose a file to start.');
assert.equal(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), 'Paste the sender’s connection code to start.'); assert.equal(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), 'Paste the sender’s connection code to start.');
@@ -254,14 +303,17 @@ try {
await connect(sender, receiver, 2 * 1024 * 1024); await connect(sender, receiver, 2 * 1024 * 1024);
await click(receiver, 'Choose destination & receive to disk'); await click(receiver, 'Choose destination & receive to disk');
await wait(receiver, () => !!window.__hellcon.releaseWrite); await wait(receiver, () => !!window.__hellcon.releaseWrite);
await click(sender, 'Receive'); await evaluate(sender, () => window.__hellcon.chooseFile(1024, 'pending-at-disconnect.bin'));
assert.equal(await evaluate(sender, () => !!document.querySelector('ul[aria-label="Files waiting to send"]')), true);
await click(sender, 'Disconnect');
assert.equal(await evaluate(sender, () => !!document.querySelector('ul[aria-label="Files waiting to send"]')), false);
await wait(receiver, () => window.__hellcon.aborted); await wait(receiver, () => window.__hellcon.aborted);
assert.equal(await evaluate(receiver, () => !!document.querySelector('a.download')), false); assert.equal(await evaluate(receiver, () => !!document.querySelector('a.download')), false);
await wait(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs=')); await wait(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs='));
assert.match(await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value), /session failed/); assert.match(await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value), /session failed/);
console.log('PASS: privacy-safe candidate/check diagnostics remain available after completion and failure.'); console.log('PASS: privacy-safe candidate/check diagnostics remain available after completion and failure.');
console.log('PASS: switching away from Send closes the connection and aborts the receiver’s pending disk write.'); console.log('PASS: Disconnect closes the connection and aborts the receiver’s pending disk write.');
await click(sender, 'Send'); await click(receiver, 'Reset'); await click(sender, 'Reset'); await click(receiver, 'Reset');
await connect(sender, receiver, 2048); await connect(sender, receiver, 2048);
await click(receiver, 'Receive in memory (up to 64 MiB)'); await click(receiver, 'Receive in memory (up to 64 MiB)');
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file')); await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
+1
View File
@@ -53,6 +53,7 @@ try {
if(bytes.length!==2*1024*1024+7||!bytes.every(b=>b===123))throw new Error('File content mismatch'); if(bytes.length!==2*1024*1024+7||!bytes.every(b=>b===123))throw new Error('File content mismatch');
}else{ }else{
await stage('waiting for receipt');await wait(()=>element('[role=status]').textContent?.includes('confirmed the complete file')); await stage('waiting for receipt');await wait(()=>element('[role=status]').textContent?.includes('confirmed the complete file'));
click('Disconnect');
} }
await post(role+'Result',{ok:true}); await post(role+'Result',{ok:true});
}catch(error){ }catch(error){
+5 -6
View File
@@ -1,9 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'; import { ref } from 'vue';
import SendPanel from './components/SendPanel.vue'; import TransferPanel from './components/TransferPanel.vue';
import ReceivePanel from './components/ReceivePanel.vue';
const mode = ref<'send' | 'receive'>('send'); const mode = ref<'send' | 'receive'>('send');
const sessionActive = ref(false);
const isLocal = location.protocol === 'file:'; const isLocal = location.protocol === 'file:';
const canDownloadApp = import.meta.env.PROD && !isLocal; const canDownloadApp = import.meta.env.PROD && !isLocal;
</script> </script>
@@ -21,12 +21,11 @@ const canDownloadApp = import.meta.env.PROD && !isLocal;
<p v-if="canDownloadApp || isLocal" class="status">For large files in the downloaded local version, use desktop Chrome on the receiving machine and choose “Choose destination &amp; receive to disk”.</p> <p v-if="canDownloadApp || isLocal" class="status">For large files in the downloaded local version, use desktop Chrome on the receiving machine and choose “Choose destination &amp; receive to disk”.</p>
<div class="tabs" role="group" aria-label="Transfer mode"> <div class="tabs" role="group" aria-label="Transfer mode">
<button :class="{ active: mode === 'send' }" :aria-pressed="mode === 'send'" @click="mode = 'send'">Send</button> <button :disabled="sessionActive" :class="{ active: mode === 'send' }" :aria-pressed="mode === 'send'" @click="mode = 'send'">Send</button>
<button :class="{ active: mode === 'receive' }" :aria-pressed="mode === 'receive'" @click="mode = 'receive'">Receive</button> <button :disabled="sessionActive" :class="{ active: mode === 'receive' }" :aria-pressed="mode === 'receive'" @click="mode = 'receive'">Receive</button>
</div> </div>
<SendPanel v-if="mode === 'send'" /> <TransferPanel :key="mode" :sending="mode === 'send'" @session-change="sessionActive = $event" />
<ReceivePanel v-else />
</main> </main>
<footer> <footer>
+119 -49
View File
@@ -5,23 +5,32 @@ import type { FileMetadata, TransferState, FileDestination } from '../lib/transf
import { computed, onBeforeUnmount, ref } from 'vue'; import { computed, onBeforeUnmount, ref } from 'vue';
import NetworkSettings from './NetworkSettings.vue'; import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts'; import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts'; import { MEMORY_LIMIT, validateMetadata } from '../lib/transfer.ts';
import { FileSession, QUEUE_LIMIT, type QueueItem } from '../lib/session.ts';
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts'; import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts'; import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts';
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState; type Step = 'session-ready' | 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session { interface Session {
pc: RTCPeerConnection; pc: RTCPeerConnection;
options: IceOptions; options: IceOptions;
file: File | null;
controller: AbortController; controller: AbortController;
transfer: Transfer | null; transfer: FileSession | null;
diagnostics: ConnectionDiagnostics; diagnostics: ConnectionDiagnostics;
timer?: ReturnType<typeof setTimeout>; timer?: ReturnType<typeof setTimeout>;
} }
const props = defineProps<{ sending?: boolean }>(); const props = defineProps<{ sending?: boolean }>();
const file = ref<File | null>(null); const file = ref<File | null>(null);
const selectedFiles = ref<File[]>([]);
const queuedFiles = ref<QueueItem[]>([]);
const sendState = ref<TransferState | null>(null);
const receiveState = ref<TransferState | null>(null);
const outgoing = ref<FileMetadata | null>(null);
const receiveProgress = ref(0);
const lastDirection = ref<'send' | 'receive'>('send');
const history = ref<string[]>([]);
const emit = defineEmits<{ sessionChange: [active: boolean] }>();
const inputCode = ref(''); const inputCode = ref('');
const outputCode = ref(''); const outputCode = ref('');
const step = ref<Step>('idle'); const step = ref<Step>('idle');
@@ -32,6 +41,9 @@ const verified = ref(false);
const progress = ref(0); const progress = ref(0);
const incoming = ref<FileMetadata | null>(null); const incoming = ref<FileMetadata | null>(null);
const downloadUrl = ref(''); const downloadUrl = ref('');
const downloadName = ref('');
const connected = ref(false);
const choosing = ref(false); const choosing = ref(false);
const dragover = ref(false); const dragover = ref(false);
const diagnosticLines = ref<string[]>([]); const diagnosticLines = ref<string[]>([]);
@@ -45,8 +57,9 @@ const canStreamDownload = supportsStreamingDownload();
const streamedDownload = ref(false); const streamedDownload = ref(false);
let active: Session | null = null; let active: Session | null = null;
let copyTimer: ReturnType<typeof setTimeout> | undefined; let copyTimer: ReturnType<typeof setTimeout> | undefined;
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value)); const busy = computed(() => !['idle', 'closed', 'done', 'session-ready'].includes(step.value));
const status = computed(() => ({ const status = computed(() => ({
'session-ready': 'Connected. Add files to send, or wait for your peer.',
idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.', idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.',
gathering: 'Gathering connection info (up to 30 seconds)…', gathering: 'Gathering connection info (up to 30 seconds)…',
'offer-ready': 'Send your code through an authenticated channel, then paste the answer.', 'offer-ready': 'Send your code through an authenticated channel, then paste the answer.',
@@ -56,7 +69,7 @@ const status = computed(() => ({
'choose-storage': 'Choose how to receive this file.', 'choose-storage': 'Choose how to receive this file.',
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…', sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…', 'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…',
done: props.sending ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : streamedDownload.value ? 'File handed to your browser. Check Downloads for the final save result.' : 'File saved to disk.'), done: lastDirection.value === 'send' ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : streamedDownload.value ? 'File handed to your browser. Check Downloads for the final save result.' : 'File saved to disk.'),
closed: props.sending closed: props.sending
? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.' ? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.'
: 'Ask the sender for a new code and paste it above. Previous codes cannot reopen a closed connection.', : 'Ask the sender for a new code and paste it above. Previous codes cannot reopen a closed connection.',
@@ -64,11 +77,12 @@ const status = computed(() => ({
function revokeDownload() { function revokeDownload() {
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value); if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
downloadUrl.value = ''; downloadUrl.value = ''; downloadName.value = '';
} }
function dispose() { function dispose() {
const old = active; const old = active;
active = null; active = null; connected.value = false; queuedFiles.value = []; emit('sessionChange', false);
managedCredentials.value = null; settings.value.allowTurn = false;
if (!old) return; if (!old) return;
clearTimeout(old.timer); clearTimeout(old.timer);
// Start the snapshot before aborting/closing anything; close the peer after // Start the snapshot before aborting/closing anything; close the peer after
@@ -79,58 +93,98 @@ function dispose() {
old.pc.ondatachannel = old.pc.onconnectionstatechange = null; old.pc.ondatachannel = old.pc.onconnectionstatechange = null;
} }
function reset(keepNetwork = false) { function reset(keepNetwork = false) {
const allowTurn = settings.value.allowTurn;
dispose(); revokeDownload(); clearTimeout(copyTimer); dispose(); revokeDownload(); clearTimeout(copyTimer);
if (keepNetwork) settings.value.allowTurn = allowTurn;
latestDiagnostics = null; diagnosticLines.value = []; latestDiagnostics = null; diagnosticLines.value = [];
managedCredentials.value = null; managedCredentials.value = null;
if (!keepNetwork) settings.value.allowTurn = false; if (!keepNetwork) settings.value.allowTurn = false;
inputCode.value = outputCode.value = error.value = ''; inputCode.value = outputCode.value = error.value = '';
fps.value = incoming.value = null; fps.value = incoming.value = null;
verified.value = copied.value = choosing.value = false; verified.value = copied.value = choosing.value = false;
progress.value = 0; step.value = 'idle'; streamedDownload.value = false; progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; streamedDownload.value = false;
sendState.value = receiveState.value = null; outgoing.value = null; history.value = [];
} }
function fail(session: Session, err: unknown) { function fail(session: Session, err: unknown) {
if (active !== session) return; if (active !== session) return;
session.diagnostics.record('session failed'); session.diagnostics.record('session failed');
dispose(); revokeDownload(); dispose();
managedCredentials.value = null; managedCredentials.value = null;
fps.value = incoming.value = null; fps.value = incoming.value = null;
outputCode.value = ''; verified.value = false; outputCode.value = ''; verified.value = false;
settings.value.allowTurn = false; settings.value.allowTurn = false;
if (sendState.value && sendState.value !== 'done') sendState.value = 'closed';
if (receiveState.value && receiveState.value !== 'done') receiveState.value = 'closed';
error.value = asError(err).message; step.value = 'closed'; error.value = asError(err).message; step.value = 'closed';
} }
function pickFiles(event: Event) { function pickFiles(event: Event) {
const selected = event.target instanceof HTMLInputElement ? event.target.files?.[0] const list = event.target instanceof HTMLInputElement ? event.target.files
: event instanceof DragEvent ? event.dataTransfer?.files[0] : undefined; : event instanceof DragEvent ? event.dataTransfer?.files : null;
if (!selected) return; const files = Array.from(list || []);
reset(); if (!files.length) return;
if (!Number.isSafeInteger(selected.size) || selected.size < 0) { file.value = null; error.value = 'This file’s size cannot be represented accurately.'; return; } try {
file.value = selected; if (files.length > QUEUE_LIMIT) throw new Error(`Queue up to ${QUEUE_LIMIT} files at a time.`);
for (const item of files) validateMetadata({ name: item.name, size: item.size, mime: item.type || '' });
if (active?.transfer) active.transfer.add(files);
else {
if (active) throw new Error('Finish connecting before adding more files.');
selectedFiles.value = files; file.value = files[0]!;
}
error.value = '';
} catch (err) { error.value = asError(err).message; }
if (event.target instanceof HTMLInputElement) event.target.value = '';
} }
function removeQueued(id: number) { active?.transfer?.remove(id); }
function remember(message: string) { history.value = [...history.value.slice(-49), message]; }
function disconnect() {
dispose(); step.value = 'closed';
if (sendState.value && sendState.value !== 'done') sendState.value = 'closed';
if (receiveState.value && receiveState.value !== 'done') receiveState.value = 'closed';
incoming.value = null; outputCode.value = ''; fps.value = null; verified.value = false;
}
function declineFile() { if (!choosing.value) active?.transfer?.decline(); }
function attach(session: Session, channel: RTCDataChannel) { function attach(session: Session, channel: RTCDataChannel) {
if (active !== session) { channel.close(); return; } if (active !== session) { channel.close(); return; }
if (session.transfer || channel.label !== 'hellcon-v2' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) { if (session.transfer || channel.label !== 'hellcon-v3' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
channel.close(); fail(session, new Error('Unexpected data channel.')); return; channel.close(); fail(session, new Error('Unexpected data channel.')); return;
} }
session.transfer = new Transfer(channel, { session.transfer = new FileSession(channel, !!props.sending, {
file: props.sending ? session.file : null, onReady: () => { if (active === session) { connected.value = true; step.value = 'session-ready'; clearTimeout(session.timer); } },
onState: state => { if (active === session) { step.value = state; session.diagnostics.record(`transfer ${state}`); } }, onQueue: items => { if (active === session) queuedFiles.value = items; },
onMeta: meta => { if (active === session) incoming.value = meta; }, onState: (direction, state, meta) => {
onProgress: (bytes, size) => { if (active === session) progress.value = Math.min(99, Math.floor(bytes / Math.max(size, 1) * 100)); },
onComplete: ({ blob }) => {
if (active !== session) return; if (active !== session) return;
progress.value = 100; step.value = state; lastDirection.value = direction;
managedCredentials.value = null; session.diagnostics.record(`transfer ${direction} ${state}`);
settings.value.allowTurn = false; if (state === 'done') session.diagnostics.record('transfer done');
if (blob) downloadUrl.value = URL.createObjectURL(blob); if (direction === 'send') { sendState.value = state; outgoing.value = meta; if (state === 'waiting-accept') progress.value = 0; }
// The receiver leaves the channel open until its completion ACK reaches the sender. else { receiveState.value = state; if (state === 'choose-storage' && meta.name) { incoming.value = meta; receiveProgress.value = 0; streamedDownload.value = false; } }
if (props.sending) dispose(); },
else { onProgress: (direction, bytes, size) => {
clearTimeout(session.timer); if (active !== session) return;
session.timer = setTimeout(() => { if (active === session) dispose(); }, 10000); const percent = Math.min(99, Math.floor(bytes / Math.max(size, 1) * 100));
if (direction === 'send') progress.value = percent; else receiveProgress.value = percent;
},
onComplete: (direction, { blob, meta }) => {
if (active !== session) return;
if (direction === 'send') progress.value = 100; else receiveProgress.value = 100;
remember(`${direction === 'send' ? 'Sent' : 'Received'}: ${meta.name}`);
void session.diagnostics.capture();
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; }
},
onDecline: (direction, meta) => {
if (active !== session) return;
if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; }
remember(`Declined: ${meta.name}`);
if (lastDirection.value === direction) {
const other = direction === 'send' ? receiveState.value : sendState.value;
step.value = other && other !== 'done' ? other : 'session-ready';
lastDirection.value = direction === 'send' ? 'receive' : 'send';
} }
}, },
onClose: () => { if (active === session) disconnect(); },
onError: err => fail(session, err), onError: err => fail(session, err),
}); });
if (props.sending) { session.transfer.add(selectedFiles.value); selectedFiles.value = []; file.value = null; }
if (verified.value) session.transfer.verify(); if (verified.value) session.transfer.verify();
} }
function start() { function start() {
@@ -147,15 +201,16 @@ function start() {
if (latestDiagnostics === diagnostics) diagnosticLines.value = lines; if (latestDiagnostics === diagnostics) diagnosticLines.value = lines;
}); });
latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines]; latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines];
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null, diagnostics }; const session: Session = { pc, options, controller: new AbortController(), transfer: null, diagnostics };
active = session; active = session; emit('sessionChange', true);
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000); session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
pc.ondatachannel = event => attach(session, event.channel); pc.ondatachannel = event => attach(session, event.channel);
pc.onconnectionstatechange = () => { pc.onconnectionstatechange = () => {
if (active !== session) return; if (active !== session) return;
if (['failed', 'closed'].includes(pc.connectionState)) { if (['failed', 'closed'].includes(pc.connectionState)) {
if (step.value === 'done') dispose(); const unfinished = [sendState.value, receiveState.value].some(state => state && state !== 'done' && state !== 'closed');
else fail(session, new Error('Connection failed. Direct connections may be blocked; TURN is available only if both people opt in.')); if (connected.value && !unfinished) disconnect();
else fail(session, new Error('Connection failed. Unfinished files were cancelled. Direct connections may be blocked; TURN is available only if both people opt in.'));
} }
}; };
return session; return session;
@@ -175,7 +230,7 @@ async function createCode() {
session.pc.setConfiguration(iceConfiguration(configured)); session.pc.setConfiguration(iceConfiguration(configured));
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null; managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
const options = { ...session.options, signal: session.controller.signal }; const options = { ...session.options, signal: session.controller.signal };
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v2')); if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options); const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
if (active !== session) return; if (active !== session) return;
outputCode.value = code; outputCode.value = code;
@@ -221,7 +276,7 @@ function verify() {
} }
async function acceptFile(destination: 'disk' | 'memory' | 'download') { async function acceptFile(destination: 'disk' | 'memory' | 'download') {
const session = active; const session = active;
if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return; if (!session?.transfer || !incoming.value || choosing.value || receiveState.value !== 'choose-storage') return;
choosing.value = true; error.value = ''; choosing.value = true; error.value = '';
let writable: FileDestination | undefined; let writable: FileDestination | undefined;
try { try {
@@ -235,6 +290,7 @@ async function acceptFile(destination: 'disk' | 'memory' | 'download') {
writable = await handle.createWritable(); writable = await handle.createWritable();
if (active !== session) { await writable.abort(); return; } if (active !== session) { await writable.abort(); return; }
} }
revokeDownload();
streamedDownload.value = destination === 'download'; streamedDownload.value = destination === 'download';
session.diagnostics.record(`storage ${destination}`); session.diagnostics.record(`storage ${destination}`);
session.transfer.accept(writable); session.transfer.accept(writable);
@@ -252,6 +308,9 @@ async function copy() {
copyTimer = setTimeout(() => { copied.value = false; }, 1500); copyTimer = setTimeout(() => { copied.value = false; }, 1500);
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; } } catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
} }
function stateLabel(state: TransferState | null) {
return state ? ({ verification: 'Connecting', 'waiting-accept': 'Waiting for acceptance', 'choose-storage': 'Choose where to save', sending: 'Sending', receiving: 'Receiving', saving: 'Saving', 'awaiting-receipt': 'Waiting for receipt', done: 'Complete', closed: 'Cancelled' })[state] : 'Declined';
}
function formatBytes(bytes: number) { function formatBytes(bytes: number) {
if (bytes < 1024) return `${bytes} B`; if (bytes < 1024) return `${bytes} B`;
const index = Math.min(5, Math.floor(Math.log(bytes) / Math.log(1024))); const index = Math.min(5, Math.floor(Math.log(bytes) / Math.log(1024)));
@@ -265,21 +324,24 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<template> <template>
<div class="panel"> <div class="panel">
<template v-if="sending"> <template v-if="sending || connected">
<label class="step" for="file-input">Choose one file</label> <label class="step" for="file-input">{{ connected ? 'Add files to send' : 'Choose files' }}</label>
<div class="dropzone" :class="{ dragover }" @dragover.prevent="dragover = true" @dragleave="dragover = false" @drop.prevent="dragover = false; pickFiles($event)"> <div class="dropzone" :class="{ dragover }" @dragover.prevent="dragover = true" @dragleave="dragover = false" @drop.prevent="dragover = false; pickFiles($event)">
<p>Drop a file here or choose one below. Choosing a new file cancels the current connection.</p> <p>Choose or drop files. Each direction sends one file at a time; both people can send on this connection.</p>
<input id="file-input" type="file" @change="pickFiles" /> <input id="file-input" type="file" multiple @change="pickFiles" />
</div> </div>
<p v-if="file" class="file-chip"><span>{{ file.name }}</span><span>{{ formatBytes(file.size) }}</span></p> <p v-if="!connected && selectedFiles.length" class="status">{{ selectedFiles.length }} file(s) selected</p>
<ul v-if="!connected && selectedFiles.length"><li v-for="(item, index) in selectedFiles" :key="index">{{ item.name }} — {{ formatBytes(item.size) }}</li></ul>
<ul v-if="queuedFiles.length" aria-label="Files waiting to send"><li v-for="item in queuedFiles" :key="item.id">{{ item.file.name }} — {{ formatBytes(item.file.size) }} <button @click="removeQueued(item.id)" :aria-label="'Remove ' + item.file.name">Remove</button></li></ul>
<p v-if="outgoing" class="status">Sending: {{ outgoing.name }} — {{ stateLabel(sendState) }} ({{ progress }}%)</p>
</template> </template>
<NetworkSettings v-model="settings" :disabled="busy" :managed-credentials="managedCredentials" /> <NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
<p class="status">Connection codes are not encrypted: they can reveal your IP address and connection details to anyone who sees them. Exchange them privately with your intended peer.</p> <p class="status">Connection codes are not encrypted: they can reveal your IP address and connection details to anyone who sees them. Exchange them privately with your intended peer.</p>
<template v-if="!sending"> <template v-if="!sending">
<label class="step" for="offer-input">Paste the sender’s connection code</label> <label class="step" for="offer-input">Paste the sender’s connection code</label>
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="busy" /> <textarea id="offer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="busy" />
</template> </template>
<button class="primary" :disabled="busy || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button> <button class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<template v-if="outputCode"> <template v-if="outputCode">
<label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label> <label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" /> <textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
@@ -297,7 +359,8 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<p class="status">Compare every byte over an authenticated channel an attacker cannot alter (for example, an in-person comparison). Your fingerprint must match their “Their fingerprint”, and vice versa. If either differs, cancel. Both people must confirm before the filename or contents are sent.</p> <p class="status">Compare every byte over an authenticated channel an attacker cannot alter (for example, an in-person comparison). Your fingerprint must match their “Their fingerprint”, and vice versa. If either differs, cancel. Both people must confirm before the filename or contents are sent.</p>
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Fingerprints confirmed' : 'Both fingerprints match — confirm' }}</button> <button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Fingerprints confirmed' : 'Both fingerprints match — confirm' }}</button>
</div> </div>
<div v-if="incoming && step === 'choose-storage'" class="incoming"> <div v-if="incoming && receiveState === 'choose-storage'" class="incoming">
<button :disabled="choosing" @click="declineFile">Decline file</button>
<p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p> <p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p>
<p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p> <p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p>
<button v-if="canStreamDownload" class="primary" :disabled="choosing" @click="acceptFile('download')">Receive as download ({{ formatBytes(incoming.size) }})</button> <button v-if="canStreamDownload" class="primary" :disabled="choosing" @click="acceptFile('download')">Receive as download ({{ formatBytes(incoming.size) }})</button>
@@ -306,7 +369,9 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile('memory')">Receive in memory (up to 64 MiB)</button> <button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile('memory')">Receive in memory (up to 64 MiB)</button>
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk && !canStreamDownload" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p> <p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk && !canStreamDownload" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p>
</div> </div>
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div> <p v-if="incoming && receiveState !== 'choose-storage'" class="status">Receiving: {{ incoming.name }} — {{ stateLabel(receiveState) }} ({{ receiveProgress }}%)</p>
<div v-if="outgoing" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Sending progress"><div :style="{ width: progress + '%' }"></div></div>
<div v-if="incoming" class="progress" role="progressbar" :aria-valuenow="receiveProgress" aria-valuemin="0" aria-valuemax="100" aria-label="Receiving progress"><div :style="{ width: receiveProgress + '%' }"></div></div>
<p class="status" role="status">{{ status }}</p> <p class="status" role="status">{{ status }}</p>
<p v-if="error" class="error" role="alert">{{ error }}</p> <p v-if="error" class="error" role="alert">{{ error }}</p>
<details v-if="diagnosticLines.length"> <details v-if="diagnosticLines.length">
@@ -315,8 +380,13 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<label class="step" for="connection-diagnostics">Diagnostic log (select and copy)</label> <label class="step" for="connection-diagnostics">Diagnostic log (select and copy)</label>
<textarea id="connection-diagnostics" :value="diagnosticLines.join('\n')" readonly rows="12" @focus="selectCode" /> <textarea id="connection-diagnostics" :value="diagnosticLines.join('\n')" readonly rows="12" @focus="selectCode" />
</details> </details>
<div v-if="downloadUrl && incoming" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div> <div v-if="downloadUrl" class="file-chip"><span>{{ downloadName }}</span><a class="download" :href="downloadUrl" :download="downloadName">Save file</a></div>
<p v-if="downloadUrl && receiveState === 'choose-storage'" class="status">Save the previous file before accepting this one. Accepting replaces its memory download.</p>
<p v-if="!connected && step === 'done'" class="status">Connection ended. Exchange fresh codes to send more files.</p>
<p v-if="connected" class="status">Connection verified. Either person can add files. Keep both tabs open.</p>
<ul v-if="history.length" aria-label="Recent file results"><li v-for="(entry, index) in history" :key="index">{{ entry }}</li></ul>
<button v-if="connected || busy" @click="disconnect">Disconnect</button>
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button> <button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
<p class="status">Switching HellCon’s Send/Receive mode cancels the connection. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p> <p class="status">Send/Receive chooses who starts the connection. Disconnect before changing this setup choice. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
</div> </div>
</template> </template>
+166
View File
@@ -0,0 +1,166 @@
import { Transfer, validateMetadata, type TransferChannel, type FileDestination, type FileMetadata, type TransferState, type TransferResult } from './transfer.ts';
import { CHUNK_SIZE } from './webrtc.ts';
import { asError, isRecord } from './validation.ts';
export const QUEUE_LIMIT = 32;
export interface QueueItem { id: number; file: File }
export interface SessionCallbacks {
onReady(): void;
onQueue(items: QueueItem[]): void;
onState(direction: 'send' | 'receive', state: TransferState, meta: FileMetadata): void;
onProgress(direction: 'send' | 'receive', bytes: number, size: number): void;
onComplete(direction: 'send' | 'receive', result: TransferResult): void;
onDecline(direction: 'send' | 'receive', meta: FileMetadata): void;
onError(error: Error): void;
onClose(): void;
}
interface Active { id: number; transfer: Transfer; meta: FileMetadata }
// One sequential queue per direction. At most two active transfers share the
// transport, with separate bounded Transfer windows and unique session IDs.
export class FileSession {
private pending: QueueItem[] = [];
private outgoing: Active | null = null;
private incoming: Active | null = null;
private nextId: number;
private lastRemoteId = 0;
private verified = false;
private peerReady = false;
private readySent = false;
private started = false;
private closed = false;
private timer: ReturnType<typeof setTimeout>;
private readonly dc: TransferChannel;
private readonly initiator: boolean;
private readonly callbacks: SessionCallbacks;
constructor(dc: TransferChannel, initiator: boolean, callbacks: SessionCallbacks) {
this.dc = dc; this.initiator = initiator; this.callbacks = callbacks;
this.nextId = initiator ? 1 : 2;
dc.binaryType = 'arraybuffer';
dc.onopen = () => this.ready();
dc.onmessage = event => { try { this.message(event.data); } catch (error) { this.fail(error); } };
dc.onclose = () => this.outgoing || this.incoming ? this.fail(new Error('Connection closed. Unfinished files were cancelled.')) : this.close();
dc.onerror = () => this.fail(new Error('Connection failed. Exchange fresh codes.'));
this.timer = setTimeout(() => this.fail(new Error('Verification timed out.')), 5 * 60 * 1000);
}
private control(data: object) { this.dc.send(JSON.stringify({ v: 3, ...data })); }
verify() { this.verified = true; this.ready(); }
private ready() {
if (this.closed || !this.verified || this.dc.readyState !== 'open') return;
try {
if (!this.readySent) { this.readySent = true; this.control({ type: 'ready' }); }
if (this.peerReady && !this.started) {
this.started = true; clearTimeout(this.timer); this.callbacks.onReady(); this.pump();
}
} catch (error) { this.fail(error); }
}
add(files: File[]) {
if (this.closed) throw new Error('Connection ended.');
if (files.length + this.pending.length + (this.outgoing ? 1 : 0) > QUEUE_LIMIT) throw new Error(`Queue up to ${QUEUE_LIMIT} files at a time.`);
for (const file of files) validateMetadata({ name: file.name, size: file.size, mime: file.type || '' });
if (this.nextId + files.length * 2 > 0xffffffff) throw new Error('Start a new session.');
for (const file of files) { this.pending.push({ id: this.nextId, file }); this.nextId += 2; }
this.callbacks.onQueue([...this.pending]); this.pump();
}
remove(id: number) { this.pending = this.pending.filter(item => item.id !== id); this.callbacks.onQueue([...this.pending]); }
accept(destination: FileDestination | null = null) {
if (!this.incoming) throw new Error('File is no longer available.');
this.incoming.transfer.accept(destination);
}
decline() {
const item = this.incoming;
if (!item || item.transfer.state !== 'choose-storage') return;
this.control({ type: 'decline', id: item.id });
this.incoming = null; item.transfer.close(); this.callbacks.onDecline('receive', item.meta);
}
private pump() {
if (!this.started || this.closed || this.outgoing || !this.pending.length) return;
const item = this.pending.shift()!;
this.callbacks.onQueue([...this.pending]);
const meta = validateMetadata({ name: item.file.name, size: item.file.size, mime: item.file.type || '' });
this.control({ type: 'start', id: item.id });
this.outgoing = this.create(item.id, item.file, meta);
this.outgoing.transfer.verify();
}
private create(id: number, file: File | null, meta: FileMetadata): Active {
const raw = this.dc;
const channel = new EventTarget() as TransferChannel;
channel.binaryType = 'arraybuffer'; channel.bufferedAmountLowThreshold = 0;
channel.onopen = channel.onmessage = channel.onclose = channel.onerror = null;
let ended = false;
Object.defineProperties(channel, {
readyState: { get: () => ended ? 'closed' : raw.readyState },
bufferedAmount: { get: () => raw.bufferedAmount },
bufferedAmountLowThreshold: { get: () => raw.bufferedAmountLowThreshold, set: value => { raw.bufferedAmountLowThreshold = value; } },
});
const drain = () => channel.dispatchEvent(new Event('bufferedamountlow'));
const close = () => channel.dispatchEvent(new Event('close'));
raw.addEventListener('bufferedamountlow', drain);
raw.addEventListener('close', close);
channel.close = () => { ended = true; raw.removeEventListener('bufferedamountlow', drain); raw.removeEventListener('close', close); channel.dispatchEvent(new Event('close')); };
channel.send = data => {
if (ended || this.closed) throw new Error('Connection ended.');
if (typeof data === 'string') this.control({ type: 'frame', id, data });
else {
const packet = new Uint8Array(data.byteLength + 4);
new DataView(packet.buffer).setUint32(0, id);
packet.set(new Uint8Array(data), 4); raw.send(packet.buffer);
}
};
const direction = file ? 'send' : 'receive';
const item: Active = { id, meta, transfer: new Transfer(channel, {
file,
onState: state => this.callbacks.onState(direction, state, item.meta),
onMeta: metadata => { item.meta = metadata; this.callbacks.onState(direction, 'choose-storage', metadata); },
onProgress: (bytes, size) => this.callbacks.onProgress(direction, bytes, size),
onComplete: result => {
if (this.closed) return;
if (direction === 'send') this.outgoing = null; else this.incoming = null;
item.transfer.close(); this.callbacks.onComplete(direction, result);
queueMicrotask(() => { try { this.pump(); } catch (error) { this.fail(error); } });
},
onError: error => this.fail(error),
}) };
return item;
}
private message(data: unknown) {
if (this.closed) return;
if (data instanceof ArrayBuffer) {
if (!this.started || data.byteLength <= 4 || data.byteLength > CHUNK_SIZE + 4) throw new Error('Invalid file packet.');
const id = new DataView(data).getUint32(0);
if (!this.incoming || this.incoming.id !== id) throw new Error('Unexpected file ID.');
this.incoming.transfer.enqueue(data.slice(4)); return;
}
if (typeof data !== 'string' || data.length > 4096) throw new Error('Invalid session message.');
const msg: unknown = JSON.parse(data);
if (!isRecord(msg) || msg.v !== 3) throw new Error('Unsupported session protocol.');
if (msg.type === 'ready' && !this.peerReady) { this.peerReady = true; this.ready(); return; }
if (!this.started) throw new Error('File data arrived before verification.');
if (typeof msg.id !== 'number' || !Number.isInteger(msg.id) || msg.id <= 0 || msg.id > 0xffffffff) throw new Error('Invalid file ID.');
if (msg.type === 'start') {
if (this.incoming || msg.id % 2 !== (this.initiator ? 0 : 1) || msg.id <= this.lastRemoteId) throw new Error('Unexpected file offer.');
this.lastRemoteId = msg.id;
this.incoming = this.create(msg.id, null, { name: '', size: 0, mime: '' });
this.incoming.transfer.verify(); return;
}
if (msg.type === 'decline') {
const item = this.outgoing;
if (!item || item.id !== msg.id || item.transfer.state !== 'waiting-accept') throw new Error('Unexpected decline.');
this.outgoing = null; item.transfer.close(); this.callbacks.onDecline('send', item.meta); this.pump(); return;
}
if (msg.type === 'frame' && typeof msg.data === 'string') {
const item = [this.incoming, this.outgoing].find(item => item?.id === msg.id);
if (!item) throw new Error('Unexpected file ID.');
item.transfer.enqueue(msg.data); return;
}
throw new Error('Unexpected session message.');
}
private fail(error: unknown) { if (!this.closed) { this.callbacks.onError(asError(error)); this.close(); } }
close() {
if (this.closed) return;
this.closed = true; clearTimeout(this.timer);
this.outgoing?.transfer.close(); this.incoming?.transfer.close(); this.pending = [];
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
this.dc.close(); this.callbacks.onQueue([]); this.callbacks.onClose();
}
}
+38 -7
View File
@@ -27,6 +27,7 @@ export interface TransferOptions {
onProgress?: (bytes: number, size: number) => void; onProgress?: (bytes: number, size: number) => void;
onComplete?: (result: TransferResult) => void; onComplete?: (result: TransferResult) => void;
onError?: (error: Error) => void; onError?: (error: Error) => void;
onClose?: () => void;
timeout?: number; timeout?: number;
} }
type ControlType = 'ready' | 'meta' | 'accept' | 'ack' | 'end' | 'complete'; type ControlType = 'ready' | 'meta' | 'accept' | 'ack' | 'end' | 'complete';
@@ -48,7 +49,10 @@ export function validateMetadata(meta: unknown): FileMetadata {
// One ordered, reliable channel; bounded receive queue and acknowledged send window. // One ordered, reliable channel; bounded receive queue and acknowledged send window.
export class Transfer { export class Transfer {
readonly dc: TransferChannel; readonly dc: TransferChannel;
readonly file: File | null; file: File | null;
readonly sending: boolean;
peerSupportsRepeat = false;
readonly onClose: () => void;
readonly onState: NonNullable<TransferOptions['onState']>; readonly onState: NonNullable<TransferOptions['onState']>;
readonly onMeta: NonNullable<TransferOptions['onMeta']>; readonly onMeta: NonNullable<TransferOptions['onMeta']>;
readonly onProgress: NonNullable<TransferOptions['onProgress']>; readonly onProgress: NonNullable<TransferOptions['onProgress']>;
@@ -77,9 +81,11 @@ export class Transfer {
if (!this.meta) throw new Error('Missing file metadata.'); if (!this.meta) throw new Error('Missing file metadata.');
return this.meta; return this.meta;
} }
constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, timeout = 60000 }: TransferOptions = {}) { constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, onClose = () => {}, timeout = 60000 }: TransferOptions = {}) {
this.dc = dc; this.dc = dc;
this.file = file; this.file = file;
this.sending = !!file;
this.onClose = onClose;
this.onState = onState; this.onState = onState;
this.onMeta = onMeta; this.onMeta = onMeta;
this.onProgress = onProgress; this.onProgress = onProgress;
@@ -115,7 +121,7 @@ export class Transfer {
this.timer = setTimeout(() => this.fail(new Error('Transfer timed out. Start a new connection.')), ms); this.timer = setTimeout(() => this.fail(new Error('Transfer timed out. Start a new connection.')), ms);
} }
guard(fn: () => void) { try { fn(); } catch (err) { this.fail(err); } } guard(fn: () => void) { try { fn(); } catch (err) { this.fail(err); } }
control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number } = {}) { control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number; repeat?: boolean } = {}) {
if (this.closed || this.dc.readyState !== 'open') throw new Error('Connection is not open.'); if (this.closed || this.dc.readyState !== 'open') throw new Error('Connection is not open.');
const text = JSON.stringify({ v: 2, type, ...data }); const text = JSON.stringify({ v: 2, type, ...data });
if (text.length > CONTROL_LIMIT) throw new Error('Control message is too large.'); if (text.length > CONTROL_LIMIT) throw new Error('Control message is too large.');
@@ -128,7 +134,7 @@ export class Transfer {
} }
ready() { ready() {
if (!this.verified || this.dc.readyState !== 'open' || this.closed) return; if (!this.verified || this.dc.readyState !== 'open' || this.closed) return;
if (!this.readySent) { this.control('ready'); this.readySent = true; } if (!this.readySent) { this.control('ready', { repeat: true }); this.readySent = true; }
if (this.file && this.peerReady && this.state === 'verification') { if (this.file && this.peerReady && this.state === 'verification') {
this.meta = validateMetadata({ name: this.file.name, size: this.file.size, mime: this.file.type || '' }); this.meta = validateMetadata({ name: this.file.name, size: this.file.size, mime: this.file.type || '' });
this.setState('waiting-accept'); this.setState('waiting-accept');
@@ -167,11 +173,14 @@ export class Transfer {
const msg: unknown = JSON.parse(data); const msg: unknown = JSON.parse(data);
if (!isRecord(msg) || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.'); if (!isRecord(msg) || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
if (msg.type === 'ready' && !this.peerReady && this.state === 'verification') { if (msg.type === 'ready' && !this.peerReady && this.state === 'verification') {
this.peerSupportsRepeat = msg.repeat === true;
this.peerReady = true; this.ready(); return; this.peerReady = true; this.ready(); return;
} }
if (!this.verified || !this.peerReady || !this.readySent) throw new Error('File data arrived before verification.'); if (!this.verified || !this.peerReady || !this.readySent) throw new Error('File data arrived before verification.');
if (msg.type === 'meta' && !this.file && this.state === 'verification') { if (msg.type === 'meta' && !this.sending && (this.state === 'verification' || (this.state === 'done' && this.peerSupportsRepeat))) {
this.meta = validateMetadata(msg); const meta = validateMetadata(msg);
this.resetFile();
this.meta = meta;
this.setState('choose-storage'); this.onMeta(this.metadata); this.touch(5 * 60 * 1000); return; this.setState('choose-storage'); this.onMeta(this.metadata); this.touch(5 * 60 * 1000); return;
} }
if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') { if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') {
@@ -191,15 +200,36 @@ export class Transfer {
// Treat downloads as opaque files, regardless of the sender's MIME claim. // Treat downloads as opaque files, regardless of the sender's MIME claim.
const blob = this.writable ? null : new Blob(this.chunks, { type: 'application/octet-stream' }); const blob = this.writable ? null : new Blob(this.chunks, { type: 'application/octet-stream' });
this.chunks = []; this.chunks = [];
this.writable = null;
this.control('complete', { bytes: this.received }); this.control('complete', { bytes: this.received });
this.setState('done'); clearTimeout(this.timer); this.setState('done'); clearTimeout(this.timer);
this.onComplete({ blob, meta: this.metadata }); return; this.onComplete({ blob, meta: this.metadata }); return;
} }
if (msg.type === 'complete' && this.file && this.state === 'awaiting-receipt' && msg.bytes === this.file.size && this.acked === this.file.size) { if (msg.type === 'complete' && this.file && this.state === 'awaiting-receipt' && msg.bytes === this.file.size && this.acked === this.file.size) {
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.metadata }); this.close(); return; this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.metadata });
if (!this.peerSupportsRepeat) this.close();
return;
} }
throw new Error('Unexpected transfer message.'); throw new Error('Unexpected transfer message.');
} }
get canSendAnother() {
return this.sending && this.state === 'done' && !this.closed && this.peerSupportsRepeat && this.dc.readyState === 'open';
}
private resetFile() {
this.received = this.sent = this.acked = 0;
this.chunks = [];
this.writable = null;
this.meta = null;
}
sendAnother(file: File) {
if (!this.canSendAnother) throw new Error('Start a new connection to send another file.');
const meta = validateMetadata({ name: file.name, size: file.size, mime: file.type || '' });
this.resetFile();
this.file = file;
this.meta = meta;
this.setState('waiting-accept');
this.guard(() => { this.control('meta', meta); this.touch(5 * 60 * 1000); });
}
accept(writable: FileDestination | null = null) { accept(writable: FileDestination | null = null) {
if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.'); if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.');
if (!writable && this.metadata.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.'); if (!writable && this.metadata.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
@@ -235,5 +265,6 @@ export class Transfer {
if (writable && this.state !== 'done') Promise.resolve().then(() => writable.abort()).catch(() => {}); if (writable && this.state !== 'done') Promise.resolve().then(() => writable.abort()).catch(() => {});
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null; this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
this.dc.close(); this.dc.close();
this.onClose();
} }
} }
+2 -2
View File
@@ -132,7 +132,7 @@ export function getFingerprints(pc: { localDescription: { sdp: string } | null;
} }
export function encodeSignal(sdp: string) { export function encodeSignal(sdp: string) {
const code = btoa(JSON.stringify({ version: 2, sdp })).replace(/=+$/, ''); const code = btoa(JSON.stringify({ version: 3, sdp })).replace(/=+$/, '');
if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.'); if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
return code; return code;
} }
@@ -142,7 +142,7 @@ export function decodeSignal(text: unknown, options?: Pick<IceOptions, 'allowTur
try { try {
const clean = text.trim().replace(/\s+/g, ''); const clean = text.trim().replace(/\s+/g, '');
const data: unknown = JSON.parse(atob(clean)); const data: unknown = JSON.parse(atob(clean));
if (!isRecord(data) || data.version !== 2) throw new Error('Both people need the current HellCon version.'); if (!isRecord(data) || data.version !== 3) throw new Error('Both people need the current HellCon version.');
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.'); if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
validateDescription(data.sdp, options); validateDescription(data.sdp, options);
return data.sdp; return data.sdp;
+120
View File
@@ -0,0 +1,120 @@
import test, { type TestContext } from 'node:test';
import assert from 'node:assert/strict';
import { FileSession, QUEUE_LIMIT, type SessionCallbacks, type QueueItem } from '../src/lib/session.ts';
import type { TransferChannel, TransferResult, TransferState } from '../src/lib/transfer.ts';
class Channel extends EventTarget implements TransferChannel {
binaryType: BinaryType = 'arraybuffer';
bufferedAmountLowThreshold = 0;
bufferedAmount = 0;
readyState: RTCDataChannelState = 'open';
onopen: TransferChannel['onopen'] = null;
onmessage: TransferChannel['onmessage'] = null;
onclose: TransferChannel['onclose'] = null;
onerror: TransferChannel['onerror'] = null;
peer: Channel | null = null;
frames: (string | ArrayBuffer)[] = [];
send(data: string | ArrayBuffer) { this.frames.push(data); queueMicrotask(() => this.peer?.onmessage?.(new MessageEvent('message', { data }))); }
close() { this.readyState = 'closed'; this.dispatchEvent(new Event('close')); }
}
const tick = () => new Promise<void>(resolve => setImmediate(resolve));
async function until(check: () => boolean) { for (let n = 0; n < 500; n++) { if (check()) return; await tick(); } assert.fail('Condition did not become true'); }
const file = (name: string, size = 3) => new File([new Uint8Array(size).fill(42)], name);
function side(channel: Channel, initiator: boolean) {
const state = { ready: false, queue: [] as QueueItem[], send: '' as TransferState | '', receive: '' as TransferState | '', results: [] as { direction: string; result: TransferResult }[], declined: [] as string[], errors: [] as string[], closed: false };
const callbacks: SessionCallbacks = {
onReady() { state.ready = true; }, onQueue(items) { state.queue = items; },
onState(direction, value) { state[direction] = value; }, onProgress() {},
onComplete(direction, result) { state.results.push({ direction, result }); },
onDecline(direction, meta) { state.declined.push(meta.name); state[direction] = ''; },
onError(error) { state.errors.push(error.message); }, onClose() { state.closed = true; },
};
return { session: new FileSession(channel, initiator, callbacks), state, channel };
}
function pair(t: TestContext) {
const a = new Channel(), b = new Channel(); a.peer = b; b.peer = a;
const first = side(a, true), second = side(b, false);
t.after(() => { first.session.close(); second.session.close(); });
return { first, second };
}
test('queues remain private until both peers verify, then require per-file acceptance', async t => {
const { first, second } = pair(t);
first.session.add([file('one'), file('two', 0)]);
first.session.verify(); await tick();
assert.equal(first.channel.frames.length, 1); assert.equal(second.state.receive, '');
second.session.verify(); await until(() => second.state.receive === 'choose-storage');
assert.equal(first.state.send, 'waiting-accept');
second.session.accept(); await until(() => first.state.results.length === 1 && second.state.receive === 'choose-storage');
assert.equal(first.state.send, 'waiting-accept');
second.session.accept(); await until(() => first.state.results.length === 2);
assert.deepEqual(second.state.results.map(item => item.result.meta.name), ['one', 'two']);
assert.equal(second.state.results[1]!.result.blob!.size, 0);
assert.deepEqual(first.state.errors, []); assert.deepEqual(second.state.errors, []);
});
test('simultaneous bidirectional queues have isolated bytes, receipts and destinations', async t => {
const { first, second } = pair(t);
first.session.add([file('a', 40000), file('b')]); second.session.add([file('c', 20000), file('d', 0)]);
first.session.verify(); second.session.verify();
for (let index = 0; index < 2; index++) {
await until(() => first.state.receive === 'choose-storage' && second.state.receive === 'choose-storage');
first.session.accept(); second.session.accept();
await until(() => first.state.results.length >= (index + 1) * 2 && second.state.results.length >= (index + 1) * 2);
}
for (const side of [first, second]) {
for (const { result } of side.state.results.filter(item => item.direction === 'receive')) {
assert.ok(new Uint8Array(await result.blob!.arrayBuffer()).every(byte => byte === 42));
}
assert.deepEqual(side.state.errors, []);
}
assert.deepEqual(first.state.results.filter(item => item.direction === 'receive').map(item => item.result.meta.name), ['c', 'd']);
});
test('remove pending and decline offered files without ending the session', async t => {
const { first, second } = pair(t);
first.session.add([file('decline'), file('remove'), file('keep')]);
first.session.remove(first.state.queue[1]!.id);
first.session.verify(); second.session.verify();
await until(() => second.state.receive === 'choose-storage'); second.session.decline();
await until(() => first.state.declined.length === 1 && second.state.receive === 'choose-storage');
second.session.accept(); await until(() => first.state.results.length === 1);
assert.equal(first.state.results[0]!.result.meta.name, 'keep');
assert.deepEqual(first.state.declined, ['decline']); assert.equal(first.state.closed, false);
});
test('queue limit is atomic and cancellation aborts both active disk destinations', async t => {
const { first, second } = pair(t);
assert.throws(() => first.session.add(Array.from({ length: QUEUE_LIMIT + 1 }, () => file('too-many'))), /Queue up to/);
assert.equal(first.state.queue.length, 0);
first.session.add([file('a')]); second.session.add([file('b')]);
first.session.verify(); second.session.verify();
await until(() => first.state.receive === 'choose-storage' && second.state.receive === 'choose-storage');
let aborted = 0;
const destination = () => {
let release: (() => void) | undefined;
return { write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() { assert.fail('Cancelled destination must not close'); }, async abort() { aborted++; release?.(); } };
};
first.session.accept(destination()); second.session.accept(destination()); await tick();
first.session.close(); second.session.close(); await until(() => aborted === 2);
assert.equal(first.state.results.length, 0); assert.equal(second.state.results.length, 0);
});
test('reused file IDs and stale receipts fail closed', async t => {
for (const stale of ['start', 'frame']) {
const { first, second } = pair(t);
first.session.add([file('one', 0)]); first.session.verify(); second.session.verify();
await until(() => second.state.receive === 'choose-storage'); second.session.accept();
await until(() => first.state.results.length === 1);
const target = stale === 'start' ? second : first;
target.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: stale, id: 1, data: JSON.stringify({ v: 2, type: 'complete', bytes: 0 }) }) }));
assert.equal(target.state.closed, true); assert.equal(target.state.errors.length, 1);
}
});
test('unsolicited offers before verification and excess binary payload fail closed', async t => {
const { first, second } = pair(t);
first.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: 'start', id: 2 }) }));
second.channel.onmessage?.(new MessageEvent('message', { data: new ArrayBuffer(100000) }));
assert.equal(first.state.closed, true); assert.equal(second.state.closed, true);
});
+45
View File
@@ -231,3 +231,48 @@ test('metadata accepts files above 64 GiB while preserving exact byte counts', (
assert.equal(validateMetadata({ ...meta(), size }).size, size); assert.equal(validateMetadata({ ...meta(), size }).size, size);
} }
}); });
test('consecutive files reuse verification, reset counts, and require separate acceptance', async t => {
const results: TransferResult[] = [];
const { sender, receiver, a, errors } = pair(t, 33, { onComplete: result => results.push(result) });
sender.verify(); receiver.verify();
await until(() => receiver.state === 'choose-storage'); receiver.accept();
await until(() => sender.state === 'done');
assert.equal(sender.canSendAnother, true);
for (const bytes of [new Uint8Array(0), Uint8Array.of(1, 2, 3)]) {
sender.sendAnother(new File([bytes], 'next.bin'));
await until(() => receiver.state === 'choose-storage');
assert.equal(sender.sent, 0); assert.equal(sender.acked, 0); assert.equal(receiver.received, 0);
assert.throws(() => sender.sendAnother(new File([], 'early.bin')), /new connection/);
receiver.accept(); await until(() => sender.state === 'done');
assert.deepEqual(new Uint8Array(await results.at(-1)!.blob!.arrayBuffer()), bytes);
}
assert.equal(results.length, 3);
assert.equal(a.frames.filter(frame => typeof frame === 'string' && JSON.parse(frame).type === 'ready').length, 1);
assert.deepEqual(errors, []);
});
test('legacy readiness retains single-file sender behavior', async t => {
const { sender, b } = pair(t, 0);
b.onmessage = null;
sender.verify(); message(sender, 'ready'); await sender.queue;
message(sender, 'accept'); await sender.queue;
message(sender, 'complete', { bytes: 0 }); await sender.queue;
assert.equal(sender.state, 'done'); assert.equal(sender.closed, true);
assert.equal(sender.canSendAnother, false);
});
test('next disk transfer never reuses or aborts the completed destination', async t => {
let writes = 0, closes = 0, aborts = 0;
const { sender, receiver } = pair(t, 1);
sender.verify(); receiver.verify();
await until(() => receiver.state === 'choose-storage');
receiver.accept({ async write() { writes++; }, async close() { closes++; }, async abort() { aborts++; } });
await until(() => sender.state === 'done');
sender.sendAnother(new File([Uint8Array.of(9)], 'next.bin'));
await until(() => receiver.state === 'choose-storage');
receiver.accept({ async write() { throw new Error('Disk full'); }, async close() { assert.fail('Must not close failed storage'); }, async abort() {} });
await until(() => receiver.closed);
assert.equal(writes, 1); assert.equal(closes, 1); assert.equal(aborts, 0);
assert.notEqual(sender.state, 'done');
});
+1 -1
View File
@@ -33,7 +33,7 @@ test('signals round-trip but reject legacy, malformed and oversized codes', () =
assert.throws(() => decodeSignal(btoa(sdp))); assert.throws(() => decodeSignal(btoa(sdp)));
assert.throws(() => decodeSignal('bad!')); assert.throws(() => decodeSignal('bad!'));
assert.throws(() => decodeSignal('a'.repeat(MAX_SIGNAL_LENGTH + 1))); assert.throws(() => decodeSignal('a'.repeat(MAX_SIGNAL_LENGTH + 1)));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 1, sdp })))); assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 2, sdp }))));
}); });
class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; } class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; }