Start from scratch
This commit is contained in:
1 parent
9f3f21884f
commit
24307eb96a
61 files changed
+906
-8959
No files matched your search
+5
-228
@@ -1,233 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
|
||||
import AppDialog from './components/AppDialog.vue';
|
||||
import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts';
|
||||
import type { ReconnectPairing } from './lib/reconnect.ts';
|
||||
import { asError } from './lib/validation.ts';
|
||||
|
||||
const logoUrl = `${import.meta.env.BASE_URL}HellNet_alt.png`;
|
||||
const giteaIconUrl = `${import.meta.env.BASE_URL}gitea.svg`;
|
||||
const connections = ref<SavedConnection[]>([]), selected = ref('');
|
||||
const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({});
|
||||
const current = computed(() => connections.value.find(item => item.id === selected.value));
|
||||
const sidebarOpen = ref(false), adding = ref(false);
|
||||
const confirmingRemoval = ref(false), removing = ref(false), removalId = ref('');
|
||||
const renamingId = ref(''), renameDraft = ref('');
|
||||
let renameContainer: HTMLElement | null = null;
|
||||
const removalTarget = computed(() => connections.value.find(item => item.id === removalId.value));
|
||||
const error = ref(''), removalError = ref('');
|
||||
const heading = ref<HTMLElement | null>(null);
|
||||
let persistent = true, pending = 0, writes = Promise.resolve(), refreshRequested = false;
|
||||
let updates: BroadcastChannel | undefined;
|
||||
function select(id: string) {
|
||||
selected.value = id; confirmingRemoval.value = false; sidebarOpen.value = false;
|
||||
void nextTick(() => heading.value?.focus());
|
||||
}
|
||||
function startRename(item: SavedConnection, opener: HTMLButtonElement) {
|
||||
renameContainer = opener.closest<HTMLElement>('.connection-item');
|
||||
renamingId.value = item.id;
|
||||
renameDraft.value = item.name;
|
||||
void nextTick(() => { const input = document.querySelector<HTMLInputElement>('.connection-rename-input'); input?.focus(); input?.select(); });
|
||||
}
|
||||
function saveRename() {
|
||||
const id = renamingId.value;
|
||||
if (!id) return;
|
||||
renamingId.value = '';
|
||||
const name = renameDraft.value.trim();
|
||||
const item = connections.value.find(record => record.id === id);
|
||||
if (name && item && name !== item.name) update(id, { name });
|
||||
}
|
||||
function focusRenameAction() { void nextTick(() => renameContainer?.querySelector<HTMLButtonElement>('.edit-action')?.focus()); }
|
||||
function cancelRename() { renamingId.value = ''; focusRenameAction(); }
|
||||
function finishRename(event: KeyboardEvent) { (event.target as HTMLInputElement).blur(); focusRenameAction(); }
|
||||
function confirmRemove(id: string) { removalId.value = id; removalError.value = ''; confirmingRemoval.value = true; }
|
||||
function applyRecords(records: SavedConnection[]) {
|
||||
connections.value = records;
|
||||
for (const id of Object.keys(states.value)) if (!records.some(item => item.id === id)) delete states.value[id];
|
||||
if (!records.some(item => item.id === renamingId.value)) renamingId.value = '';
|
||||
// Close a removal prompt whose connection another tab already removed.
|
||||
if (!removing.value && !records.some(item => item.id === removalId.value)) confirmingRemoval.value = false;
|
||||
if (!records.some(item => item.id === selected.value)) select(records[0]!.id);
|
||||
}
|
||||
function setStatus(id: string, state: 'ready' | 'connecting' | 'connected') {
|
||||
if (connections.value.some(item => item.id === id)) states.value[id] = state;
|
||||
}
|
||||
function statusLabel(id: string) { return states.value[id] === 'connected' ? 'Connected' : states.value[id] === 'connecting' ? 'Connecting' : 'Ready to connect'; }
|
||||
async function refresh() {
|
||||
if (!persistent) return;
|
||||
if (pending || removing.value) { refreshRequested = true; return; }
|
||||
refreshRequested = false;
|
||||
try { const records = await loadConnections(); if (!pending && !removing.value) applyRecords(records); else refreshRequested = true; }
|
||||
catch (err) { error.value = asError(err).message; }
|
||||
}
|
||||
onMounted(async () => {
|
||||
try { connections.value = await loadConnections(); }
|
||||
catch (err) {
|
||||
persistent = false; connections.value = [emptyConnection()];
|
||||
error.value = `${asError(err).message} Connections will only last for this tab.`;
|
||||
}
|
||||
selected.value = connections.value[0]!.id;
|
||||
if (typeof BroadcastChannel !== 'undefined') {
|
||||
updates = new BroadcastChannel('hellcon-connections');
|
||||
updates.onmessage = () => { void refresh(); };
|
||||
}
|
||||
window.addEventListener('focus', refresh);
|
||||
});
|
||||
onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); });
|
||||
async function add() {
|
||||
if (adding.value || removing.value || connections.value.length >= CONNECTION_LIMIT) return;
|
||||
adding.value = true;
|
||||
try {
|
||||
await writes;
|
||||
if (persistent) connections.value = await addConnection();
|
||||
else connections.value.push(emptyConnection(Math.max(...connections.value.map(item => item.number)) + 1));
|
||||
select(connections.value.at(-1)!.id); updates?.postMessage('changed');
|
||||
} catch (err) { error.value = asError(err).message; }
|
||||
finally { adding.value = false; }
|
||||
}
|
||||
function update(id: string, change: ConnectionUpdate) {
|
||||
const index = connections.value.findIndex(item => item.id === id);
|
||||
if (index < 0) return;
|
||||
try { connections.value[index] = updateConnection(connections.value[index]!, change); }
|
||||
catch (err) { error.value = asError(err).message; return; }
|
||||
if (!persistent) return;
|
||||
pending++;
|
||||
writes = writes.then(async () => {
|
||||
try {
|
||||
const records = await saveConnection(id, change);
|
||||
if (pending === 1) applyRecords(records);
|
||||
updates?.postMessage('changed');
|
||||
} catch (err) {
|
||||
// Keep this tab usable without pretending the change reached storage.
|
||||
error.value = `${asError(err).message} Your latest changes may be lost when this tab closes.`;
|
||||
refreshRequested = true;
|
||||
} finally { pending--; if (!pending && refreshRequested) void refresh(); }
|
||||
});
|
||||
}
|
||||
// Pairing setup needs the committed write, rather than the optimistic update
|
||||
// used by ordinary settings, before either browser reports success. null
|
||||
// removes a pairing the peer could not store or does not share.
|
||||
function saveReconnect(id: string, reconnect: ReconnectPairing | null): Promise<void> {
|
||||
if (!persistent) {
|
||||
if (reconnect) return Promise.reject(new Error('Reconnect needs saved connection storage in this browser.'));
|
||||
update(id, { reconnect }); return Promise.resolve();
|
||||
}
|
||||
pending++;
|
||||
const operation = writes.then(async () => {
|
||||
try {
|
||||
const records = await saveConnection(id, { reconnect });
|
||||
if (pending === 1) applyRecords(records);
|
||||
updates?.postMessage('changed');
|
||||
} catch (err) {
|
||||
refreshRequested = true;
|
||||
throw err;
|
||||
} finally { pending--; if (!pending && refreshRequested) void refresh(); }
|
||||
});
|
||||
writes = operation.catch(() => {});
|
||||
return operation;
|
||||
}
|
||||
// Connection setup re-reads the record so trust forgotten in another tab is
|
||||
// never reused from this tab's copy. A failed read stops setup.
|
||||
async function trust(id: string) {
|
||||
await writes;
|
||||
const records = persistent ? await loadConnections() : connections.value;
|
||||
const record = records.find(item => item.id === id);
|
||||
if (!record) throw new Error('This connection is no longer saved. Reload the page.');
|
||||
if (persistent && !pending && !removing.value) applyRecords(records);
|
||||
return record;
|
||||
}
|
||||
async function remove() {
|
||||
if (!removalTarget.value || removing.value || adding.value) return;
|
||||
const id = removalTarget.value.id, wasSelected = id === selected.value;
|
||||
const index = connections.value.findIndex(item => item.id === id);
|
||||
removing.value = true; removalError.value = '';
|
||||
try {
|
||||
await writes;
|
||||
const records = persistent ? await removeConnection(id) : connections.value.filter(item => item.id !== id);
|
||||
applyRecords(records.length ? records : [emptyConnection()]);
|
||||
confirmingRemoval.value = false;
|
||||
await nextTick();
|
||||
// Focus the newly opened row, or the row that took the removed row's place.
|
||||
const row = wasSelected ? document.querySelector('.connection-item.selected') : document.querySelectorAll('.connection-item')[Math.min(index, connections.value.length - 1)];
|
||||
const link = row?.querySelector<HTMLButtonElement>('.connection-link');
|
||||
if (link?.offsetParent) link.focus();
|
||||
else heading.value?.focus();
|
||||
updates?.postMessage('changed');
|
||||
} catch (err) { removalError.value = asError(err).message; }
|
||||
finally { removing.value = false; if (refreshRequested) void refresh(); }
|
||||
}
|
||||
const message = 'Hello, world!';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a class="skip-link" href="#main-content">Skip to main content</a>
|
||||
<div class="app-shell" :class="{ 'sidebar-open': sidebarOpen }">
|
||||
<aside id="connections-sidebar" class="sidebar" aria-label="Connections sidebar">
|
||||
<header class="brand">
|
||||
<img :src="logoUrl" width="38" height="38" alt="" />
|
||||
<div><span class="brand-name">HellCon</span><p>Direct file sharing</p></div>
|
||||
</header>
|
||||
<div class="sidebar-section-heading"><h2>Connections</h2><span>{{ connections.length }}</span></div>
|
||||
<nav class="connection-nav" aria-label="Connections">
|
||||
<div v-for="item in connections" :key="item.id" class="connection-item" :class="{ selected: selected === item.id }">
|
||||
<button v-if="renamingId !== item.id" class="connection-link" :aria-current="selected === item.id ? 'page' : undefined" @click="select(item.id)">
|
||||
<span class="connection-name">{{ item.name }}</span>
|
||||
<span class="connection-status-line"><span class="connection-dot" :class="states[item.id] || 'ready'" aria-hidden="true"></span><span class="connection-status">{{ statusLabel(item.id) }}</span></span>
|
||||
</button>
|
||||
<div v-else class="connection-edit">
|
||||
<input v-model="renameDraft" class="connection-rename-input" :aria-label="`New name for ${item.name}`" aria-describedby="rename-hint" maxlength="80" autocomplete="off" spellcheck="false"
|
||||
@blur="saveRename" @keydown.enter.prevent="finishRename" @keydown.esc.prevent="cancelRename" />
|
||||
<span class="connection-status-line"><span class="connection-dot" :class="states[item.id] || 'ready'" aria-hidden="true"></span><span class="connection-status">{{ statusLabel(item.id) }}</span></span>
|
||||
</div>
|
||||
<button v-if="renamingId !== item.id" class="connection-action edit-action" :aria-label="`Rename ${item.name}`" :title="`Rename ${item.name}`" :disabled="removing" @click="startRename(item, $event.currentTarget as HTMLButtonElement)"><span aria-hidden="true">✎</span></button>
|
||||
<button class="connection-action remove-action" :aria-label="`Remove ${item.name}`" :title="`Remove ${item.name}`" :disabled="adding || removing" @click="confirmRemove(item.id)"><span aria-hidden="true">✕</span></button>
|
||||
</div>
|
||||
<span id="rename-hint" class="sr-only">Press Enter or leave the field to save. Press Escape to cancel.</span>
|
||||
</nav>
|
||||
<button class="add-connection" :disabled="adding || removing || !connections.length || connections.length >= CONNECTION_LIMIT" @click="add"><span aria-hidden="true">+</span> Add connection</button>
|
||||
<footer class="sidebar-footer">
|
||||
<span class="sidebar-tag">Browser to browser</span>
|
||||
<p>No accounts. Your connections stay on this device.</p>
|
||||
<details class="privacy-details">
|
||||
<summary>About privacy & connections</summary>
|
||||
<p>Files travel over encrypted WebRTC data channels. Compare full fingerprints on first pairing, or let a connection authenticate its remembered device. Reconnect by exchanging fresh codes.</p>
|
||||
<p>Trust your browser and the app’s host: its code can read selected files and use your device identity. HTTPS protects delivery. A TURN relay is used only after opt-in.</p>
|
||||
<p>Clearing site data removes saved connections and identities.</p>
|
||||
</details>
|
||||
<a class="source-link" href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer" aria-label="View HellCon source code on Gitea">
|
||||
<img :src="giteaIconUrl" width="20" height="20" alt="" />
|
||||
<span>Source code</span>
|
||||
</a>
|
||||
</footer>
|
||||
</aside>
|
||||
<main id="main-content" class="main-pane" tabindex="-1">
|
||||
<h1 v-if="current" ref="heading" class="sr-only" tabindex="-1">{{ current.name }}</h1>
|
||||
<div class="mobile-bar">
|
||||
<div v-if="current" class="mobile-current">
|
||||
<span class="mobile-current-name" aria-hidden="true">{{ current.name }}</span>
|
||||
<span class="connection-status-line"><span class="connection-dot" :class="states[current.id] || 'ready'" aria-hidden="true"></span><span class="mobile-current-status">{{ statusLabel(current.id) }}</span></span>
|
||||
</div>
|
||||
<button class="sidebar-toggle" :aria-expanded="sidebarOpen" aria-controls="connections-sidebar" @click="sidebarOpen = !sidebarOpen">{{ sidebarOpen ? 'Hide connections' : 'Show connections' }}</button>
|
||||
</div>
|
||||
<div class="workspace-scroll">
|
||||
<p v-if="error" class="storage-error" role="alert">{{ error }}</p>
|
||||
<template v-for="item in connections" :key="item.id">
|
||||
<KeepAlive>
|
||||
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :save-reconnect="saveReconnect"
|
||||
@status="setStatus" @update="update" />
|
||||
</KeepAlive>
|
||||
</template>
|
||||
<p v-if="!current" class="status">Opening your connections…</p>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<AppDialog v-model="confirmingRemoval" :title="`Remove ${removalTarget?.name || 'connection'}?`" :busy="removing">
|
||||
<p>This ends its session and forgets its remembered device. Saved files and your device identity are kept.</p>
|
||||
<p v-if="connections.length === 1">A fresh Con 1 will replace your last connection.</p>
|
||||
<p v-if="removalError" class="error" role="alert">{{ removalError }}</p>
|
||||
<template #actions="{ close }">
|
||||
<button :disabled="removing" autofocus @click="close">Keep connection</button>
|
||||
<button class="danger" :disabled="removing" @click="remove">{{ removing ? 'Removing…' : 'Remove connection' }}</button>
|
||||
</template>
|
||||
</AppDialog>
|
||||
<main>
|
||||
<h1>HellCon</h1>
|
||||
<p>{{ message }}</p>
|
||||
</main>
|
||||
</template>
|
||||
@@ -1,41 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, useId, watch } from 'vue';
|
||||
|
||||
const open = defineModel<boolean>({ default: false });
|
||||
const props = defineProps<{ title: string; busy?: boolean }>();
|
||||
const dialog = ref<HTMLDialogElement | null>(null);
|
||||
const titleId = useId(), bodyId = useId();
|
||||
function close() { if (!props.busy) open.value = false; }
|
||||
function closed() { if (!dialog.value?.open) open.value = false; }
|
||||
// showModal() makes the page inert but lets Tab leave for the browser UI; wrap instead.
|
||||
function trap(event: KeyboardEvent) {
|
||||
const items = [...dialog.value?.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])') ?? []]
|
||||
.filter(item => !item.matches(':disabled') && item.offsetParent !== null);
|
||||
const first = items[0], last = items.at(-1);
|
||||
if (!first || !last) { event.preventDefault(); return; }
|
||||
const active = document.activeElement;
|
||||
if (event.shiftKey && (active === first || !dialog.value?.contains(active))) { event.preventDefault(); last.focus(); }
|
||||
else if (!event.shiftKey && (active === last || !dialog.value?.contains(active))) { event.preventDefault(); first.focus(); }
|
||||
}
|
||||
function sync() {
|
||||
if (open.value && !dialog.value?.open) dialog.value?.showModal();
|
||||
else if (!open.value && dialog.value?.open) dialog.value.close();
|
||||
}
|
||||
watch(open, sync, { flush: 'post' });
|
||||
onMounted(sync);
|
||||
onBeforeUnmount(() => dialog.value?.close());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<dialog ref="dialog" class="app-dialog" :aria-labelledby="titleId" :aria-describedby="bodyId" :aria-busy="busy || undefined"
|
||||
@cancel.prevent="close" @close="closed" @keydown.tab="trap">
|
||||
<header class="dialog-header">
|
||||
<h2 :id="titleId">{{ title }}</h2>
|
||||
<button class="dialog-close" type="button" aria-label="Close dialog" :disabled="busy" @click="close"><span aria-hidden="true">×</span></button>
|
||||
</header>
|
||||
<div :id="bodyId" class="dialog-body"><slot :close="close" /></div>
|
||||
<div v-if="$slots.actions" class="dialog-actions"><slot name="actions" :close="close" /></div>
|
||||
</dialog>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -1,36 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import TransferPanel from './TransferPanel.vue';
|
||||
import type { SavedConnection, ConnectionUpdate } from '../lib/connections.ts';
|
||||
import type { ReconnectPairing } from '../lib/reconnect.ts';
|
||||
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection>; saveReconnect: (id: string, reconnect: ReconnectPairing | null) => Promise<void> }>();
|
||||
const emit = defineEmits<{
|
||||
status: [id: string, state: 'ready' | 'connecting' | 'connected'];
|
||||
update: [id: string, change: ConnectionUpdate];
|
||||
}>();
|
||||
const mode = ref<'send' | 'receive'>('send');
|
||||
const sessionActive = ref(false), connected = ref(false);
|
||||
const direction = ref<'send' | 'receive'>('send');
|
||||
const panel = ref<InstanceType<typeof TransferPanel> | null>(null);
|
||||
function status() { emit('status', props.connection.id, connected.value ? 'connected' : sessionActive.value ? 'connecting' : 'ready'); }
|
||||
function navigate(next: 'send' | 'receive') {
|
||||
if (connected.value) { direction.value = next; panel.value?.focusDirection(next); }
|
||||
else if (!sessionActive.value) mode.value = next;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="connection-workspace">
|
||||
<div class="workspace-intro">
|
||||
<h2>{{ connected ? 'Share files' : 'Start a session' }}</h2>
|
||||
<p>{{ connected ? 'Your connection is ready.' : 'Exchange connection codes with your peer to start sharing.' }} Each direction sends one file at a time; both people can send on this connection.</p>
|
||||
</div>
|
||||
<div class="tabs" role="group" :aria-label="connected ? 'Transfer sections' : 'Connection setup'">
|
||||
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'send' }" :aria-pressed="(connected ? direction : mode) === 'send'" @click="navigate('send')">Send</button>
|
||||
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'receive' }" :aria-pressed="(connected ? direction : mode) === 'receive'" @click="navigate('receive')">Receive</button>
|
||||
</div>
|
||||
<TransferPanel ref="panel" :key="mode" :sending="mode === 'send'" :connection="connection" :load-trust="() => loadTrust(connection.id)" :save-reconnect="reconnect => saveReconnect(connection.id, reconnect)"
|
||||
@session-change="sessionActive = $event; status()" @connected-change="connected = $event; direction = mode; status()"
|
||||
@update="emit('update', connection.id, $event)" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,84 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onActivated, onMounted, ref, shallowRef } from 'vue';
|
||||
import { clearIdentityStorage, createIdentity, loadIdentityState, saveIdentityState, type IdentityState } from '../lib/identity.ts';
|
||||
import type { ConnectionUpdate } from '../lib/connections.ts';
|
||||
import { asError } from '../lib/validation.ts';
|
||||
const props = defineProps<{ disabled: boolean; paired: string; remember: boolean; reconnect: string }>();
|
||||
const emit = defineEmits<{ update: [change: ConnectionUpdate] }>();
|
||||
const supported = (() => { try { return isSecureContext && !!crypto.subtle && !!window.indexedDB; } catch { return false; } })();
|
||||
const state = shallowRef<IdentityState>({ identity: null });
|
||||
const working = ref(false), loaded = ref(false);
|
||||
const error = ref(''), confirmDelete = ref(false);
|
||||
onMounted(async () => {
|
||||
if (!supported) return;
|
||||
try { state.value = await loadIdentityState(); loaded.value = true; }
|
||||
catch (err) { error.value = asError(err).message; }
|
||||
});
|
||||
onActivated(async () => {
|
||||
// Another slot may have replaced the shared identity while this workspace
|
||||
// was cached. Never interrupt an active session to refresh it.
|
||||
if (!loaded.value || props.disabled) return;
|
||||
try {
|
||||
const next = await loadIdentityState();
|
||||
if (props.disabled) return;
|
||||
if (next.revision !== state.value.revision) confirmDelete.value = false;
|
||||
state.value = next;
|
||||
} catch (err) { error.value = asError(err).message; }
|
||||
});
|
||||
async function run(action: () => Promise<void>) {
|
||||
if (props.disabled || working.value) return;
|
||||
working.value = true; error.value = '';
|
||||
try { await action(); } catch (err) { error.value = asError(err).message; }
|
||||
finally { working.value = false; }
|
||||
}
|
||||
function recover() { void run(async () => { if (!confirmDelete.value) return; await clearIdentityStorage(); state.value = { identity: null }; loaded.value = true; confirmDelete.value = false; }); }
|
||||
// Creating an identity from a connection opts that connection in.
|
||||
function create() { void run(async () => { state.value = await saveIdentityState({ identity: await createIdentity() }, state.value.revision); emit('update', { rememberDevice: true }); }); }
|
||||
function reset() { void run(async () => { if (!confirmDelete.value) return; state.value = await saveIdentityState({ identity: null }, state.value.revision); confirmDelete.value = false; }); }
|
||||
function toggle(event: Event) { if (!props.disabled && event.target instanceof HTMLInputElement) emit('update', { rememberDevice: event.target.checked }); }
|
||||
function forget() { if (!props.disabled) emit('update', { peerKey: '' }); }
|
||||
function stopReconnect() { if (!props.disabled) emit('update', { reconnect: null }); }
|
||||
async function refreshIdentity() {
|
||||
if (working.value) throw new Error('Wait for the device settings operation to finish before connecting.');
|
||||
if (!supported) return null;
|
||||
try {
|
||||
const next = await loadIdentityState();
|
||||
if (next.revision !== state.value.revision) confirmDelete.value = false;
|
||||
state.value = next; loaded.value = true; error.value = '';
|
||||
return next.identity;
|
||||
} catch (err) {
|
||||
error.value = asError(err).message;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
defineExpose({ refreshIdentity });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<details v-if="supported" class="config-details">
|
||||
<summary>Remembered device</summary>
|
||||
<p class="status">Optionally remember the device on this connection, so later sessions verify it automatically. This uses a device identity stored in this browser and shared by all connections. Clearing site data loses it. Trusted app code is required: it can use this identity.</p>
|
||||
<fieldset class="device-settings" :disabled="disabled || working || !loaded">
|
||||
<button v-if="!state.identity" @click="create">Create device identity</button>
|
||||
<template v-else>
|
||||
<template v-if="paired">
|
||||
<p class="status">Paired device <code>{{ paired.slice(-12) }}</code>. Later sessions verify it automatically.</p>
|
||||
<template v-if="reconnect">
|
||||
<p class="status">Reconnects without codes through <strong>{{ reconnect }}</strong>.</p>
|
||||
<button @click="stopReconnect">Turn off reconnect</button>
|
||||
</template>
|
||||
<button @click="forget">Forget device</button>
|
||||
</template>
|
||||
<label v-else><input id="remember-device" :checked="remember" type="checkbox" @change="toggle" /> Use my device identity on this connection</label>
|
||||
<p class="status">When enabled, your public identity is included in this connection’s codes and can link your sessions.</p>
|
||||
<label><input v-model="confirmDelete" type="checkbox" /> Delete this browser’s device identity</label>
|
||||
<button :disabled="!confirmDelete" @click="reset">Delete device identity</button>
|
||||
</template>
|
||||
</fieldset>
|
||||
<div v-if="!loaded && error">
|
||||
<label><input v-model="confirmDelete" type="checkbox" :disabled="disabled || working" /> Delete unreadable device storage</label>
|
||||
<button :disabled="disabled || working || !confirmDelete" @click="recover">Clear device storage</button>
|
||||
</div>
|
||||
<p v-if="error" role="alert" class="error">{{ error }}</p>
|
||||
</details>
|
||||
</template>
|
||||
@@ -1,51 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { IceOptions, NetworkSettings } from '../lib/webrtc.ts';
|
||||
import { STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
import type { DiscoverySettings } from '../lib/reconnect.ts';
|
||||
const settings = defineModel<NetworkSettings>({ required: true });
|
||||
// Discovery stays editable while connected: reconnect is set up over a live session.
|
||||
const discovery = defineModel<DiscoverySettings>('discovery', { required: true });
|
||||
defineProps<{ disabled?: boolean; managedCredentials?: IceOptions | null; defaultTracker: string }>();
|
||||
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||
const host = (url: string) => { try { return new URL(url).host; } catch { return url; } };
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<fieldset :disabled="disabled" class="network-settings">
|
||||
<legend>Connection settings</legend>
|
||||
<label for="stun-provider">STUN provider</label>
|
||||
<select id="stun-provider" v-model="settings.stunChoice" class="stun-select">
|
||||
<option v-for="provider in STUN_PROVIDERS" :key="provider.id" :value="provider.id">{{ provider.label }}</option>
|
||||
<option value="custom">Custom…</option>
|
||||
</select>
|
||||
<input v-if="settings.stunChoice === 'custom'" v-model="settings.customStun" class="stun-input" aria-label="Custom STUN address" placeholder="stun:your.domain:3478" />
|
||||
<p class="status">STUN helps discover a reachable address. Its operator sees your public IP and request timing, but does not carry your file. Direct connections may fail on restrictive networks.</p>
|
||||
<label class="checkbox"><input type="checkbox" v-model="settings.allowTurn" /> Allow a TURN relay for this connection (opt-in)</label>
|
||||
<template v-if="settings.allowTurn">
|
||||
<p class="status">Both people must opt in. Your browser may contact this relay and route encrypted file traffic through it. The operator sees addresses, timing and traffic volume, and may charge for bandwidth. Use credentials you are authorized to use; they remain in this tab.</p>
|
||||
<label v-if="iceEndpoint" class="checkbox"><input type="checkbox" v-model="settings.managedTurn" /> Use the configured relay with temporary credentials</label>
|
||||
<template v-if="iceEndpoint && settings.managedTurn">
|
||||
<p v-if="!managedCredentials" class="status">The relay details will appear here when you create a connection code.</p>
|
||||
<input class="stun-input" aria-label="TURN address" :value="Array.isArray(managedCredentials?.turnUrl) ? managedCredentials.turnUrl.join(', ') : managedCredentials?.turnUrl || ''" placeholder="TURN address (filled when creating a code)" readonly />
|
||||
<input class="stun-input" aria-label="TURN username" :value="managedCredentials?.username || ''" placeholder="TURN username (filled when creating a code)" readonly />
|
||||
<input class="stun-input" type="password" aria-label="TURN password" :value="managedCredentials?.credential || ''" placeholder="TURN password (filled when creating a code)" autocomplete="off" readonly />
|
||||
</template>
|
||||
<template v-else>
|
||||
<input v-model="settings.turnUrl" class="stun-input" aria-label="TURN address" placeholder="turns:relay.example:5349?transport=tcp" autocomplete="off" />
|
||||
<input v-model="settings.username" class="stun-input" aria-label="TURN username" placeholder="TURN username" autocomplete="off" />
|
||||
<input v-model="settings.credential" class="stun-input" type="password" aria-label="TURN password" placeholder="TURN password" autocomplete="off" />
|
||||
</template>
|
||||
</template>
|
||||
</fieldset>
|
||||
<fieldset class="network-settings">
|
||||
<legend>Connection discovery</legend>
|
||||
<label for="discovery">Find paired devices with</label>
|
||||
<select id="discovery" v-model="discovery.choice" class="stun-select">
|
||||
<option value="manual">Manual codes only</option>
|
||||
<option v-if="defaultTracker" value="default">Default tracker ({{ host(defaultTracker) }})</option>
|
||||
<option value="custom">Custom tracker…</option>
|
||||
</select>
|
||||
<input v-if="discovery.choice === 'custom'" id="tracker-url" v-model="discovery.custom" class="stun-input" aria-label="Custom tracker address" placeholder="wss://tracker.example" autocomplete="off" spellcheck="false" />
|
||||
<p class="status">A WebTorrent tracker lets paired devices find each other, so both people press Reconnect instead of exchanging codes. Its operator sees your IP addresses and when your devices meet, not your codes or files. This applies to new reconnect setups; existing ones keep their tracker.</p>
|
||||
</fieldset>
|
||||
</template>
|
||||
@@ -1,799 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { asError } from '../lib/validation.ts';
|
||||
import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts';
|
||||
import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.ts';
|
||||
import { computed, onActivated, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import DeviceSettings from './DeviceSettings.vue';
|
||||
import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts';
|
||||
import NetworkSettings from './NetworkSettings.vue';
|
||||
import { acceptAnswer, createAnswer, createOffer, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
import { createRef, decodeCode, encodeCode, MAX_INPUT_LENGTH } from '../lib/codes.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 { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts';
|
||||
import type { ConnectionUpdate, SavedConnection } from '../lib/connections.ts';
|
||||
import { derivePairing, discoveryId, discoveryTracker, loadDiscovery, pairingCheck, pairingNonce, parseCheck, parseNonce, saveDiscovery, signalingKey, trackerUrl, type ReconnectPairing } from '../lib/reconnect.ts';
|
||||
import { ReconnectAttempt } from '../lib/tracker.ts';
|
||||
import type { Identity } from '../lib/identity.ts';
|
||||
|
||||
type Step = 'session-ready' | 'idle' | 'discovering' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
|
||||
interface Session {
|
||||
pc: RTCPeerConnection;
|
||||
// Offers and creates the data channel. Manual setup follows Send/Receive;
|
||||
// tracker reconnect lets the lower device key offer.
|
||||
initiator: boolean;
|
||||
options: IceOptions;
|
||||
controller: AbortController;
|
||||
transfer: FileSession | null;
|
||||
diagnostics: ConnectionDiagnostics;
|
||||
localHello?: IdentityHello;
|
||||
remoteHello?: IdentityHello;
|
||||
identityContext?: IdentityContext;
|
||||
identity?: IdentityState['identity'];
|
||||
expected?: string;
|
||||
// Shared by this session's offer and answer codes.
|
||||
ref?: string;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const props = defineProps<{ sending?: boolean; connection: SavedConnection; loadTrust: () => Promise<SavedConnection>; saveReconnect: (reconnect: ReconnectPairing | null) => Promise<void> }>();
|
||||
const devices = ref<InstanceType<typeof DeviceSettings> | null>(null);
|
||||
const identityStatus = ref('');
|
||||
// Offered on the verification step whenever the verified peer would change
|
||||
// this connection's paired device: 'new' starts ticked, 'replace' does not.
|
||||
const pairing = ref<'' | 'new' | 'replace'>(''), rememberPeer = ref(false);
|
||||
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 emit = defineEmits<{ sessionChange: [active: boolean]; connectedChange: [connected: boolean]; update: [change: ConnectionUpdate] }>();
|
||||
const inputCode = ref('');
|
||||
const outputCode = ref('');
|
||||
const step = ref<Step>('idle');
|
||||
const error = ref('');
|
||||
const copied = ref(false);
|
||||
const fps = ref<Fingerprints | null>(null);
|
||||
const verified = ref(false);
|
||||
const progress = ref(0);
|
||||
const incoming = ref<FileMetadata | null>(null);
|
||||
const downloadUrl = ref('');
|
||||
const downloadName = ref('');
|
||||
const connected = ref(false);
|
||||
const sendSection = ref<HTMLElement | null>(null);
|
||||
const receiveSection = ref<HTMLElement | null>(null);
|
||||
watch(connected, value => emit('connectedChange', value));
|
||||
function focusDirection(direction: 'send' | 'receive') {
|
||||
const section = direction === 'send' ? sendSection.value : receiveSection.value;
|
||||
section?.focus({ preventScroll: true });
|
||||
section?.scrollIntoView({ block: 'start', behavior: 'auto' });
|
||||
}
|
||||
defineExpose({ focusDirection });
|
||||
|
||||
const choosing = ref(false);
|
||||
const dragover = ref(false);
|
||||
const diagnosticLines = ref<string[]>([]);
|
||||
let latestDiagnostics: ConnectionDiagnostics | null = null;
|
||||
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||
const defaultStun = import.meta.env.VITE_STUN_URL || '';
|
||||
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||
const managedCredentials = ref<IceOptions | null>(null);
|
||||
// Shared by all connections in this browser; reloaded when a cached workspace
|
||||
// returns, since another connection may have changed it.
|
||||
const defaultTracker = import.meta.env.VITE_TRACKER_URL || '';
|
||||
const discovery = ref(loadDiscovery(defaultTracker));
|
||||
watch(discovery, saveDiscovery, { deep: true });
|
||||
onActivated(() => { discovery.value = loadDiscovery(defaultTracker); });
|
||||
// Every size is received the same way: streamed to Downloads where supported, otherwise
|
||||
// through the native save picker, otherwise buffered in memory (capped) and saved on completion.
|
||||
const receiveMethod = computed(() => {
|
||||
if (!incoming.value) return null;
|
||||
if (supportsStreamingDownload()) return 'download';
|
||||
if (typeof window.showSaveFilePicker === 'function') return 'disk';
|
||||
return incoming.value.size <= MEMORY_LIMIT ? 'memory' : null;
|
||||
});
|
||||
const savedToDisk = ref(false);
|
||||
let active: Session | null = null;
|
||||
// Tracker reconnect: one attempt per slot and browser profile, cancelled by
|
||||
// reset, failure and unmount. reconnectRun invalidates stale async steps.
|
||||
let attempt: ReconnectAttempt | null = null, releaseLock: (() => void) | null = null, attemptTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let reconnectRun = 0;
|
||||
const discoveryHost = ref(''), discoveryPeers = ref(0);
|
||||
// Reconnect setup over a session whose peer proved the paired device key.
|
||||
const authenticatedPeer = ref('');
|
||||
const pairingState = ref<'' | 'proposed' | 'incoming' | 'accepted' | 'saving' | 'awaiting-stored' | 'done'>(''), pairingError = ref('');
|
||||
// Set when the peer's stored pairing matched this one during this session.
|
||||
const pairingConfirmed = ref(false);
|
||||
const incomingTracker = ref('');
|
||||
let pairingSetup: { tracker: string; proposer: string; acceptor?: string; key?: CryptoKey; stored?: boolean } | null = null;
|
||||
const pairingBusy = () => ['proposed', 'accepted', 'saving', 'awaiting-stored'].includes(pairingState.value);
|
||||
const selectedTracker = computed(() => {
|
||||
try { return { url: discoveryTracker(discovery.value, defaultTracker), error: '' }; }
|
||||
catch (err) { return { url: '', error: asError(err).message }; }
|
||||
});
|
||||
const canPair = computed(() => connected.value && !!authenticatedPeer.value && authenticatedPeer.value === props.connection.peerKey);
|
||||
const trackerHost = (url: string) => { try { return new URL(url).host; } catch { return url; } };
|
||||
let copyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const busy = computed(() => !['idle', 'closed', 'done', 'session-ready'].includes(step.value));
|
||||
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.',
|
||||
discovering: discoveryPeers.value ? 'Your peer is online. Connecting…' : `Waiting for your peer on ${discoveryHost.value}. Ask them to open this connection and press Reconnect.`,
|
||||
gathering: 'Gathering connection info (up to 30 seconds)…',
|
||||
'offer-ready': 'Send your code through an authenticated channel, then paste the answer.',
|
||||
'answer-ready': 'Send your answer back, then compare both full fingerprints.',
|
||||
verification: verified.value ? 'Waiting for the connection and your peer’s verification…' : 'Compare both full fingerprints before confirming.',
|
||||
'waiting-accept': 'Waiting for the receiver to accept the file…',
|
||||
'choose-storage': 'Accept or decline this file.',
|
||||
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
|
||||
'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…',
|
||||
done: lastDirection.value === 'send' ? 'The receiver confirmed the complete file.' : (savedToDisk.value ? 'File saved to disk.' : 'File handed to your browser. Check Downloads for the final save result.'),
|
||||
closed: props.sending
|
||||
? '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.',
|
||||
}[step.value] || ''));
|
||||
|
||||
function revokeDownload() {
|
||||
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
|
||||
downloadUrl.value = ''; downloadName.value = '';
|
||||
}
|
||||
function saveDownload() {
|
||||
const link = document.createElement('a');
|
||||
link.href = downloadUrl.value; link.download = downloadName.value;
|
||||
document.body.append(link); link.click(); link.remove();
|
||||
}
|
||||
function dispose() {
|
||||
const old = active;
|
||||
if (old) {
|
||||
if (outgoing.value && sendState.value && !['done', 'closed'].includes(sendState.value)) sendState.value = 'closed';
|
||||
if (incoming.value && receiveState.value && !['done', 'closed'].includes(receiveState.value)) receiveState.value = 'closed';
|
||||
}
|
||||
active = null; connected.value = false; queuedFiles.value = []; emit('sessionChange', false);
|
||||
authenticatedPeer.value = ''; pairingState.value = ''; pairingError.value = ''; pairingSetup = null; pairingConfirmed.value = false;
|
||||
managedCredentials.value = null; settings.value.allowTurn = false;
|
||||
if (!old) return;
|
||||
clearTimeout(old.timer);
|
||||
// Start the snapshot before aborting/closing anything; close the peer after
|
||||
// stats resolve (bounded to 300 ms), so failure evidence remains available.
|
||||
void old.diagnostics.finish(() => old.pc.close());
|
||||
old.controller.abort();
|
||||
old.transfer?.close();
|
||||
old.pc.ondatachannel = old.pc.onconnectionstatechange = null;
|
||||
}
|
||||
function stopAttempt() {
|
||||
reconnectRun++; clearTimeout(attemptTimer);
|
||||
attempt?.close(); attempt = null;
|
||||
releaseLock?.(); releaseLock = null;
|
||||
}
|
||||
function reset(keepNetwork = false) {
|
||||
const allowTurn = settings.value.allowTurn;
|
||||
stopAttempt(); dispose(); revokeDownload(); clearTimeout(copyTimer);
|
||||
if (keepNetwork) settings.value.allowTurn = allowTurn;
|
||||
latestDiagnostics = null; diagnosticLines.value = [];
|
||||
managedCredentials.value = null;
|
||||
if (!keepNetwork) settings.value.allowTurn = false;
|
||||
inputCode.value = outputCode.value = error.value = '';
|
||||
identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false;
|
||||
fps.value = incoming.value = null;
|
||||
verified.value = copied.value = choosing.value = false;
|
||||
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; savedToDisk.value = false;
|
||||
sendState.value = receiveState.value = null; outgoing.value = null;
|
||||
}
|
||||
function fail(session: Session, err: unknown) {
|
||||
if (active !== session) return;
|
||||
session.diagnostics.record('session failed');
|
||||
stopAttempt(); dispose();
|
||||
managedCredentials.value = null;
|
||||
fps.value = incoming.value = null;
|
||||
outputCode.value = ''; verified.value = 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';
|
||||
}
|
||||
function pickFiles(event: Event) {
|
||||
const list = event.target instanceof HTMLInputElement ? event.target.files
|
||||
: event instanceof DragEvent ? event.dataTransfer?.files : null;
|
||||
const files = Array.from(list || []);
|
||||
if (!files.length) return;
|
||||
try {
|
||||
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 disconnect() {
|
||||
stopAttempt(); 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) {
|
||||
if (active !== session) { channel.close(); return; }
|
||||
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;
|
||||
}
|
||||
const transfer = session.transfer = new FileSession(channel, session.initiator, {
|
||||
onReady: () => { if (active === session) {
|
||||
connected.value = true; step.value = 'session-ready'; clearTimeout(session.timer);
|
||||
stopAttempt();
|
||||
// Ready implies both fresh proofs verified, so the key may now be saved.
|
||||
if (session.identityContext && session.remoteHello) {
|
||||
const key = session.remoteHello.key;
|
||||
if (session.expected === key) { identityStatus.value = 'Paired device authenticated for this connection.'; authenticatedPeer.value = key; }
|
||||
else if (rememberPeer.value) { emit('update', { peerKey: key }); identityStatus.value = `Device proof checked. Remembered for ${props.connection.name}.`; authenticatedPeer.value = key; }
|
||||
else identityStatus.value = 'Device proof checked. This device was not remembered.';
|
||||
if (authenticatedPeer.value) void sendPairingCheck(session);
|
||||
}
|
||||
// Files chosen before connecting join the queue once the session is ready,
|
||||
// so a replaced reconnect peer never takes them along.
|
||||
if (selectedFiles.value.length) {
|
||||
try { transfer.add(selectedFiles.value); selectedFiles.value = []; file.value = null; }
|
||||
catch (err) { error.value = asError(err).message; }
|
||||
}
|
||||
} },
|
||||
onPairing: message => void receivePairing(session, message),
|
||||
onQueue: items => { if (active === session) queuedFiles.value = items; },
|
||||
onState: (direction, state, meta) => {
|
||||
if (active !== session) return;
|
||||
step.value = state; lastDirection.value = direction;
|
||||
session.diagnostics.record(`transfer ${direction} ${state}`);
|
||||
if (state === 'done') session.diagnostics.record('transfer done');
|
||||
if (direction === 'send') { sendState.value = state; outgoing.value = meta; if (state === 'waiting-accept') progress.value = 0; }
|
||||
else { receiveState.value = state; if (state === 'choose-storage' && meta.name) { incoming.value = meta; receiveProgress.value = 0; savedToDisk.value = false; } }
|
||||
},
|
||||
onProgress: (direction, bytes, size) => {
|
||||
if (active !== session) return;
|
||||
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;
|
||||
void session.diagnostics.capture();
|
||||
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; saveDownload(); }
|
||||
},
|
||||
onDecline: direction => {
|
||||
if (active !== session) return;
|
||||
if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; }
|
||||
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),
|
||||
});
|
||||
configureIdentity(session);
|
||||
if (verified.value) session.transfer.verify();
|
||||
}
|
||||
function start(initiator: boolean) {
|
||||
const chosen = settings.value;
|
||||
const options = {
|
||||
...chosen,
|
||||
stunUrl: chosen.stunChoice === 'custom' ? chosen.customStun.trim() || null : STUN_PROVIDERS.find(p => p.id === chosen.stunChoice)?.url ?? null,
|
||||
turnUrl: chosen.turnUrl.trim(),
|
||||
};
|
||||
// Fetch managed credentials before gathering, while retaining normal cancellation.
|
||||
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
|
||||
let diagnostics: ConnectionDiagnostics;
|
||||
diagnostics = new ConnectionDiagnostics(pc, lines => {
|
||||
if (latestDiagnostics === diagnostics) diagnosticLines.value = lines;
|
||||
});
|
||||
latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines];
|
||||
const session: Session = { pc, initiator, options, controller: new AbortController(), transfer: null, diagnostics };
|
||||
active = session; emit('sessionChange', true);
|
||||
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.onconnectionstatechange = () => {
|
||||
if (active !== session) return;
|
||||
if (['failed', 'closed'].includes(pc.connectionState)) {
|
||||
const unfinished = [sendState.value, receiveState.value].some(state => state && state !== 'done' && state !== 'closed');
|
||||
if (connected.value && !unfinished) disconnect();
|
||||
else fail(session, new Error(connected.value
|
||||
? 'Connection lost. Unfinished files were cancelled. Exchange fresh codes to reconnect.'
|
||||
: 'Could not establish the peer connection. Retry with fresh codes. If it fails again, copy Connection diagnostics from both devices.'));
|
||||
}
|
||||
};
|
||||
return session;
|
||||
}
|
||||
async function createCode() {
|
||||
const pasted = inputCode.value;
|
||||
reset(true); inputCode.value = props.sending ? '' : pasted; step.value = 'gathering';
|
||||
let session: Session | undefined;
|
||||
try {
|
||||
if (props.sending) {
|
||||
if (!file.value) throw new Error('Choose a file first.');
|
||||
validateMetadata({ name: file.value.name, size: file.value.size, mime: file.value.type || '' });
|
||||
}
|
||||
session = start(!!props.sending);
|
||||
// Re-read saved trust for each connection; another tab may have forgotten
|
||||
// the paired peer or replaced the local identity since this page loaded.
|
||||
if (props.connection.rememberDevice) {
|
||||
const trust = await props.loadTrust();
|
||||
const identity = trust.rememberDevice ? await devices.value?.refreshIdentity() : null;
|
||||
if (active !== session) return;
|
||||
if (trust.rememberDevice) session.expected = trust.peerKey;
|
||||
if (identity) { session.identity = identity; session.localHello = hello(identity); }
|
||||
}
|
||||
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
|
||||
if (active !== session) return;
|
||||
session.pc.setConfiguration(iceConfiguration(configured));
|
||||
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
|
||||
const offer = props.sending ? null : await decodeCode(pasted, { type: 'offer', allowTurn: session.options.allowTurn });
|
||||
if (active !== session) return;
|
||||
session.ref = offer ? offer.ref : createRef(); session.remoteHello = offer?.identity;
|
||||
const options = { ...session.options, signal: session.controller.signal };
|
||||
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
|
||||
const sdp = offer ? await createAnswer(session.pc, offer.sdp, options) : await createOffer(session.pc, options);
|
||||
if (active !== session) return;
|
||||
const code = await encodeCode({ type: props.sending ? 'offer' : 'answer', ref: session.ref, sdp, identity: session.localHello });
|
||||
if (active !== session) return;
|
||||
outputCode.value = code;
|
||||
session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready');
|
||||
session.diagnostics.descriptions();
|
||||
void session.diagnostics.capture();
|
||||
if (!props.sending) { fps.value = getFingerprints(session.pc, options); offerPairing(session); configureIdentity(session); }
|
||||
step.value = props.sending ? 'offer-ready' : 'answer-ready';
|
||||
} catch (err) {
|
||||
if (session) fail(session, err);
|
||||
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; }
|
||||
}
|
||||
}
|
||||
async function useAnswer() {
|
||||
const session = active;
|
||||
if (!session || step.value !== 'offer-ready') return;
|
||||
error.value = '';
|
||||
step.value = 'verification';
|
||||
try {
|
||||
const answer = await decodeCode(inputCode.value, { type: 'answer', ref: session.ref, allowTurn: session.options.allowTurn });
|
||||
if (active !== session) return;
|
||||
session.remoteHello = answer.identity;
|
||||
await acceptAnswer(session.pc, answer.sdp, session.options);
|
||||
if (active !== session) return;
|
||||
session.diagnostics.record('answer applied');
|
||||
session.diagnostics.descriptions();
|
||||
void session.diagnostics.capture();
|
||||
fps.value = getFingerprints(session.pc, session.options);
|
||||
offerPairing(session);
|
||||
configureIdentity(session);
|
||||
} catch (err) {
|
||||
if (active !== session) return;
|
||||
// A rejected answer does not consume a valid local offer. Let the user
|
||||
// correct a paste error instead of silently invalidating both peers' codes.
|
||||
if (session.pc.signalingState === 'have-local-offer') {
|
||||
error.value = `${asError(err, 'Invalid answer.').message} Correct the answer and connect again; your offer is still valid.`;
|
||||
step.value = 'offer-ready';
|
||||
} else fail(session, err);
|
||||
}
|
||||
}
|
||||
function offerPairing(session: Session) {
|
||||
const key = session.localHello && session.remoteHello?.key;
|
||||
pairing.value = !key || key === session.expected ? '' : session.expected ? 'replace' : 'new';
|
||||
rememberPeer.value = pairing.value === 'new';
|
||||
}
|
||||
function configureIdentity(session: Session) {
|
||||
if (!fps.value || !session.transfer || session.identityContext) return;
|
||||
if (!session.identity || !session.localHello || !session.remoteHello) {
|
||||
if (session.expected) identityStatus.value = 'A device identity is missing. Compare both fingerprints manually; the paired device is not being used.';
|
||||
else if (session.localHello || session.remoteHello) identityStatus.value = 'Both people must use their device identity to remember each other. Compare fingerprints manually for this connection.';
|
||||
return;
|
||||
}
|
||||
const initiator = session.initiator;
|
||||
const context: IdentityContext = {
|
||||
offer: initiator ? session.localHello : session.remoteHello,
|
||||
answer: initiator ? session.remoteHello : session.localHello,
|
||||
offerFingerprint: initiator ? fps.value.local : fps.value.remote,
|
||||
answerFingerprint: initiator ? fps.value.remote : fps.value.local,
|
||||
};
|
||||
session.identityContext = context;
|
||||
const identity = session.identity;
|
||||
session.transfer.authenticate({ sign: () => signIdentity(identity, context, initiator), verify: proof => verifyIdentity(proof, context, !initiator) });
|
||||
if (session.expected === session.remoteHello.key) {
|
||||
identityStatus.value = 'Checking the paired device’s fresh proof…'; verify();
|
||||
} else {
|
||||
identityStatus.value = session.expected ? 'Device identity differs from the paired device. Compare both fingerprints manually before continuing. The paired device is only replaced if you choose to.' : 'New device. Compare both fingerprints manually before remembering it.';
|
||||
}
|
||||
}
|
||||
function verify() {
|
||||
if (!active || !fps.value || verified.value) return;
|
||||
verified.value = true; step.value = 'verification';
|
||||
// Gathering/handshake timeout ends; Transfer manages verification and transfer deadlines.
|
||||
const session = active;
|
||||
clearTimeout(session.timer);
|
||||
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
|
||||
session.transfer?.verify();
|
||||
}
|
||||
// Holds a Web Lock for the attempt so two tabs of this browser never reconnect
|
||||
// the same slot at once. Resolves null when another tab holds it.
|
||||
function exclusive(name: string) {
|
||||
if (!navigator.locks) return Promise.resolve<(() => void) | null>(() => {});
|
||||
return new Promise<(() => void) | null>(resolve => {
|
||||
navigator.locks.request(name, { ifAvailable: true }, lock => lock ? new Promise<void>(release => resolve(release)) : resolve(null)).catch(() => resolve(null));
|
||||
});
|
||||
}
|
||||
function abortReconnect(err: unknown) {
|
||||
if (active) { fail(active, err); return; }
|
||||
stopAttempt(); settings.value.allowTurn = false;
|
||||
emit('sessionChange', false);
|
||||
error.value = asError(err).message; step.value = 'closed';
|
||||
}
|
||||
interface ReconnectContext { run: number; identity: Identity; peerKey: string }
|
||||
const cancelled = () => new Error('Reconnect cancelled.');
|
||||
// Each offer or answer gets a fresh peer connection; the previous one is closed.
|
||||
async function reconnectPeer(context: ReconnectContext, initiator: boolean) {
|
||||
if (context.run !== reconnectRun) throw cancelled();
|
||||
const allowTurn = settings.value.allowTurn;
|
||||
if (active) dispose();
|
||||
settings.value.allowTurn = allowTurn;
|
||||
fps.value = null; verified.value = false; identityStatus.value = '';
|
||||
const session = start(initiator);
|
||||
session.expected = context.peerKey; session.identity = context.identity; session.localHello = hello(context.identity);
|
||||
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
|
||||
if (active !== session) throw cancelled();
|
||||
session.pc.setConfiguration(iceConfiguration(configured));
|
||||
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
|
||||
return session;
|
||||
}
|
||||
function checkPeer(context: ReconnectContext, key: string | undefined) {
|
||||
if (key !== context.peerKey) throw new Error('A different device answered on this pairing. Exchange codes manually to check it.');
|
||||
}
|
||||
async function reconnectOffer(context: ReconnectContext) {
|
||||
const session = await reconnectPeer(context, true);
|
||||
session.ref = createRef();
|
||||
attach(session, session.pc.createDataChannel('hellcon-v3'));
|
||||
const sdp = await createOffer(session.pc, { ...session.options, signal: session.controller.signal });
|
||||
if (active !== session) throw cancelled();
|
||||
session.diagnostics.record('reconnect offer ready');
|
||||
return encodeCode({ type: 'offer', ref: session.ref, sdp, identity: session.localHello });
|
||||
}
|
||||
async function reconnectAnswer(context: ReconnectContext, text: string) {
|
||||
const session = await reconnectPeer(context, false);
|
||||
const offer = await decodeCode(text, { type: 'offer', allowTurn: session.options.allowTurn });
|
||||
if (active !== session) throw cancelled();
|
||||
checkPeer(context, offer.identity?.key);
|
||||
session.ref = offer.ref; session.remoteHello = offer.identity;
|
||||
const options = { ...session.options, signal: session.controller.signal };
|
||||
const sdp = await createAnswer(session.pc, offer.sdp, options);
|
||||
if (active !== session) throw cancelled();
|
||||
const code = await encodeCode({ type: 'answer', ref: session.ref, sdp, identity: session.localHello });
|
||||
session.diagnostics.record('reconnect answer ready');
|
||||
fps.value = getFingerprints(session.pc, options); configureIdentity(session);
|
||||
return code;
|
||||
}
|
||||
async function reconnectAccept(context: ReconnectContext, text: string) {
|
||||
const session = active;
|
||||
if (context.run !== reconnectRun || !session?.initiator || !session.ref) throw cancelled();
|
||||
const answer = await decodeCode(text, { type: 'answer', ref: session.ref, allowTurn: session.options.allowTurn });
|
||||
if (active !== session) throw cancelled();
|
||||
checkPeer(context, answer.identity?.key);
|
||||
session.remoteHello = answer.identity;
|
||||
await acceptAnswer(session.pc, answer.sdp, session.options);
|
||||
if (active !== session) throw cancelled();
|
||||
session.diagnostics.record('answer applied');
|
||||
fps.value = getFingerprints(session.pc, session.options); configureIdentity(session);
|
||||
}
|
||||
async function reconnect() {
|
||||
if (busy.value || connected.value) return;
|
||||
reset(true);
|
||||
const run = reconnectRun;
|
||||
step.value = 'discovering'; discoveryPeers.value = 0; emit('sessionChange', true);
|
||||
try {
|
||||
const release = await exclusive(`hellcon-reconnect-${props.connection.id}`);
|
||||
if (run !== reconnectRun) { release?.(); return; }
|
||||
if (!release) throw new Error('Another HellCon tab is already reconnecting this connection.');
|
||||
releaseLock = release;
|
||||
// Re-read trust and identity: another tab may have forgotten the device.
|
||||
const trust = await props.loadTrust();
|
||||
const pairing = trust.reconnect;
|
||||
if (!pairing) throw new Error('Reconnect is not set up for this connection. Exchange codes manually.');
|
||||
const identity = await devices.value?.refreshIdentity();
|
||||
if (run !== reconnectRun) return;
|
||||
if (!identity || identity.publicKey !== pairing.localKey) throw new Error('This browser’s device identity changed since reconnect was set up. Exchange codes manually and set it up again.');
|
||||
const [infoHash, key] = await Promise.all([discoveryId(pairing.key), signalingKey(pairing.key)]);
|
||||
if (run !== reconnectRun) return;
|
||||
const url = pairing.trackers[0]!;
|
||||
discoveryHost.value = trackerHost(url);
|
||||
const context: ReconnectContext = { run, identity, peerKey: pairing.peerKey };
|
||||
const current: ReconnectAttempt = new ReconnectAttempt({
|
||||
url, infoHash, key, initiator: identity.publicKey < pairing.peerKey,
|
||||
hooks: {
|
||||
createOffer: () => reconnectOffer(context),
|
||||
createAnswer: offer => reconnectAnswer(context, offer),
|
||||
acceptAnswer: answer => reconnectAccept(context, answer),
|
||||
onPeers: count => { if (attempt === current) discoveryPeers.value = count; },
|
||||
onError: err => { if (attempt === current) abortReconnect(err); },
|
||||
},
|
||||
});
|
||||
attempt = current;
|
||||
attemptTimer = setTimeout(() => abortReconnect(new Error('Reconnect timed out. Check that both people pressed Reconnect, or exchange codes manually.')), 5 * 60 * 1000);
|
||||
await current.start();
|
||||
} catch (err) { if (run === reconnectRun) abortReconnect(err); }
|
||||
}
|
||||
function derivePairingKey(session: Session, setup: { tracker: string; proposer: string; acceptor?: string }, proposer: boolean) {
|
||||
const context = session.identityContext, local = session.localHello?.key, remote = session.remoteHello?.key;
|
||||
if (!context || !local || !remote || !setup.acceptor) throw new Error('Reconnect needs a session authenticated by both device identities.');
|
||||
return derivePairing({
|
||||
proposerNonce: setup.proposer, acceptorNonce: setup.acceptor,
|
||||
proposerKey: proposer ? local : remote, acceptorKey: proposer ? remote : local,
|
||||
offerFingerprint: context.offerFingerprint, answerFingerprint: context.answerFingerprint, tracker: setup.tracker,
|
||||
});
|
||||
}
|
||||
async function storePairing(session: Session, setup: NonNullable<typeof pairingSetup>, key: CryptoKey) {
|
||||
await props.saveReconnect({ version: 1, trackers: [setup.tracker], key, localKey: session.localHello!.key, peerKey: session.remoteHello!.key });
|
||||
setup.stored = true;
|
||||
}
|
||||
// Each authenticated session compares stored pairings, so an interrupted setup,
|
||||
// a failed write or Turn off reconnect on one side is noticed on the other.
|
||||
async function sendPairingCheck(session: Session) {
|
||||
const pairing = props.connection.reconnect;
|
||||
try {
|
||||
const value = pairing && pairing.peerKey === authenticatedPeer.value ? await pairingCheck(pairing.key) : '';
|
||||
if (active === session) session.transfer?.sendPairing({ step: 'check', value });
|
||||
} catch { /* the session ended */ }
|
||||
}
|
||||
async function receivePairingCheck(session: Session, value: string) {
|
||||
const pairing = props.connection.reconnect;
|
||||
if (!pairing || !authenticatedPeer.value || pairing.peerKey !== authenticatedPeer.value) return;
|
||||
const matches = value === await pairingCheck(pairing.key);
|
||||
if (active !== session || pairingBusy() || props.connection.reconnect !== pairing) return;
|
||||
if (matches) { pairingConfirmed.value = true; return; }
|
||||
await props.saveReconnect(null);
|
||||
if (active === session) pairingError.value = 'Your peer’s device has no matching reconnect settings, so reconnect was turned off here as well. Set it up again to use it.';
|
||||
}
|
||||
// The proposer suggests a tracker; the peer sees it and accepts before anything
|
||||
// is stored or contacted. Both contribute a nonce; the proposer stores first,
|
||||
// and the acceptor's write is acknowledged before either reports success. If
|
||||
// the peer's write fails, the proposer removes its own copy again.
|
||||
function proposePairing() {
|
||||
const session = active;
|
||||
if (!session?.transfer || !canPair.value || pairingBusy()) return;
|
||||
try {
|
||||
if (!selectedTracker.value.url) throw new Error(selectedTracker.value.error || 'Choose a tracker under Network settings → Connection discovery.');
|
||||
pairingSetup = { tracker: selectedTracker.value.url, proposer: pairingNonce() };
|
||||
session.transfer.sendPairing({ step: 'propose', tracker: pairingSetup.tracker, nonce: pairingSetup.proposer });
|
||||
pairingState.value = 'proposed'; pairingError.value = '';
|
||||
} catch (err) { pairingError.value = asError(err).message; }
|
||||
}
|
||||
async function acceptPairing() {
|
||||
const session = active, setup = pairingSetup;
|
||||
if (!session?.transfer || pairingState.value !== 'incoming' || !setup) return;
|
||||
// Claim this proposal before key derivation yields; a second click must not
|
||||
// replace its nonce or send a second acceptance while Vue is rerendering.
|
||||
pairingState.value = 'accepted';
|
||||
try {
|
||||
setup.acceptor = pairingNonce();
|
||||
setup.key = await derivePairingKey(session, setup, false);
|
||||
if (active !== session || pairingSetup !== setup) return;
|
||||
session.transfer.sendPairing({ step: 'accept', nonce: setup.acceptor });
|
||||
} catch (err) {
|
||||
if (active !== session || pairingSetup !== setup) return;
|
||||
try { session.transfer.sendPairing({ step: 'error' }); } catch { /* the session ended */ }
|
||||
pairingState.value = ''; pairingSetup = null; pairingError.value = asError(err).message;
|
||||
}
|
||||
}
|
||||
function declinePairing() {
|
||||
try { active?.transfer?.sendPairing({ step: 'decline' }); } catch { /* the session ended */ }
|
||||
pairingState.value = ''; pairingSetup = null;
|
||||
}
|
||||
async function receivePairing(session: Session, message: Record<string, unknown>) {
|
||||
if (active !== session) return;
|
||||
try {
|
||||
if (message.step === 'propose') {
|
||||
if (pairingBusy()) throw new Error('You both proposed reconnect at once. Let one person set it up.');
|
||||
if (!canPair.value) {
|
||||
session.transfer?.sendPairing({ step: 'decline' });
|
||||
throw new Error('Your peer proposed tracker reconnect, but this connection has not remembered their device.');
|
||||
}
|
||||
pairingSetup = { tracker: trackerUrl(message.tracker), proposer: parseNonce(message.nonce) };
|
||||
incomingTracker.value = pairingSetup.tracker; pairingState.value = 'incoming'; pairingError.value = '';
|
||||
} else if (message.step === 'accept' && pairingState.value === 'proposed' && pairingSetup) {
|
||||
const setup = pairingSetup;
|
||||
setup.acceptor = parseNonce(message.nonce);
|
||||
const key = await derivePairingKey(session, setup, true);
|
||||
if (active !== session || pairingSetup !== setup) return;
|
||||
pairingState.value = 'saving';
|
||||
await storePairing(session, setup, key);
|
||||
if (active !== session || pairingSetup !== setup) return;
|
||||
session.transfer?.sendPairing({ step: 'done' });
|
||||
pairingState.value = 'awaiting-stored';
|
||||
} else if (message.step === 'done' && pairingState.value === 'accepted' && pairingSetup?.key) {
|
||||
const setup = pairingSetup;
|
||||
const key = setup.key!;
|
||||
pairingState.value = 'saving';
|
||||
await storePairing(session, setup, key);
|
||||
if (active !== session || pairingSetup !== setup) return;
|
||||
session.transfer?.sendPairing({ step: 'stored' });
|
||||
pairingState.value = 'done'; pairingConfirmed.value = true;
|
||||
} else if (message.step === 'stored' && pairingState.value === 'awaiting-stored' && pairingSetup) {
|
||||
pairingState.value = 'done'; pairingConfirmed.value = true;
|
||||
} else if (message.step === 'error') {
|
||||
// Without a setup in progress, this side already reported its own error.
|
||||
const setup = pairingSetup;
|
||||
if (!setup) return;
|
||||
pairingState.value = ''; pairingSetup = null;
|
||||
pairingError.value = 'Your peer could not finish reconnect setup. Check their browser storage and try again.';
|
||||
if (setup.stored) {
|
||||
try { await props.saveReconnect(null); }
|
||||
catch (err) { pairingError.value = `Your peer could not finish reconnect setup, and turning it off here failed too: ${asError(err).message}`; }
|
||||
}
|
||||
} else if (message.step === 'decline') {
|
||||
if (pairingBusy()) pairingError.value = 'Your peer declined tracker reconnect.';
|
||||
pairingState.value = ''; pairingSetup = null;
|
||||
} else if (message.step === 'check') {
|
||||
await receivePairingCheck(session, parseCheck(message.value));
|
||||
} else throw new Error('Unexpected reconnect setup message.');
|
||||
} catch (err) { if (active === session) {
|
||||
if (pairingSetup && message.step !== 'error') {
|
||||
try { session.transfer?.sendPairing({ step: 'error' }); } catch { /* the session ended */ }
|
||||
}
|
||||
pairingState.value = ''; pairingSetup = null; pairingError.value = asError(err).message;
|
||||
} }
|
||||
}
|
||||
async function acceptFile() {
|
||||
const session = active, destination = receiveMethod.value;
|
||||
if (!session?.transfer || !incoming.value || !destination || choosing.value || receiveState.value !== 'choose-storage') return;
|
||||
choosing.value = true; error.value = '';
|
||||
let writable: FileDestination | undefined;
|
||||
try {
|
||||
if (destination === 'download') {
|
||||
writable = await createDownloadDestination(incoming.value, session.controller.signal);
|
||||
if (active !== session) { await writable.abort(); return; }
|
||||
} else if (destination === 'disk') {
|
||||
if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
|
||||
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
|
||||
if (active !== session) return;
|
||||
writable = await handle.createWritable();
|
||||
if (active !== session) { await writable.abort(); return; }
|
||||
}
|
||||
revokeDownload();
|
||||
savedToDisk.value = destination === 'disk';
|
||||
session.diagnostics.record(`storage ${destination}`);
|
||||
session.transfer.accept(writable);
|
||||
} catch (err) {
|
||||
if (writable) await writable.abort().catch(() => {});
|
||||
if (active === session && asError(err).name !== 'AbortError') error.value = asError(err, 'Could not open the destination file.').message;
|
||||
} finally { if (active === session) choosing.value = false; }
|
||||
}
|
||||
async function copy() {
|
||||
const session = active;
|
||||
try {
|
||||
await navigator.clipboard.writeText(outputCode.value);
|
||||
if (active !== session) return;
|
||||
copied.value = true; clearTimeout(copyTimer);
|
||||
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
|
||||
} 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': 'Awaiting acceptance', sending: 'Sending', receiving: 'Receiving', saving: 'Saving', 'awaiting-receipt': 'Waiting for receipt', done: 'Complete', closed: 'Cancelled' })[state] : 'Declined';
|
||||
}
|
||||
function formatBytes(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const index = Math.min(5, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'][index]}`;
|
||||
}
|
||||
function selectCode(event: FocusEvent) {
|
||||
if (event.target instanceof HTMLTextAreaElement) event.target.select();
|
||||
}
|
||||
onBeforeUnmount(() => { stopAttempt(); dispose(); revokeDownload(); clearTimeout(copyTimer); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="panel">
|
||||
<section v-if="sending || connected" ref="sendSection" class="transfer-section" tabindex="-1" aria-labelledby="send-heading">
|
||||
<h2 id="send-heading" class="step">Send files</h2>
|
||||
<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)">
|
||||
<p>Choose or drop files.</p>
|
||||
<input id="file-input" type="file" multiple @change="pickFiles" />
|
||||
</div>
|
||||
<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>
|
||||
<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>
|
||||
</section>
|
||||
<DeviceSettings ref="devices" :paired="connection.peerKey" :remember="connection.rememberDevice" :reconnect="connection.reconnect ? trackerHost(connection.reconnect.trackers[0]!) : ''" :disabled="busy || connected" @update="emit('update', $event)" />
|
||||
<details class="config-details">
|
||||
<summary>Network settings</summary>
|
||||
<NetworkSettings v-model="settings" v-model:discovery="discovery" :disabled="busy || connected" :managed-credentials="managedCredentials" :default-tracker="defaultTracker" />
|
||||
</details>
|
||||
<template v-if="connection.reconnect && !connected">
|
||||
<button class="primary" :disabled="busy" @click="reconnect">Reconnect</button>
|
||||
<p class="status">Both people open {{ connection.name }} and press Reconnect; {{ trackerHost(connection.reconnect.trackers[0]!) }} introduces your browsers. Or exchange codes below.</p>
|
||||
</template>
|
||||
<p v-if="!connected" class="status">Exchange codes privately. They contain your IP address and connection details.</p>
|
||||
<template v-if="!sending">
|
||||
<label class="step" for="offer-input">Paste the sender’s connection code</label>
|
||||
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="busy" />
|
||||
</template>
|
||||
<button class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
|
||||
<template v-if="outputCode">
|
||||
<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" />
|
||||
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
|
||||
</template>
|
||||
<template v-if="sending && outputCode">
|
||||
<label class="step" for="answer-input">Paste the receiver’s answer</label>
|
||||
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="step !== 'offer-ready'" />
|
||||
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
|
||||
</template>
|
||||
<p v-if="identityStatus" class="status" role="status">{{ identityStatus }}</p>
|
||||
<div v-if="fps" class="fingerprint">
|
||||
<h2 class="step">Verify both full SHA-256 fingerprints</h2>
|
||||
<div class="fp-row"><span>Your fingerprint</span><code>{{ fps.local }}</code></div>
|
||||
<div class="fp-row"><span>Their fingerprint</span><code>{{ fps.remote }}</code></div>
|
||||
<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>
|
||||
<label v-if="pairing"><input v-model="rememberPeer" type="checkbox" :disabled="verified" /> {{ pairing === 'new' ? `Remember this device for ${connection.name}` : `Replace the paired device of ${connection.name}` }}</label>
|
||||
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Verification submitted' : 'Both fingerprints match — confirm' }}</button>
|
||||
</div>
|
||||
<section v-if="connected || incoming || downloadUrl" ref="receiveSection" class="transfer-section" tabindex="-1" aria-labelledby="receive-heading">
|
||||
<h2 id="receive-heading" class="step">Receive files</h2>
|
||||
<p v-if="!incoming" class="status">Waiting for your peer to send a file. You can send files yourself using Send above.</p>
|
||||
<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 class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p>
|
||||
<button v-if="receiveMethod" class="primary" :disabled="choosing" @click="acceptFile">Accept file</button>
|
||||
<p v-if="receiveMethod === 'disk'" class="status">Your browser asks where to save this file. Keep this page open until the transfer finishes.</p>
|
||||
<p v-else-if="receiveMethod" class="status">Your browser downloads this file. Allow the download and keep this page open until the transfer finishes.</p>
|
||||
<p v-else class="error">This browser cannot receive files over 64 MiB. Use a browser with streaming-download or file-system saving support, or send a smaller file.</p>
|
||||
</div>
|
||||
<p v-if="incoming && receiveState !== 'choose-storage'" class="status">Receiving: {{ incoming.name }} — {{ stateLabel(receiveState) }} ({{ receiveProgress }}%)</p>
|
||||
<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>
|
||||
<div v-if="downloadUrl" class="file-chip"><span>{{ downloadName }}</span><a class="download" :href="downloadUrl" :download="downloadName">Save again</a></div>
|
||||
</section>
|
||||
<p class="status" role="status">{{ status }}</p>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<details v-if="diagnosticLines.length">
|
||||
<summary>Connection diagnostics</summary>
|
||||
<p class="status">Candidate types and check counters only; no addresses, connection codes, credentials or filenames. Missing counters appear as ?. These details remain available after failure.</p>
|
||||
<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" />
|
||||
</details>
|
||||
<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>
|
||||
<section v-if="canPair" class="reconnect-setup" aria-labelledby="reconnect-heading">
|
||||
<h2 id="reconnect-heading" class="step">Reconnect without codes</h2>
|
||||
<template v-if="pairingState === 'incoming'">
|
||||
<p class="status">Your peer proposes reconnecting through <strong>{{ trackerHost(incomingTracker) }}</strong>. The tracker sees both IP addresses and when you connect, but not your files or codes.</p>
|
||||
<div class="session-actions">
|
||||
<button class="primary" @click="acceptPairing">Accept</button>
|
||||
<button @click="declinePairing">Decline</button>
|
||||
</div>
|
||||
</template>
|
||||
<p v-else-if="pairingState === 'saving'" class="status" role="status">Saving reconnect settings…</p>
|
||||
<p v-else-if="pairingState === 'awaiting-stored'" class="status" role="status">Waiting for your peer to save reconnect settings…</p>
|
||||
<p v-else-if="pairingState === 'proposed' || pairingState === 'accepted'" class="status" role="status">Waiting for your peer to confirm…</p>
|
||||
<p v-else-if="pairingState === 'done'" class="status" role="status">Reconnect is set up on both devices. Next time, both people open {{ connection.name }} and press Reconnect.</p>
|
||||
<template v-else>
|
||||
<p v-if="connection.reconnect" class="status">Reconnect through <strong>{{ trackerHost(connection.reconnect.trackers[0]!) }}</strong> is set up{{ pairingConfirmed ? ' on both devices' : '' }}.</p>
|
||||
<template v-if="selectedTracker.url">
|
||||
<p class="status">Next time, both people press Reconnect instead of exchanging codes. <strong>{{ trackerHost(selectedTracker.url) }}</strong> introduces your browsers: it sees IP addresses and timing, not files or codes. Your peer confirms the tracker first.</p>
|
||||
<button @click="proposePairing">{{ connection.reconnect ? 'Set up reconnect again' : 'Set up reconnect' }}</button>
|
||||
</template>
|
||||
<p v-else-if="selectedTracker.error" class="error">{{ selectedTracker.error }} Fix the tracker under Network settings → Connection discovery.</p>
|
||||
<p v-else-if="!connection.reconnect" class="status">To reconnect without exchanging codes next time, choose a tracker under Network settings → Connection discovery.</p>
|
||||
</template>
|
||||
<p v-if="pairingError" class="error" role="alert">{{ pairingError }}</p>
|
||||
</section>
|
||||
<div v-if="step !== 'idle'" class="session-actions">
|
||||
<button v-if="connected || busy" @click="disconnect">Disconnect</button>
|
||||
<button @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
|
||||
</div>
|
||||
<p class="status">Before connecting, Send/Receive chooses who starts. Once connected, use either button to jump between sending and receiving without disconnecting. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
|
||||
</div>
|
||||
</template>
|
||||
Vendored
-10
@@ -4,13 +4,3 @@ declare module '*.vue' {
|
||||
const component: DefineComponent;
|
||||
export default component;
|
||||
}
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_ICE_ENDPOINT?: string;
|
||||
readonly VITE_STUN_URL?: string;
|
||||
readonly VITE_TRACKER_URL?: string;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
showSaveFilePicker?: (options?: { suggestedName?: string }) => Promise<{ createWritable(): Promise<import('./lib/transfer.ts').FileDestination> }>;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import { parseHello, type IdentityHello } from './identity.ts';
|
||||
import { asError, isRecord } from './validation.ts';
|
||||
import { MAX_SIGNAL_LENGTH, validateDescription, type IceOptions } from './webrtc.ts';
|
||||
|
||||
// Connection codes: "HC1." + base64url(deflate-raw(JSON)).
|
||||
// Codes carry connection details, not secrets; fingerprints authenticate peers.
|
||||
export const CODE_PREFIX = 'HC1.';
|
||||
export const MAX_CODE_LENGTH = MAX_SIGNAL_LENGTH;
|
||||
// Pasted text may contain line breaks or other whitespace around the code.
|
||||
export const MAX_INPUT_LENGTH = MAX_CODE_LENGTH * 2;
|
||||
const MAX_PAYLOAD = MAX_SIGNAL_LENGTH + 1024;
|
||||
const INVALID = 'Invalid connection code. Paste the complete code.';
|
||||
|
||||
export interface Signal {
|
||||
type: 'offer' | 'answer';
|
||||
// Chosen by the offerer and echoed by the answer, which addresses that offer.
|
||||
ref: string;
|
||||
sdp: string;
|
||||
identity?: IdentityHello;
|
||||
}
|
||||
export interface DecodeOptions extends Pick<IceOptions, 'allowTurn'> { type?: Signal['type']; ref?: string }
|
||||
|
||||
export function toBase64Url(bytes: Uint8Array) {
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
||||
}
|
||||
export function fromBase64Url(text: string, invalid = INVALID) {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(text) || text.length % 4 === 1) throw new Error(invalid);
|
||||
return Uint8Array.from(atob(text.replaceAll('-', '+').replaceAll('_', '/')), char => char.charCodeAt(0));
|
||||
}
|
||||
async function deflate(text: string) {
|
||||
const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('deflate-raw'));
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer());
|
||||
}
|
||||
// Stops reading once the output exceeds the limit, so a small hostile code
|
||||
// cannot expand without bound.
|
||||
async function inflate(bytes: Uint8Array<ArrayBuffer>) {
|
||||
const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw')).getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
length += value.byteLength;
|
||||
if (length > MAX_PAYLOAD) { void reader.cancel().catch(() => {}); throw new Error('Connection code is too large.'); }
|
||||
chunks.push(value);
|
||||
}
|
||||
const output = new Uint8Array(length);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) { output.set(chunk, offset); offset += chunk.byteLength; }
|
||||
return output;
|
||||
}
|
||||
|
||||
export function createRef() { return toBase64Url(crypto.getRandomValues(new Uint8Array(16))); }
|
||||
|
||||
export async function encodeCode({ type, ref, sdp, identity }: Signal) {
|
||||
const payload = identity ? { version: 4, type, ref, sdp, identity: parseHello(identity) } : { version: 3, type, ref, sdp };
|
||||
const code = CODE_PREFIX + toBase64Url(await deflate(JSON.stringify(payload)));
|
||||
if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
|
||||
return code;
|
||||
}
|
||||
|
||||
export async function decodeCode(text: unknown, { type, ref, ...options }: DecodeOptions = {}): Promise<Signal> {
|
||||
if (typeof text !== 'string' || text.length > MAX_INPUT_LENGTH) throw new Error('Connection code is too large.');
|
||||
const code = text.replace(/\s+/g, '');
|
||||
if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large.');
|
||||
if (!code.startsWith(CODE_PREFIX)) {
|
||||
let legacy = false;
|
||||
try { legacy = isRecord(JSON.parse(atob(code))); } catch { /* not an old code either */ }
|
||||
throw new Error(legacy ? 'Both people need the current HellCon version.' : INVALID);
|
||||
}
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await inflate(fromBase64Url(code.slice(CODE_PREFIX.length)))));
|
||||
} catch (err) {
|
||||
if (asError(err).message === 'Connection code is too large.') throw err;
|
||||
throw new Error(INVALID);
|
||||
}
|
||||
if (!isRecord(data) || ![3, 4].includes(data.version as number)) throw new Error('Both people need the current HellCon version.');
|
||||
if ((data.type !== 'offer' && data.type !== 'answer') || typeof data.ref !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(data.ref) || typeof data.sdp !== 'string') {
|
||||
throw new Error(INVALID);
|
||||
}
|
||||
if (data.version === 3 && data.identity !== undefined) throw new Error(INVALID);
|
||||
const identity = data.version === 4 ? parseHello(data.identity) : undefined;
|
||||
validateDescription(data.sdp, options);
|
||||
if (type && data.type !== type) {
|
||||
throw new Error(type === 'answer' ? 'This is a connection code, not an answer. Paste the answer your peer created.' : 'This is an answer, not a connection code. Paste the code the sender created.');
|
||||
}
|
||||
if (ref !== undefined && data.ref !== ref) throw new Error('This answer belongs to a different connection code. Ask your peer to answer your current code.');
|
||||
return { type: data.type, ref: data.ref, sdp: data.sdp, ...(identity ? { identity } : {}) };
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
// Only allowlisted categories and numbers leave this module. Never retain raw
|
||||
// SDP, candidate addresses/IDs, URLs, credentials, filenames or browser errors.
|
||||
const candidateTypes = ['host', 'srflx', 'prflx', 'relay'] as const;
|
||||
const protocols = ['udp', 'tcp'] as const;
|
||||
const pairStates = ['frozen', 'waiting', 'in-progress', 'failed', 'succeeded'] as const;
|
||||
const counters = ['requestsSent', 'requestsReceived', 'responsesSent', 'responsesReceived'] as const;
|
||||
type StatsEntry = Record<string, unknown>;
|
||||
type Stats = Pick<RTCStatsReport, 'forEach' | 'get'>;
|
||||
const category = (value: unknown, allowed: readonly string[]) => typeof value === 'string' && allowed.includes(value) ? value : 'unknown';
|
||||
const count = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? String(value) : '?';
|
||||
|
||||
export function summarizeCandidates(sdp: string | undefined): string {
|
||||
const counts = { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 };
|
||||
for (const line of sdp?.split(/\r?\n/) ?? []) {
|
||||
if (!line.startsWith('a=candidate:')) continue;
|
||||
const type = category(line.match(/\styp\s+(\S+)/)?.[1], candidateTypes) as keyof typeof counts;
|
||||
counts[type]++;
|
||||
}
|
||||
return Object.entries(counts).map(([type, n]) => `${type}=${n}`).join(' ') +
|
||||
` end=${sdp?.split(/\r?\n/).includes('a=end-of-candidates') ? 'yes' : 'no'}`;
|
||||
}
|
||||
|
||||
export function summarizeStats(stats: Stats): string[] {
|
||||
const pairs: StatsEntry[] = [];
|
||||
const selected = new Set<string>();
|
||||
const candidates = { local: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 }, remote: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 } };
|
||||
stats.forEach((entry: StatsEntry) => {
|
||||
if (entry.type === 'transport' && typeof entry.selectedCandidatePairId === 'string') selected.add(entry.selectedCandidatePairId);
|
||||
if (entry.type === 'candidate-pair') pairs.push(entry);
|
||||
const side = entry.type === 'local-candidate' ? 'local' : entry.type === 'remote-candidate' ? 'remote' : null;
|
||||
if (side) candidates[side][category(entry.candidateType, candidateTypes) as keyof typeof candidates.local]++;
|
||||
});
|
||||
const endpoint = (id: unknown) => {
|
||||
const entry = typeof id === 'string' ? stats.get(id) as StatsEntry | undefined : undefined;
|
||||
return `${category(entry?.candidateType, candidateTypes)}/${category(entry?.protocol, protocols)}`;
|
||||
};
|
||||
const lines = (['local', 'remote'] as const).map(side => `${side} stats: ` + Object.entries(candidates[side]).map(([type, n]) => `${type}=${n}`).join(' '));
|
||||
lines.push(`pairs=${pairs.length}`);
|
||||
// Put a selected route first, cap output on machines with many interfaces.
|
||||
const isSelected = (pair: StatsEntry) => typeof pair.id === 'string' && selected.has(pair.id) || pair.selected === true;
|
||||
pairs.sort((a, b) => Number(isSelected(b)) - Number(isSelected(a)));
|
||||
for (const pair of pairs.slice(0, 12)) {
|
||||
lines.push(`pair ${endpoint(pair.localCandidateId)} → ${endpoint(pair.remoteCandidateId)} ${category(pair.state, pairStates)}` +
|
||||
` selected=${isSelected(pair)} nominated=${pair.nominated === true} ` + counters.map(key => `${key}=${count(pair[key])}`).join(' '));
|
||||
}
|
||||
stats.forEach((entry: StatsEntry) => {
|
||||
if (entry.type === 'transport') lines.push(`transport dtls=${category(entry.dtlsState, ['new', 'connecting', 'connected', 'closed', 'failed'])}`);
|
||||
});
|
||||
if (pairs.length > 12) lines.push(`pairs omitted=${pairs.length - 12}`);
|
||||
return lines;
|
||||
}
|
||||
|
||||
export class ConnectionDiagnostics {
|
||||
readonly lines: string[] = [];
|
||||
private readonly started = performance.now();
|
||||
private stopped = false;
|
||||
private sampleTimers: ReturnType<typeof setTimeout>[] = [];
|
||||
private samplingStarted = false;
|
||||
private finishing: Promise<void> | undefined;
|
||||
private readonly listeners: Array<[EventTarget, string, EventListener]> = [];
|
||||
private readonly pc: RTCPeerConnection;
|
||||
private readonly update: (lines: string[]) => void;
|
||||
constructor(pc: RTCPeerConnection, update: (lines: string[]) => void) {
|
||||
this.pc = pc; this.update = update;
|
||||
const listen = (target: EventTarget, event: string, listener: EventListener) => {
|
||||
target.addEventListener(event, listener);
|
||||
this.listeners.push([target, event, listener]);
|
||||
};
|
||||
const state = () => {
|
||||
this.sampleWhileChecking();
|
||||
this.record(`pc=${category(pc.connectionState, ['new', 'connecting', 'connected', 'disconnected', 'failed', 'closed'])} ice=${category(pc.iceConnectionState, ['new', 'checking', 'connected', 'completed', 'disconnected', 'failed', 'closed'])} gathering=${category(pc.iceGatheringState, ['new', 'gathering', 'complete'])}`);
|
||||
};
|
||||
for (const event of ['connectionstatechange', 'iceconnectionstatechange', 'icegatheringstatechange']) listen(pc, event, state);
|
||||
listen(pc, 'icecandidateerror', event => this.record(`ICE server error=${count((event as RTCPeerConnectionIceErrorEvent).errorCode)}`));
|
||||
if (typeof document !== 'undefined') {
|
||||
const visibility = () => this.record(`page=${category(document.visibilityState, ['visible', 'hidden'])}`);
|
||||
listen(document, 'visibilitychange', visibility);
|
||||
visibility();
|
||||
}
|
||||
state();
|
||||
}
|
||||
private sampleWhileChecking() {
|
||||
if (this.stopped || this.finishing) return;
|
||||
if (this.pc.iceConnectionState !== 'checking') {
|
||||
for (const timer of this.sampleTimers) clearTimeout(timer);
|
||||
this.sampleTimers = [];
|
||||
return;
|
||||
}
|
||||
if (this.samplingStarted) return;
|
||||
this.samplingStarted = true;
|
||||
// Preserve evidence before browsers discard failed candidate pairs. Four
|
||||
// bounded snapshots cover short setup failures without polling indefinitely.
|
||||
this.sampleTimers = [3000, 6000, 9000, 12000].map(delay => setTimeout(() => {
|
||||
if (this.stopped || this.finishing || this.pc.iceConnectionState !== 'checking') return;
|
||||
this.record('connectivity sample');
|
||||
void this.capture();
|
||||
}, delay));
|
||||
}
|
||||
record(message: string) {
|
||||
if (this.stopped) return;
|
||||
this.lines.push(`${((performance.now() - this.started) / 1000).toFixed(1)}s ${message}`);
|
||||
this.lines.splice(0, Math.max(0, this.lines.length - 80));
|
||||
this.update([...this.lines]);
|
||||
}
|
||||
descriptions() {
|
||||
this.record(`local code: ${summarizeCandidates(this.pc.localDescription?.sdp)}`);
|
||||
this.record(`remote code: ${summarizeCandidates(this.pc.remoteDescription?.sdp)}`);
|
||||
}
|
||||
async capture() {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const stats = await Promise.race([
|
||||
this.pc.getStats(),
|
||||
new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), 300); }),
|
||||
]);
|
||||
if (stats) for (const line of summarizeStats(stats)) this.record(line);
|
||||
else this.record('stats unavailable: deadline');
|
||||
} catch { this.record('stats unavailable'); }
|
||||
finally { clearTimeout(timer); }
|
||||
}
|
||||
// Request final stats while the connection is alive. Always close, even when
|
||||
// getStats rejects or hangs. Reset can start a new session during this wait.
|
||||
finish(close: () => void) {
|
||||
for (const timer of this.sampleTimers) clearTimeout(timer);
|
||||
this.sampleTimers = [];
|
||||
return this.finishing ??= this.capture().finally(() => {
|
||||
this.stopped = true;
|
||||
for (const [target, event, listener] of this.listeners) target.removeEventListener(event, listener);
|
||||
close();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { parsePairing, type ReconnectPairing } from './reconnect.ts';
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
export const CONNECTION_LIMIT = 100;
|
||||
export interface SavedConnection {
|
||||
id: string;
|
||||
number: number;
|
||||
name: string;
|
||||
// The peer this connection trusts. Only set after mutual verification.
|
||||
peerKey: string;
|
||||
// Per-connection opt-in to include this browser's identity in codes.
|
||||
rememberDevice: boolean;
|
||||
// Tracker reconnect with the paired device. Cleared whenever that device changes.
|
||||
reconnect: ReconnectPairing | null;
|
||||
}
|
||||
export type ConnectionUpdate = { name: string } | { peerKey: string } | { rememberDevice: boolean } | { reconnect: ReconnectPairing | null };
|
||||
export function connectionName(value: string) {
|
||||
const name = value.trim();
|
||||
if (!name || name.length > 80) throw new Error('Use a connection name between 1 and 80 characters.');
|
||||
return name;
|
||||
}
|
||||
export function updateConnection(current: SavedConnection, update: ConnectionUpdate): SavedConnection {
|
||||
if ('name' in update) return { ...current, name: connectionName(update.name) };
|
||||
if ('peerKey' in update) {
|
||||
if (update.peerKey && !/^04[0-9a-f]{128}$/.test(update.peerKey)) throw new Error('Invalid paired device.');
|
||||
return { ...current, peerKey: update.peerKey, reconnect: update.peerKey === current.peerKey ? current.reconnect : null };
|
||||
}
|
||||
if ('rememberDevice' in update) return { ...current, rememberDevice: update.rememberDevice === true };
|
||||
if ('reconnect' in update) {
|
||||
if (!update.reconnect) return { ...current, reconnect: null };
|
||||
const reconnect = parsePairing(update.reconnect, current.peerKey);
|
||||
if (!reconnect) throw new Error('Reconnect needs this connection’s paired device. Pair again and retry.');
|
||||
return { ...current, reconnect };
|
||||
}
|
||||
throw new Error('Invalid connection update.');
|
||||
}
|
||||
export function emptyConnection(number = 1): SavedConnection {
|
||||
return { id: crypto.randomUUID(), number, name: `Con ${number}`, peerKey: '', rememberDevice: false, reconnect: null };
|
||||
}
|
||||
function validateConnection(value: unknown): SavedConnection {
|
||||
if (!isRecord(value) || typeof value.id !== 'string' || !value.id || !Number.isSafeInteger(value.number) || (value.number as number) < 1 ||
|
||||
typeof value.name !== 'string' || typeof value.peerKey !== 'string') throw new Error('Saved connections are unreadable.');
|
||||
const record = updateConnection({ id: value.id, number: value.number as number, name: connectionName(value.name), peerKey: '', rememberDevice: value.rememberDevice === true, reconnect: null }, { peerKey: value.peerKey });
|
||||
return { ...record, reconnect: parsePairing(value.reconnect, record.peerKey) };
|
||||
}
|
||||
async function database() {
|
||||
return new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open('hellcon-connections', 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore('connections', { keyPath: 'id' });
|
||||
request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
|
||||
request.onerror = () => reject(new Error('Connection storage is unavailable.'));
|
||||
request.onblocked = () => reject(new Error('Close other HellCon tabs to open connection storage.'));
|
||||
});
|
||||
}
|
||||
// Read and write within one transaction so other tabs cannot overwrite a rename
|
||||
// or paired device with a stale copy of the entire record.
|
||||
async function change(action: (records: SavedConnection[], store: IDBObjectStore) => void) {
|
||||
const db = await database();
|
||||
try {
|
||||
return await new Promise<SavedConnection[]>((resolve, reject) => {
|
||||
const tx = db.transaction('connections', 'readwrite'), store = tx.objectStore('connections');
|
||||
let records: SavedConnection[] = [], failure: unknown;
|
||||
const read = store.getAll();
|
||||
read.onsuccess = () => {
|
||||
try {
|
||||
records = read.result.map((raw: unknown) => {
|
||||
const record = validateConnection(raw);
|
||||
// Pre-release 0.0.5 builds saved filenames here. Remove them on the first load.
|
||||
if (isRecord(raw) && 'history' in raw) store.put(record);
|
||||
return record;
|
||||
}).sort((a, b) => a.number - b.number);
|
||||
action(records, store);
|
||||
} catch (error) { failure = error; tx.abort(); }
|
||||
};
|
||||
tx.oncomplete = () => resolve(records);
|
||||
tx.onabort = tx.onerror = () => reject(failure || new Error('Could not save connections.'));
|
||||
});
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export function loadConnections() {
|
||||
return change((records, store) => {
|
||||
if (!records.length) { const first = emptyConnection(); store.add(first); records.push(first); }
|
||||
});
|
||||
}
|
||||
export async function addConnection() {
|
||||
const records = await change((records, store) => {
|
||||
if (records.length >= CONNECTION_LIMIT) throw new Error(`Keep up to ${CONNECTION_LIMIT} connections.`);
|
||||
const record = emptyConnection(Math.max(0, ...records.map(item => item.number)) + 1);
|
||||
store.add(record); records.push(record);
|
||||
});
|
||||
return records;
|
||||
}
|
||||
export function saveConnection(id: string, update: ConnectionUpdate) {
|
||||
return change((records, store) => {
|
||||
const index = records.findIndex(item => item.id === id);
|
||||
if (index < 0) throw new Error('This connection is no longer saved. Reload the page.');
|
||||
const record = updateConnection(records[index]!, update);
|
||||
store.put(record); records[index] = record;
|
||||
});
|
||||
}
|
||||
export function removeConnection(id: string) {
|
||||
return change((records, store) => {
|
||||
const index = records.findIndex(item => item.id === id);
|
||||
if (index >= 0) { store.delete(id); records.splice(index, 1); }
|
||||
if (!records.length) { const first = emptyConnection(); store.add(first); records.push(first); }
|
||||
});
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import type { FileDestination, FileMetadata } from './transfer.ts';
|
||||
|
||||
export function supportsStreamingDownload() {
|
||||
if (!['https:', 'http:'].includes(location.protocol) || !isSecureContext ||
|
||||
!navigator.serviceWorker || typeof TransformStream === 'undefined') return false;
|
||||
const channel = new MessageChannel();
|
||||
const stream = new ReadableStream({ start(controller) { controller.close(); } });
|
||||
try { channel.port1.postMessage(stream, [stream]); return true; }
|
||||
catch { return false; }
|
||||
finally { channel.port1.close(); channel.port2.close(); }
|
||||
}
|
||||
|
||||
export async function createDownloadDestination(meta: FileMetadata, signal: AbortSignal): Promise<FileDestination> {
|
||||
if (!supportsStreamingDownload()) throw new Error('Streaming downloads require a supported browser and HTTPS or localhost.');
|
||||
signal.throwIfAborted();
|
||||
const stream = new TransformStream<Uint8Array, Uint8Array>();
|
||||
const writer = stream.writable.getWriter();
|
||||
const channel = new MessageChannel();
|
||||
const frame = document.createElement('iframe');
|
||||
frame.hidden = true; frame.title = 'File download';
|
||||
let finished = false;
|
||||
let stopWatchingWorker = () => {};
|
||||
let resolveReady!: () => void, rejectReady!: (error: Error) => void;
|
||||
let resolveComplete!: () => void, rejectComplete!: (error: Error) => void;
|
||||
const ready = new Promise<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
const complete = new Promise<void>((resolve, reject) => { resolveComplete = resolve; rejectComplete = reject; });
|
||||
void ready.catch(() => {}); void complete.catch(() => {}); void writer.closed.catch(() => {});
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
stopWatchingWorker();
|
||||
signal.removeEventListener('abort', canceled);
|
||||
window.removeEventListener('pagehide', canceled);
|
||||
channel.port1.close(); frame.remove();
|
||||
};
|
||||
const fail = (error: Error) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
channel.port1.postMessage({ type: 'abort' });
|
||||
rejectReady(error); rejectComplete(error);
|
||||
void writer.abort(error).catch(() => {});
|
||||
cleanup();
|
||||
};
|
||||
const canceled = () => fail(new DOMException('Transfer canceled.', 'AbortError'));
|
||||
const timer = setTimeout(() => fail(new Error('Streaming download did not start. Check browser download permissions and try again.')), 30000);
|
||||
signal.addEventListener('abort', canceled, { once: true });
|
||||
window.addEventListener('pagehide', canceled);
|
||||
try {
|
||||
const registration = await Promise.race([
|
||||
navigator.serviceWorker.register(new URL('./download/worker.js', location.href).href),
|
||||
ready.then(() => { throw new Error('Unexpected download state.'); }),
|
||||
]);
|
||||
const worker = registration.active || registration.installing || registration.waiting;
|
||||
if (!worker) throw new Error('Download service worker is unavailable.');
|
||||
if (worker.state !== 'activated') await Promise.race([
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const changed = () => {
|
||||
if (worker.state === 'activated' || worker.state === 'redundant') {
|
||||
worker.removeEventListener('statechange', changed);
|
||||
worker.state === 'activated' ? resolve() : reject(new Error('Download service worker could not activate.'));
|
||||
}
|
||||
};
|
||||
stopWatchingWorker = () => worker.removeEventListener('statechange', changed);
|
||||
worker.addEventListener('statechange', changed); changed();
|
||||
}), ready,
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
if (finished) await ready;
|
||||
const id = Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
|
||||
const url = new URL(`file-${id}`, registration.scope).href;
|
||||
channel.port1.onmessage = event => {
|
||||
if (event.data?.type === 'ready' && event.data.url === url) {
|
||||
frame.src = url; document.body.append(frame);
|
||||
}
|
||||
if (event.data?.type === 'started') { clearTimeout(timer); resolveReady(); }
|
||||
if (event.data?.type === 'error') fail(new Error(event.data.message || 'Download failed.'));
|
||||
if (event.data?.type === 'complete' && !finished) {
|
||||
finished = true; resolveComplete(); cleanup();
|
||||
}
|
||||
};
|
||||
worker.postMessage({ type: 'download', id, name: meta.name, size: meta.size, stream: stream.readable }, [channel.port2, stream.readable]);
|
||||
await ready;
|
||||
return {
|
||||
async write(data) { await writer.write(new Uint8Array(data)); },
|
||||
async close() { await writer.close(); await complete; },
|
||||
async abort() { canceled(); },
|
||||
};
|
||||
} catch (error) { fail(error instanceof Error ? error : new Error('Could not start download.')); throw error; }
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
export interface Identity { publicKey: string; privateKey: CryptoKey }
|
||||
export interface IdentityHello { key: string; nonce: string }
|
||||
export interface IdentityState { revision?: string; identity: Identity | null }
|
||||
export interface IdentityContext { offer: IdentityHello; answer: IdentityHello; offerFingerprint: string; answerFingerprint: string }
|
||||
const curve = { name: 'ECDSA', namedCurve: 'P-256' };
|
||||
const signing = { name: 'ECDSA', hash: 'SHA-256' };
|
||||
const bytes = (text: string) => new TextEncoder().encode(text);
|
||||
const hex = (data: ArrayBuffer | Uint8Array) => Array.from(data instanceof Uint8Array ? data : new Uint8Array(data), n => n.toString(16).padStart(2, '0')).join('');
|
||||
function unhex(value: unknown, length: number): Uint8Array<ArrayBuffer> {
|
||||
if (typeof value !== 'string' || value.length !== length * 2 || !/^[0-9a-f]+$/.test(value)) throw new Error('Invalid device identity.');
|
||||
return Uint8Array.from(value.match(/../g)!, n => parseInt(n, 16));
|
||||
}
|
||||
export function parseHello(value: unknown): IdentityHello {
|
||||
if (!isRecord(value)) throw new Error('Invalid device identity.');
|
||||
unhex(value.key, 65); unhex(value.nonce, 32);
|
||||
if (!(value.key as string).startsWith('04')) throw new Error('Invalid device identity.');
|
||||
return { key: value.key as string, nonce: value.nonce as string };
|
||||
}
|
||||
export async function createIdentity(): Promise<Identity> {
|
||||
// Store the private key as a non-extractable CryptoKey. Same-origin JavaScript
|
||||
// can still use it to sign, so the app code must remain trusted.
|
||||
const pair = await crypto.subtle.generateKey(curve, false, ['sign', 'verify']);
|
||||
return { publicKey: hex(await crypto.subtle.exportKey('raw', pair.publicKey)), privateKey: pair.privateKey };
|
||||
}
|
||||
export function hello(identity: Identity): IdentityHello {
|
||||
return { key: identity.publicKey, nonce: hex(crypto.getRandomValues(new Uint8Array(32))) };
|
||||
}
|
||||
function transcript(context: IdentityContext, initiator: boolean) {
|
||||
const offer = parseHello(context.offer), answer = parseHello(context.answer);
|
||||
const fingerprint = /^(?:[0-9A-F]{2} ){31}[0-9A-F]{2}$/;
|
||||
if (!fingerprint.test(context.offerFingerprint) || !fingerprint.test(context.answerFingerprint)) throw new Error('Invalid identity session binding.');
|
||||
return bytes(JSON.stringify(['HellCon device proof', 1, 4, initiator ? 'offerer' : 'answerer', offer.key, offer.nonce, answer.key, answer.nonce, context.offerFingerprint, context.answerFingerprint]));
|
||||
}
|
||||
export async function signIdentity(identity: Identity, context: IdentityContext, initiator: boolean) {
|
||||
if (identity.publicKey !== (initiator ? context.offer : context.answer).key) throw new Error('Device identity changed. Start a new connection.');
|
||||
return hex(await crypto.subtle.sign(signing, identity.privateKey, transcript(context, initiator)));
|
||||
}
|
||||
export async function verifyIdentity(proof: unknown, context: IdentityContext, initiator: boolean) {
|
||||
const key = await crypto.subtle.importKey('raw', unhex((initiator ? context.offer : context.answer).key, 65), curve, false, ['verify']);
|
||||
if (!await crypto.subtle.verify(signing, key, unhex(proof, 64), transcript(context, initiator))) throw new Error('Device proof failed. Disconnect and verify fresh codes.');
|
||||
}
|
||||
|
||||
async function database() {
|
||||
return new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open('hellcon-devices', 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore('settings');
|
||||
request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
|
||||
request.onerror = () => reject(new Error('Device storage is unavailable. Use a temporary connection.'));
|
||||
request.onblocked = () => reject(new Error('Close other HellCon tabs and try again.'));
|
||||
});
|
||||
}
|
||||
export async function loadIdentityState(): Promise<IdentityState> {
|
||||
const db = await database();
|
||||
try {
|
||||
const state = await new Promise<IdentityState | undefined>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readonly');
|
||||
const request = tx.objectStore('settings').get('state');
|
||||
tx.oncomplete = () => resolve(request.result); tx.onabort = tx.onerror = () => reject(new Error('Could not read device storage.'));
|
||||
});
|
||||
if (!state) return { identity: null };
|
||||
if (state.identity) {
|
||||
unhex(state.identity.publicKey, 65);
|
||||
if (!(state.identity.privateKey instanceof CryptoKey) || state.identity.privateKey.type !== 'private') throw new Error('Stored identity is invalid. Clear device storage and create a new identity.');
|
||||
}
|
||||
return { revision: state.revision, identity: state.identity ?? null };
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export async function saveIdentityState(state: IdentityState, expectedRevision = state.revision): Promise<IdentityState> {
|
||||
const db = await database();
|
||||
const next = { ...state, revision: crypto.randomUUID() };
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readwrite');
|
||||
const store = tx.objectStore('settings');
|
||||
const current = store.get('state');
|
||||
let conflict = false;
|
||||
current.onsuccess = () => {
|
||||
if (current.result?.revision !== expectedRevision) { conflict = true; tx.abort(); }
|
||||
else store.put(next, 'state');
|
||||
};
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onabort = tx.onerror = () => reject(new Error(conflict ? 'Device settings changed in another tab. Reload before editing them.' : 'Could not save device storage. Use a temporary connection.'));
|
||||
});
|
||||
return next;
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export async function clearIdentityStorage() {
|
||||
const db = await database();
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readwrite');
|
||||
tx.objectStore('settings').delete('state');
|
||||
tx.oncomplete = () => resolve(); tx.onabort = tx.onerror = () => reject(new Error('Could not clear device storage.'));
|
||||
});
|
||||
} finally { db.close(); }
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import { fromBase64Url, MAX_CODE_LENGTH, toBase64Url } from './codes.ts';
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
// Tracker reconnect for paired devices. Both peers contribute a nonce over an
|
||||
// authenticated session; HKDF turns them into a stored base key, from which a
|
||||
// daily swarm identifier and a signaling key are derived. Trackers only see
|
||||
// sealed envelopes; device proofs still authenticate every reconnected session.
|
||||
export const RECONNECT_VERSION = 1;
|
||||
export interface ReconnectPairing {
|
||||
version: 1;
|
||||
// Agreed at pairing time, in order. The first release contacts only the first.
|
||||
trackers: string[];
|
||||
// Non-extractable HKDF base key.
|
||||
key: CryptoKey;
|
||||
localKey: string;
|
||||
peerKey: string;
|
||||
}
|
||||
export interface PairingContext {
|
||||
proposerNonce: string; acceptorNonce: string;
|
||||
proposerKey: string; acceptorKey: string;
|
||||
offerFingerprint: string; answerFingerprint: string;
|
||||
tracker: string;
|
||||
}
|
||||
export type SignalRole = 'wake' | 'offer' | 'answer';
|
||||
// Tracker routing fields as 20-character binary strings; `to` is empty for offers.
|
||||
export interface SignalRoute { role: SignalRole; infoHash: string; offerId: string; from: string; to: string }
|
||||
|
||||
const PREFIX = 'HCR1.';
|
||||
const ROLES: Record<SignalRole, string> = { wake: 'w', offer: 'o', answer: 'a' };
|
||||
// Envelopes expire quickly; the tolerance absorbs clock differences between devices.
|
||||
export const SIGNAL_LIFETIME = 2 * 60 * 1000;
|
||||
export const CLOCK_TOLERANCE = 5 * 60 * 1000;
|
||||
export const MAX_ENVELOPE_LENGTH = Math.ceil((MAX_CODE_LENGTH + 256) * 4 / 3) + 64;
|
||||
const INVALID = 'Invalid reconnect message.';
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const label = (...parts: (string | number)[]) => encoder.encode(JSON.stringify(['HellCon reconnect', RECONNECT_VERSION, ...parts]));
|
||||
const hex = (bytes: Uint8Array) => Array.from(bytes, n => n.toString(16).padStart(2, '0')).join('');
|
||||
const binaryHex = (text: string) => hex(Uint8Array.from(text, char => char.charCodeAt(0)));
|
||||
function unhex(value: unknown, length: number) {
|
||||
if (typeof value !== 'string' || value.length !== length * 2 || !/^[0-9a-f]+$/.test(value)) throw new Error('Invalid reconnect setup.');
|
||||
return Uint8Array.from(value.match(/../g)!, n => parseInt(n, 16));
|
||||
}
|
||||
|
||||
export function pairingNonce() { return hex(crypto.getRandomValues(new Uint8Array(32))); }
|
||||
export function parseNonce(value: unknown) { unhex(value, 32); return value as string; }
|
||||
export const utcDay = (time = Date.now()) => Math.floor(time / 86_400_000);
|
||||
|
||||
// Accepts one secure WebSocket URL; plain ws:// only for this machine.
|
||||
export function trackerUrl(value: unknown) {
|
||||
if (typeof value !== 'string' || value.length > 1024) throw new Error('Enter a tracker address starting with wss://.');
|
||||
let url: URL;
|
||||
try { url = new URL(value.trim()); } catch { throw new Error('Enter a tracker address starting with wss://.'); }
|
||||
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
||||
if (url.protocol !== 'wss:' && !(url.protocol === 'ws:' && loopback)) throw new Error('Enter a tracker address starting with wss://.');
|
||||
if (url.username || url.password || url.hash) throw new Error('Tracker addresses cannot contain credentials or a fragment.');
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export async function derivePairing(context: PairingContext) {
|
||||
const ikm = new Uint8Array(64);
|
||||
ikm.set(unhex(context.proposerNonce, 32)); ikm.set(unhex(context.acceptorNonce, 32), 32);
|
||||
unhex(context.proposerKey, 65); unhex(context.acceptorKey, 65);
|
||||
if (context.proposerKey === context.acceptorKey) throw new Error('Reconnect needs two different devices.');
|
||||
const salt = await crypto.subtle.digest('SHA-256', label('pairing', context.proposerKey, context.acceptorKey, context.offerFingerprint, context.answerFingerprint, trackerUrl(context.tracker)));
|
||||
const input = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);
|
||||
const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info: label('base') }, input, 256);
|
||||
return crypto.subtle.importKey('raw', bits, 'HKDF', false, ['deriveBits', 'deriveKey']);
|
||||
}
|
||||
|
||||
// The tracker's info_hash for one UTC day, as a 20-byte binary string.
|
||||
export async function discoveryId(key: CryptoKey, day = utcDay()) {
|
||||
const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: label('discovery', day) }, key, 160);
|
||||
return String.fromCharCode(...new Uint8Array(bits));
|
||||
}
|
||||
|
||||
export function signalingKey(key: CryptoKey) {
|
||||
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: label('signaling') }, key, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
||||
}
|
||||
|
||||
function associatedData(route: SignalRoute) {
|
||||
return label('signal', route.role, binaryHex(route.infoHash), binaryHex(route.offerId), binaryHex(route.from), binaryHex(route.to));
|
||||
}
|
||||
|
||||
export function signalRole(text: unknown): SignalRole | null {
|
||||
if (typeof text !== 'string' || !text.startsWith(PREFIX)) return null;
|
||||
return (Object.keys(ROLES) as SignalRole[]).find(role => text.startsWith(`${PREFIX}${ROLES[role]}.`)) ?? null;
|
||||
}
|
||||
|
||||
// Wakes carry no code; offers and answers carry a complete HellCon code.
|
||||
export async function sealSignal(key: CryptoKey, route: SignalRoute, code: string, now = Date.now()) {
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const plain = encoder.encode(JSON.stringify({ expires: now + SIGNAL_LIFETIME, code }));
|
||||
const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: associatedData(route) }, key, plain));
|
||||
const body = new Uint8Array(iv.length + sealed.length);
|
||||
body.set(iv); body.set(sealed, iv.length);
|
||||
return `${PREFIX}${ROLES[route.role]}.${toBase64Url(body)}`;
|
||||
}
|
||||
|
||||
export async function openSignal(key: CryptoKey, route: SignalRoute, text: unknown, now = Date.now()) {
|
||||
if (typeof text !== 'string' || text.length > MAX_ENVELOPE_LENGTH || signalRole(text) !== route.role) throw new Error(INVALID);
|
||||
const body = fromBase64Url(text.slice(PREFIX.length + 2), INVALID);
|
||||
if (body.length < 12 + 16) throw new Error(INVALID);
|
||||
let data: unknown;
|
||||
try {
|
||||
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: body.subarray(0, 12), additionalData: associatedData(route) }, key, body.subarray(12));
|
||||
data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plain));
|
||||
} catch { throw new Error(INVALID); }
|
||||
if (!isRecord(data) || typeof data.code !== 'string' || typeof data.expires !== 'number' || (route.role === 'wake') !== !data.code) throw new Error(INVALID);
|
||||
if (data.expires < now - CLOCK_TOLERANCE || data.expires > now + SIGNAL_LIFETIME + CLOCK_TOLERANCE) throw new Error('Reconnect message expired. Check both devices’ clocks.');
|
||||
return data.code;
|
||||
}
|
||||
|
||||
// Compared over each authenticated session, so a pairing stored or turned off
|
||||
// on only one side is noticed. It travels only inside the encrypted session.
|
||||
export async function pairingCheck(key: CryptoKey) {
|
||||
return hex(new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: label('check') }, key, 128)));
|
||||
}
|
||||
export function parseCheck(value: unknown) {
|
||||
if (value === '') return value;
|
||||
unhex(value, 16);
|
||||
return value as string;
|
||||
}
|
||||
|
||||
// Connection discovery: a per-browser preference for new reconnect setups.
|
||||
// Existing pairings keep the tracker they were set up with.
|
||||
export type DiscoveryChoice = 'manual' | 'default' | 'custom';
|
||||
export interface DiscoverySettings { choice: DiscoveryChoice; custom: string }
|
||||
const DISCOVERY_STORAGE = 'hellcon-discovery';
|
||||
export function loadDiscovery(defaultTracker: string): DiscoverySettings {
|
||||
const fallback: DiscoverySettings = { choice: defaultTracker ? 'default' : 'manual', custom: '' };
|
||||
try {
|
||||
const data: unknown = JSON.parse(localStorage.getItem(DISCOVERY_STORAGE) ?? 'null');
|
||||
if (!isRecord(data) || !['manual', 'default', 'custom'].includes(data.choice as string) || typeof data.custom !== 'string') return fallback;
|
||||
const choice = data.choice === 'default' && !defaultTracker ? 'manual' : data.choice as DiscoveryChoice;
|
||||
return { choice, custom: data.custom.slice(0, 1024) };
|
||||
} catch { return fallback; }
|
||||
}
|
||||
export function saveDiscovery(settings: DiscoverySettings) {
|
||||
try { localStorage.setItem(DISCOVERY_STORAGE, JSON.stringify({ choice: settings.choice, custom: settings.custom })); }
|
||||
catch { /* the preference lasts for this page */ }
|
||||
}
|
||||
// The concrete tracker a new pairing would use, or '' for manual codes.
|
||||
export function discoveryTracker(settings: DiscoverySettings, defaultTracker: string) {
|
||||
if (settings.choice === 'manual') return '';
|
||||
return trackerUrl(settings.choice === 'default' ? defaultTracker : settings.custom);
|
||||
}
|
||||
|
||||
// Storage validation: an unusable pairing is dropped rather than failing the record.
|
||||
export function parsePairing(value: unknown, peerKey: string): ReconnectPairing | null {
|
||||
if (!isRecord(value) || value.version !== RECONNECT_VERSION || !peerKey || value.peerKey !== peerKey) return null;
|
||||
if (!(value.key instanceof CryptoKey) || value.key.algorithm.name !== 'HKDF' || typeof value.localKey !== 'string' || !/^04[0-9a-f]{128}$/.test(value.localKey)) return null;
|
||||
if (!Array.isArray(value.trackers) || value.trackers.length < 1 || value.trackers.length > 4) return null;
|
||||
try { return { version: RECONNECT_VERSION, trackers: value.trackers.map(trackerUrl), key: value.key, localKey: value.localKey, peerKey }; }
|
||||
catch { return null; }
|
||||
}
|
||||
@@ -1,207 +0,0 @@
|
||||
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;
|
||||
// Reconnect setup messages, delivered only after both peers verified.
|
||||
onPairing?(message: Record<string, unknown>): void;
|
||||
}
|
||||
export interface SessionAuthentication { sign(): Promise<string>; verify(proof: unknown): Promise<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 authentication?: SessionAuthentication;
|
||||
private proofSent = false;
|
||||
private incomingBytes = 0;
|
||||
private processing = Promise.resolve();
|
||||
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 => {
|
||||
if (this.closed) return;
|
||||
const data: unknown = event.data;
|
||||
if (!this.verified) {
|
||||
try {
|
||||
if (typeof data !== 'string' || data.length > 4096 || JSON.parse(data)?.type !== 'ready') throw new Error('File data arrived before verification.');
|
||||
} catch (error) { this.fail(error); return; }
|
||||
}
|
||||
const size = typeof data === 'string' ? data.length * 2 : data instanceof ArrayBuffer ? data.byteLength : 0;
|
||||
this.incomingBytes += size;
|
||||
if (!size || this.incomingBytes > 2 * 1024 * 1024) { this.fail(new Error('Session receive queue exceeded.')); return; }
|
||||
this.processing = this.processing.then(() => this.message(data)).catch(error => this.fail(error)).finally(() => { this.incomingBytes -= size; });
|
||||
};
|
||||
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 })); }
|
||||
authenticate(authentication: SessionAuthentication) {
|
||||
if (this.readySent || this.closed) throw new Error('Identity setup is too late.');
|
||||
this.authentication = authentication;
|
||||
}
|
||||
verify() { this.verified = true; this.ready(); }
|
||||
private ready() { void this.sendReady().catch(error => this.fail(error)); }
|
||||
private async sendReady() {
|
||||
if (this.closed || !this.verified || this.dc.readyState !== 'open') return;
|
||||
try {
|
||||
if (!this.readySent) {
|
||||
this.readySent = true;
|
||||
const proof = await this.authentication?.sign();
|
||||
if (this.closed) return;
|
||||
this.control({ type: 'ready', ...(proof ? { proof } : {}) });
|
||||
this.proofSent = true;
|
||||
}
|
||||
if (!this.proofSent) return;
|
||||
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();
|
||||
}
|
||||
sendPairing(message: Record<string, unknown>) {
|
||||
if (!this.started || this.closed) throw new Error('Connection ended.');
|
||||
this.control({ ...message, type: 'pairing' });
|
||||
}
|
||||
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 async 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) {
|
||||
if (this.authentication) await this.authentication.verify(msg.proof);
|
||||
else if (msg.proof !== undefined) throw new Error('Unexpected device proof.');
|
||||
if (this.closed) return;
|
||||
this.peerReady = true; this.ready(); return;
|
||||
}
|
||||
if (!this.started) throw new Error('File data arrived before verification.');
|
||||
if (msg.type === 'pairing' && this.callbacks.onPairing) { this.callbacks.onPairing(msg); return; }
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
import { MAX_ENVELOPE_LENGTH, openSignal, sealSignal, signalRole, type SignalRoute } from './reconnect.ts';
|
||||
import { asError, isRecord } from './validation.ts';
|
||||
|
||||
// A minimal WebTorrent WebSocket tracker client: announce, offers routed by the
|
||||
// tracker to registered peers, and answers addressed with to_peer_id. It never
|
||||
// carries file data. Identifiers are 20-character binary strings, as on the wire.
|
||||
const ID_LENGTH = 20;
|
||||
const MAX_FRAME = MAX_ENVELOPE_LENGTH + 4096;
|
||||
// Re-announce while waiting so the swarm count stays current; trackers drop
|
||||
// peers whose socket closes, so this is not needed to stay registered.
|
||||
const KEEPALIVE = 15_000;
|
||||
export const randomId = () => String.fromCharCode(...crypto.getRandomValues(new Uint8Array(ID_LENGTH)));
|
||||
const isId = (value: unknown): value is string => typeof value === 'string' && value.length === ID_LENGTH && !/[^\x00-\xff]/.test(value);
|
||||
|
||||
export interface TrackerSignal { peerId: string; offerId: string; sdp: string }
|
||||
export interface TrackerEvents {
|
||||
// Other peers currently announced in this swarm.
|
||||
onPeers(count: number): void;
|
||||
onOffer(signal: TrackerSignal): void;
|
||||
onAnswer(signal: TrackerSignal): void;
|
||||
onError(error: Error): void;
|
||||
}
|
||||
export type SocketFactory = (url: string) => WebSocket;
|
||||
|
||||
export class TrackerClient {
|
||||
readonly peerId = randomId();
|
||||
private socket: WebSocket | null = null;
|
||||
private timer?: ReturnType<typeof setTimeout>;
|
||||
private connectTimer?: ReturnType<typeof setTimeout>;
|
||||
private rejectConnect?: (error: Error) => void;
|
||||
private closed = false;
|
||||
private readonly url: string;
|
||||
private readonly infoHash: string;
|
||||
private readonly events: TrackerEvents;
|
||||
private readonly connectSocket: SocketFactory;
|
||||
constructor(url: string, infoHash: string, events: TrackerEvents, connectSocket: SocketFactory = url => new WebSocket(url)) {
|
||||
if (!isId(infoHash)) throw new Error('Invalid tracker swarm.');
|
||||
this.url = url; this.infoHash = infoHash; this.events = events; this.connectSocket = connectSocket;
|
||||
}
|
||||
connect() {
|
||||
if (this.closed) return Promise.reject(new Error('The tracker connection is closed.'));
|
||||
if (this.socket) return Promise.reject(new Error('The tracker connection has already started.'));
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let socket: WebSocket;
|
||||
try { socket = this.connectSocket(this.url); }
|
||||
catch { reject(new Error('Could not open the tracker connection. Check the tracker address and the site’s connect-src policy.')); return; }
|
||||
this.socket = socket;
|
||||
this.rejectConnect = reject;
|
||||
this.connectTimer = setTimeout(() => this.fail(new Error('The tracker did not respond.')), 15_000);
|
||||
socket.onopen = () => {
|
||||
clearTimeout(this.connectTimer);
|
||||
this.announce('started');
|
||||
this.rejectConnect = undefined;
|
||||
resolve();
|
||||
};
|
||||
socket.onclose = () => {
|
||||
if (this.closed) return;
|
||||
const error = new Error('Could not reach the tracker, or it closed the connection.');
|
||||
this.fail(error);
|
||||
};
|
||||
socket.onmessage = event => this.receive(event.data);
|
||||
});
|
||||
}
|
||||
announce(event?: 'started' | 'stopped', offers: { offerId: string; sdp: string }[] = []) {
|
||||
this.send({
|
||||
...(event ? { event } : {}), numwant: offers.length, uploaded: 0, downloaded: 0, left: 1,
|
||||
...(event === 'stopped' ? {} : { offers: offers.map(item => ({ offer_id: item.offerId, offer: { type: 'offer', sdp: item.sdp } })) }),
|
||||
});
|
||||
clearTimeout(this.timer);
|
||||
if (!this.closed) this.timer = setTimeout(() => this.announce(), KEEPALIVE);
|
||||
}
|
||||
answer(to: string, offerId: string, sdp: string) {
|
||||
if (!isId(to) || !isId(offerId)) throw new Error('Invalid tracker route.');
|
||||
this.send({ to_peer_id: to, offer_id: offerId, answer: { type: 'answer', sdp }, uploaded: 0, downloaded: 0, left: 1 });
|
||||
}
|
||||
close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true; clearTimeout(this.timer); clearTimeout(this.connectTimer);
|
||||
this.rejectConnect?.(new Error('Tracker connection cancelled.'));
|
||||
this.rejectConnect = undefined;
|
||||
const socket = this.socket;
|
||||
if (!socket) return;
|
||||
socket.onopen = socket.onclose = socket.onmessage = null;
|
||||
try { if (socket.readyState === WebSocket.OPEN) this.send({ event: 'stopped', numwant: 0, uploaded: 0, downloaded: 0, left: 1 }, true); } catch { /* best effort */ }
|
||||
socket.close();
|
||||
}
|
||||
private send(data: object, closing = false) {
|
||||
if ((this.closed && !closing) || this.socket?.readyState !== WebSocket.OPEN) return;
|
||||
try { this.socket.send(JSON.stringify({ action: 'announce', info_hash: this.infoHash, peer_id: this.peerId, ...data })); }
|
||||
catch { this.fail(new Error('Could not send to the tracker.')); }
|
||||
}
|
||||
private fail(error: Error) {
|
||||
if (this.closed) return;
|
||||
this.rejectConnect?.(error);
|
||||
this.rejectConnect = undefined;
|
||||
this.close(); this.events.onError(error);
|
||||
}
|
||||
private receive(raw: unknown) {
|
||||
if (this.closed) return;
|
||||
let data: unknown;
|
||||
try {
|
||||
if (typeof raw !== 'string' || raw.length > MAX_FRAME) throw new Error();
|
||||
data = JSON.parse(raw);
|
||||
} catch { this.fail(new Error('The tracker sent an invalid message.')); return; }
|
||||
if (!isRecord(data)) { this.fail(new Error('The tracker sent an invalid message.')); return; }
|
||||
if (typeof data['failure reason'] === 'string') { this.fail(new Error(`The tracker refused the request: ${data['failure reason'].slice(0, 200)}`)); return; }
|
||||
// Scrapes and other swarms on a shared socket are not ours to handle.
|
||||
if (data.action !== 'announce' || data.info_hash !== this.infoHash) return;
|
||||
const { complete, incomplete } = data;
|
||||
if (Number.isSafeInteger(complete) && Number.isSafeInteger(incomplete)) this.events.onPeers(Math.max(0, (complete as number) + (incomplete as number) - 1));
|
||||
if (!isId(data.peer_id) || data.peer_id === this.peerId || !isId(data.offer_id)) return;
|
||||
const signal = (value: unknown, type: string) => isRecord(value) && value.type === type && typeof value.sdp === 'string' ? value.sdp : null;
|
||||
const offer = signal(data.offer, 'offer'), answer = signal(data.answer, 'answer');
|
||||
if (offer !== null) this.events.onOffer({ peerId: data.peer_id, offerId: data.offer_id, sdp: offer });
|
||||
else if (answer !== null) this.events.onAnswer({ peerId: data.peer_id, offerId: data.offer_id, sdp: answer });
|
||||
}
|
||||
}
|
||||
|
||||
export interface AttemptHooks {
|
||||
// Each call replaces the previous local peer connection.
|
||||
createOffer(): Promise<string>;
|
||||
createAnswer(offer: string): Promise<string>;
|
||||
acceptAnswer(answer: string): Promise<void>;
|
||||
onPeers(count: number): void;
|
||||
onError(error: Error): void;
|
||||
}
|
||||
export interface AttemptOptions {
|
||||
url: string; infoHash: string; key: CryptoKey;
|
||||
// The device with the lower public key offers; the other wakes it.
|
||||
initiator: boolean;
|
||||
hooks: AttemptHooks;
|
||||
connectSocket?: SocketFactory;
|
||||
}
|
||||
// Spacing and cap for offers or wakes, so a missing or misbehaving peer cannot
|
||||
// cause unbounded peer connections or tracker traffic.
|
||||
export const RETRY_INTERVAL = 15_000;
|
||||
export const MAX_SIGNALS = 12;
|
||||
const SEEN_LIMIT = 64;
|
||||
|
||||
// One reconnect attempt over one tracker. Whoever arrives second signals at
|
||||
// once: the initiator with an offer, the other device with a sealed wake that
|
||||
// prompts the initiator to offer. Envelopes that do not open are ignored, since
|
||||
// other clients may share a swarm.
|
||||
export class ReconnectAttempt {
|
||||
private readonly tracker: TrackerClient;
|
||||
private readonly options: AttemptOptions;
|
||||
private offerId = '';
|
||||
private lastSignal = 0;
|
||||
private signals = 0;
|
||||
private working = false;
|
||||
private answered = false;
|
||||
private closed = false;
|
||||
private readonly seen = new Set<string>();
|
||||
constructor(options: AttemptOptions) {
|
||||
this.options = options;
|
||||
this.tracker = new TrackerClient(options.url, options.infoHash, {
|
||||
onPeers: count => { if (!this.closed) { options.hooks.onPeers(count); if (count > 0) void this.signal(); } },
|
||||
onOffer: signal => void this.receiveOffer(signal),
|
||||
onAnswer: signal => void this.receiveAnswer(signal),
|
||||
onError: error => this.fail(error),
|
||||
}, options.connectSocket);
|
||||
}
|
||||
start() { return this.tracker.connect(); }
|
||||
close() { this.closed = true; this.tracker.close(); }
|
||||
private fail(error: unknown) {
|
||||
if (this.closed) return;
|
||||
this.close(); this.options.hooks.onError(asError(error));
|
||||
}
|
||||
private route(role: SignalRoute['role'], offerId: string, from: string, to = ''): SignalRoute {
|
||||
return { role, infoHash: this.options.infoHash, offerId, from, to };
|
||||
}
|
||||
private async signal(force = false) {
|
||||
// Signaling stops once an answer was sent or applied. If the responder's
|
||||
// answer is lost, the initiator is still unanswered and offers again.
|
||||
if (this.closed || this.working || this.answered) return;
|
||||
if (!force && Date.now() - this.lastSignal < RETRY_INTERVAL) return;
|
||||
if (this.signals >= MAX_SIGNALS) { this.fail(new Error('Your peer did not respond. Check that both people pressed Reconnect, or exchange codes manually.')); return; }
|
||||
this.signals++; this.working = true; this.lastSignal = Date.now();
|
||||
try {
|
||||
const { initiator, key } = this.options, offerId = randomId();
|
||||
// createOffer replaces the local peer immediately. Its previous answer
|
||||
// must stop being eligible before gathering or encryption yields.
|
||||
if (initiator) this.offerId = '';
|
||||
const code = initiator ? await this.options.hooks.createOffer() : '';
|
||||
if (this.closed) return;
|
||||
const sdp = await sealSignal(key, this.route(initiator ? 'offer' : 'wake', offerId, this.tracker.peerId), code);
|
||||
if (this.closed) return;
|
||||
if (initiator) this.offerId = offerId;
|
||||
this.tracker.announce(undefined, [{ offerId, sdp }]);
|
||||
} catch (error) { this.fail(error); }
|
||||
finally { this.working = false; }
|
||||
}
|
||||
private fresh(offerId: string) {
|
||||
if (this.seen.has(offerId)) return false;
|
||||
if (this.seen.size >= SEEN_LIMIT) this.seen.delete(this.seen.values().next().value!);
|
||||
this.seen.add(offerId);
|
||||
return true;
|
||||
}
|
||||
private async receiveOffer({ peerId, offerId, sdp }: TrackerSignal) {
|
||||
const role = signalRole(sdp);
|
||||
if (this.closed || this.seen.has(offerId) || (role === 'wake') !== this.options.initiator || role === 'answer' || !role) return;
|
||||
let code: string;
|
||||
try { code = await openSignal(this.options.key, this.route(role, offerId, peerId), sdp); }
|
||||
catch { return; }
|
||||
// Only authenticated messages consume replay slots. Invalid tracker
|
||||
// traffic must not suppress a valid offer or evict previously seen ones.
|
||||
if (this.closed || this.working || !this.fresh(offerId)) return;
|
||||
// A wake means the peer just arrived: offer now unless an offer is very recent.
|
||||
if (role === 'wake') { if (Date.now() - this.lastSignal > 3000) void this.signal(true); return; }
|
||||
this.working = true;
|
||||
try {
|
||||
const answer = await this.options.hooks.createAnswer(code);
|
||||
if (this.closed) return;
|
||||
const sealed = await sealSignal(this.options.key, this.route('answer', offerId, this.tracker.peerId, peerId), answer);
|
||||
if (this.closed) return;
|
||||
this.tracker.answer(peerId, offerId, sealed);
|
||||
this.answered = true;
|
||||
} catch (error) { this.fail(error); }
|
||||
finally { this.working = false; }
|
||||
}
|
||||
private async receiveAnswer({ peerId, offerId, sdp }: TrackerSignal) {
|
||||
if (this.closed || !this.options.initiator || !this.offerId || offerId !== this.offerId) return;
|
||||
let code: string;
|
||||
try { code = await openSignal(this.options.key, this.route('answer', offerId, peerId, this.tracker.peerId), sdp); }
|
||||
catch { return; }
|
||||
if (this.closed || offerId !== this.offerId) return;
|
||||
this.offerId = '';
|
||||
this.answered = true;
|
||||
try { await this.options.hooks.acceptAnswer(code); }
|
||||
catch (error) { this.fail(error); }
|
||||
}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
import { asError, isRecord } from './validation.ts';
|
||||
import type { BufferedChannel } from './webrtc.ts';
|
||||
import { CHUNK_SIZE, MAX_BUFFERED, waitForBufferDrain } from './webrtc.ts';
|
||||
|
||||
export interface FileMetadata { name: string; size: number; mime: string }
|
||||
export type TransferState = 'verification' | 'waiting-accept' | 'choose-storage' | 'sending' |
|
||||
'receiving' | 'saving' | 'awaiting-receipt' | 'done' | 'closed';
|
||||
export interface TransferResult { blob?: Blob | null; meta: FileMetadata }
|
||||
export interface FileDestination {
|
||||
write(data: ArrayBuffer): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
abort(): Promise<void>;
|
||||
}
|
||||
export interface TransferChannel extends BufferedChannel {
|
||||
binaryType: BinaryType;
|
||||
onopen: ((event: Event) => void) | null;
|
||||
onmessage: ((event: MessageEvent<unknown>) => void) | null;
|
||||
onclose: ((event: Event) => void) | null;
|
||||
onerror: ((event: RTCErrorEvent) => void) | null;
|
||||
send(data: string | ArrayBuffer): void;
|
||||
close(): void;
|
||||
}
|
||||
export interface TransferOptions {
|
||||
file?: File | null;
|
||||
onState?: (state: TransferState) => void;
|
||||
onMeta?: (meta: FileMetadata) => void;
|
||||
onProgress?: (bytes: number, size: number) => void;
|
||||
onComplete?: (result: TransferResult) => void;
|
||||
onError?: (error: Error) => void;
|
||||
onClose?: () => void;
|
||||
timeout?: number;
|
||||
}
|
||||
type ControlType = 'ready' | 'meta' | 'accept' | 'ack' | 'end' | 'complete';
|
||||
|
||||
export const MEMORY_LIMIT = 64 * 1024 * 1024;
|
||||
const CONTROL_LIMIT = 2048;
|
||||
const WINDOW = MAX_BUFFERED;
|
||||
|
||||
export function validateMetadata(meta: unknown): FileMetadata {
|
||||
if (!isRecord(meta) || typeof meta.name !== 'string' || !meta.name.length || meta.name.length > 255 ||
|
||||
/[\x00-\x1f\x7f/\\\u202a-\u202e\u2066-\u2069]/.test(meta.name) ||
|
||||
typeof meta.size !== 'number' || !Number.isSafeInteger(meta.size) || meta.size < 0 ||
|
||||
typeof meta.mime !== 'string' || meta.mime.length > 128 || /[^\x20-\x7e]/.test(meta.mime)) {
|
||||
throw new Error('Invalid file metadata. File size must be a nonnegative safe integer.');
|
||||
}
|
||||
return { name: meta.name, size: meta.size, mime: meta.mime };
|
||||
}
|
||||
|
||||
// One ordered, reliable channel; bounded receive queue and acknowledged send window.
|
||||
export class Transfer {
|
||||
readonly dc: TransferChannel;
|
||||
file: File | null;
|
||||
readonly sending: boolean;
|
||||
peerSupportsRepeat = false;
|
||||
readonly onClose: () => void;
|
||||
readonly onState: NonNullable<TransferOptions['onState']>;
|
||||
readonly onMeta: NonNullable<TransferOptions['onMeta']>;
|
||||
readonly onProgress: NonNullable<TransferOptions['onProgress']>;
|
||||
readonly onComplete: NonNullable<TransferOptions['onComplete']>;
|
||||
readonly onError: NonNullable<TransferOptions['onError']>;
|
||||
readonly timeout: number;
|
||||
state: TransferState;
|
||||
verified: boolean;
|
||||
peerReady: boolean;
|
||||
readySent: boolean;
|
||||
closed: boolean;
|
||||
received: number;
|
||||
sent: number;
|
||||
acked: number;
|
||||
queued: number;
|
||||
messages: number;
|
||||
chunks: ArrayBuffer[];
|
||||
queue: Promise<void>;
|
||||
readonly controller: AbortController;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private meta: FileMetadata | null = null;
|
||||
private writable: FileDestination | null = null;
|
||||
private wake: (() => void) | null = null;
|
||||
|
||||
private get metadata(): FileMetadata {
|
||||
if (!this.meta) throw new Error('Missing file metadata.');
|
||||
return this.meta;
|
||||
}
|
||||
constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, onClose = () => {}, timeout = 60000 }: TransferOptions = {}) {
|
||||
this.dc = dc;
|
||||
this.file = file;
|
||||
this.sending = !!file;
|
||||
this.onClose = onClose;
|
||||
this.onState = onState;
|
||||
this.onMeta = onMeta;
|
||||
this.onProgress = onProgress;
|
||||
this.onComplete = onComplete;
|
||||
this.onError = onError;
|
||||
this.timeout = timeout;
|
||||
this.state = 'verification';
|
||||
this.verified = false;
|
||||
this.peerReady = false;
|
||||
this.readySent = false;
|
||||
this.closed = false;
|
||||
this.received = this.sent = this.acked = this.queued = this.messages = 0;
|
||||
this.chunks = [];
|
||||
this.queue = Promise.resolve();
|
||||
this.controller = new AbortController();
|
||||
dc.binaryType = 'arraybuffer';
|
||||
dc.onopen = () => this.guard(() => this.ready());
|
||||
dc.onmessage = e => this.enqueue(e.data);
|
||||
const transportEnded = (message: string) => {
|
||||
// Firefox can report an SCTP error when the sender closes its peer
|
||||
// connection after receiving our completion ACK. The saved file remains
|
||||
// valid; a transport shutdown must not revoke a completed download.
|
||||
if (this.state === 'done') this.close();
|
||||
else this.fail(new Error(message));
|
||||
};
|
||||
dc.onclose = () => transportEnded('Connection closed before receipt was confirmed.');
|
||||
dc.onerror = () => transportEnded('Data channel failed.');
|
||||
this.touch(5 * 60 * 1000);
|
||||
}
|
||||
setState(state: TransferState) { this.state = state; this.onState(state); }
|
||||
touch(ms = this.timeout) {
|
||||
clearTimeout(this.timer);
|
||||
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); } }
|
||||
control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number; repeat?: boolean } = {}) {
|
||||
if (this.closed || this.dc.readyState !== 'open') throw new Error('Connection is not open.');
|
||||
const text = JSON.stringify({ v: 2, type, ...data });
|
||||
if (text.length > CONTROL_LIMIT) throw new Error('Control message is too large.');
|
||||
this.dc.send(text);
|
||||
}
|
||||
verify() {
|
||||
if (this.closed || this.verified) return;
|
||||
this.verified = true;
|
||||
this.guard(() => this.ready());
|
||||
}
|
||||
ready() {
|
||||
if (!this.verified || this.dc.readyState !== 'open' || this.closed) return;
|
||||
if (!this.readySent) { this.control('ready', { repeat: true }); this.readySent = true; }
|
||||
if (this.file && this.peerReady && this.state === 'verification') {
|
||||
this.meta = validateMetadata({ name: this.file.name, size: this.file.size, mime: this.file.type || '' });
|
||||
this.setState('waiting-accept');
|
||||
this.control('meta', this.metadata);
|
||||
this.touch(5 * 60 * 1000);
|
||||
}
|
||||
}
|
||||
enqueue(data: unknown) {
|
||||
if (this.closed) return;
|
||||
const binary = data instanceof ArrayBuffer;
|
||||
const size = binary ? data.byteLength : typeof data === 'string' ? data.length : Infinity;
|
||||
if (size > (binary ? CHUNK_SIZE : CONTROL_LIMIT) || this.queued + size > WINDOW * 2 || this.messages >= 128) {
|
||||
this.fail(new Error('Peer exceeded message or buffering limits.')); return;
|
||||
}
|
||||
this.queued += size; this.messages++;
|
||||
this.queue = this.queue.then(async () => {
|
||||
if (!this.closed) await this.message(data);
|
||||
}).catch(err => this.fail(err)).finally(() => { this.queued -= size; this.messages--; });
|
||||
}
|
||||
async message(data: unknown) {
|
||||
if (data instanceof ArrayBuffer) {
|
||||
if (this.file || this.state !== 'receiving' || !data.byteLength || this.received + data.byteLength > this.metadata.size) throw new Error('Unexpected or excess file data.');
|
||||
// Bound per-chunk overhead as well as payload bytes: millions of tiny
|
||||
// ArrayBuffers would otherwise defeat the in-memory size limit.
|
||||
if (data.byteLength !== Math.min(CHUNK_SIZE, this.metadata.size - this.received)) throw new Error('Invalid file chunk size.');
|
||||
if (this.writable) await this.writable.write(data);
|
||||
else this.chunks.push(data);
|
||||
if (this.closed) return;
|
||||
this.received += data.byteLength;
|
||||
this.control('ack', { bytes: this.received });
|
||||
this.onProgress(this.received, this.metadata.size);
|
||||
this.touch();
|
||||
return;
|
||||
}
|
||||
if (typeof data !== 'string') throw new Error('Unsupported transfer message.');
|
||||
const msg: unknown = JSON.parse(data);
|
||||
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') {
|
||||
this.peerSupportsRepeat = msg.repeat === true;
|
||||
this.peerReady = true; this.ready(); return;
|
||||
}
|
||||
if (!this.verified || !this.peerReady || !this.readySent) throw new Error('File data arrived before verification.');
|
||||
if (msg.type === 'meta' && !this.sending && (this.state === 'verification' || (this.state === 'done' && this.peerSupportsRepeat))) {
|
||||
const meta = validateMetadata(msg);
|
||||
this.resetFile();
|
||||
this.meta = meta;
|
||||
this.setState('choose-storage'); this.onMeta(this.metadata); this.touch(5 * 60 * 1000); return;
|
||||
}
|
||||
if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') {
|
||||
this.setState('sending'); this.touch();
|
||||
void this.sendFile().catch(err => this.fail(err)); return;
|
||||
}
|
||||
if (msg.type === 'ack' && this.file && ['sending', 'awaiting-receipt'].includes(this.state)) {
|
||||
if (typeof msg.bytes !== 'number' || !Number.isSafeInteger(msg.bytes) || msg.bytes <= this.acked || msg.bytes > this.sent ||
|
||||
(msg.bytes !== this.file.size && msg.bytes % CHUNK_SIZE !== 0)) throw new Error('Invalid receipt count.');
|
||||
this.acked = msg.bytes; this.onProgress(this.acked, this.file.size); this.wake?.(); this.touch(); return;
|
||||
}
|
||||
if (msg.type === 'end' && !this.file && this.state === 'receiving') {
|
||||
if (this.received !== this.metadata.size) throw new Error('Incomplete file.');
|
||||
this.setState('saving');
|
||||
if (this.writable) await this.writable.close();
|
||||
if (this.closed) return;
|
||||
// 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' });
|
||||
this.chunks = [];
|
||||
this.writable = null;
|
||||
this.control('complete', { bytes: this.received });
|
||||
this.setState('done'); clearTimeout(this.timer);
|
||||
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) {
|
||||
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.metadata });
|
||||
if (!this.peerSupportsRepeat) this.close();
|
||||
return;
|
||||
}
|
||||
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) {
|
||||
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.');
|
||||
this.writable = writable;
|
||||
this.setState('receiving'); this.touch();
|
||||
this.guard(() => this.control('accept'));
|
||||
}
|
||||
async sendFile() {
|
||||
const file = this.file;
|
||||
if (!file) throw new Error('No file selected.');
|
||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||
if (this.sent - this.acked >= WINDOW) await new Promise<void>(resolve => { this.wake = resolve; });
|
||||
this.wake = null;
|
||||
if (this.closed) return;
|
||||
if (this.dc.bufferedAmount > MAX_BUFFERED) await waitForBufferDrain(this.dc, { signal: this.controller.signal, timeout: this.timeout });
|
||||
const buffer = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
|
||||
if (this.closed) return;
|
||||
this.sent += buffer.byteLength;
|
||||
this.dc.send(buffer);
|
||||
}
|
||||
if (this.closed) return;
|
||||
this.setState('awaiting-receipt'); this.control('end'); this.touch();
|
||||
}
|
||||
fail(err: unknown) {
|
||||
if (this.closed) return;
|
||||
this.close(); this.setState('closed'); this.onError(asError(err));
|
||||
}
|
||||
close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true; clearTimeout(this.timer); this.controller.abort(); this.wake?.(); this.wake = null;
|
||||
this.chunks = [];
|
||||
const writable = this.writable;
|
||||
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.close();
|
||||
this.onClose();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((item: unknown) => typeof item === 'string');
|
||||
}
|
||||
|
||||
export function asError(value: unknown, fallback = 'Connection failed.'): Error {
|
||||
return value instanceof Error ? value : new Error(fallback);
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
import { isRecord, isStringArray } from './validation.ts';
|
||||
|
||||
export interface IceOptions {
|
||||
stunUrl?: string | null;
|
||||
allowTurn?: boolean;
|
||||
managedTurn?: boolean;
|
||||
turnUrl?: string | string[];
|
||||
username?: string;
|
||||
credential?: string;
|
||||
}
|
||||
|
||||
export interface NetworkSettings {
|
||||
stunChoice: 'pagequit' | 'google' | 'cloudflare' | 'none' | 'custom';
|
||||
customStun: string;
|
||||
allowTurn: boolean;
|
||||
managedTurn: boolean;
|
||||
turnUrl: string;
|
||||
username: string;
|
||||
credential: string;
|
||||
}
|
||||
|
||||
export interface WaitOptions { signal?: AbortSignal; timeout?: number }
|
||||
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'>;
|
||||
export interface Fingerprints { local: string; remote: string }
|
||||
export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>;
|
||||
export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>;
|
||||
type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>;
|
||||
|
||||
// Manual signaling; codes.ts encodes the validated descriptions for exchange.
|
||||
export const CHUNK_SIZE = 16 * 1024;
|
||||
export const MAX_BUFFERED = 1024 * 1024;
|
||||
export const MAX_SIGNAL_LENGTH = 64 * 1024;
|
||||
export const STUN_PROVIDERS = [
|
||||
{ id: 'pagequit', label: 'PageQuit', url: 'stun:stun.pagequit.net:3478' },
|
||||
{ id: 'google', label: 'Google', url: 'stun:stun.l.google.com:19302' },
|
||||
{ id: 'cloudflare', label: 'Cloudflare', url: 'stun:stun.cloudflare.com:3478' },
|
||||
{ id: 'none', label: 'None (direct connections only)', url: null },
|
||||
];
|
||||
|
||||
export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl = '', username = '', credential = '' }: IceOptions = {}): { iceServers: RTCIceServer[] } {
|
||||
const iceServers: RTCIceServer[] = [];
|
||||
if (stunUrl) {
|
||||
if (!/^stuns?:[^\s/?#@]+$/i.test(stunUrl)) throw new Error('Enter a stun: or stuns: server address.');
|
||||
iceServers.push({ urls: stunUrl });
|
||||
}
|
||||
// Credentials and URLs are ignored unless this user explicitly opts in.
|
||||
if (allowTurn) {
|
||||
const urls = Array.isArray(turnUrl) ? turnUrl : [turnUrl];
|
||||
if (!urls.length || !urls.every(url => typeof url === 'string' && /^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(url)) || !username || !credential) {
|
||||
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
|
||||
}
|
||||
iceServers.push({ urls: turnUrl, username, credential });
|
||||
}
|
||||
return { iceServers };
|
||||
}
|
||||
|
||||
export async function fetchTurnOptions(options: IceOptions, endpoint: string, { signal, fetchImpl = fetch }: { signal?: AbortSignal; fetchImpl?: CredentialFetch } = {}): Promise<IceOptions> {
|
||||
if (!options.allowTurn || !options.managedTurn || !endpoint) return options;
|
||||
const response = await fetchImpl(endpoint, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||
if (!response.ok) throw new Error('Could not obtain TURN credentials. Check the local dev server.');
|
||||
const data: unknown = await response.json();
|
||||
if (!isRecord(data) || typeof data.expiresAt !== 'number' || !Number.isFinite(data.expiresAt) ||
|
||||
data.expiresAt <= Date.now() / 1000 + 30 || !Array.isArray(data.iceServers)) {
|
||||
throw new Error('Missing or expired TURN credentials.');
|
||||
}
|
||||
const turn: unknown = data.iceServers.find((server: unknown) => {
|
||||
if (!isRecord(server)) return false;
|
||||
const urls: unknown[] = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return urls.length > 0 && urls.every(url => typeof url === 'string' && /^turns?:/i.test(url));
|
||||
});
|
||||
if (!isRecord(turn) || typeof turn.username !== 'string' || typeof turn.credential !== 'string' ||
|
||||
!(typeof turn.urls === 'string' || isStringArray(turn.urls))) {
|
||||
throw new Error('Missing or invalid TURN credentials.');
|
||||
}
|
||||
const result = { ...options, turnUrl: turn.urls, username: turn.username, credential: turn.credential };
|
||||
iceConfiguration(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createPeerConnection(options: IceOptions) {
|
||||
return new RTCPeerConnection(iceConfiguration(options));
|
||||
}
|
||||
|
||||
export function waitForIceComplete(pc: IcePeer, { signal, timeout = 30000 }: WaitOptions = {}) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
pc.removeEventListener('icegatheringstatechange', check);
|
||||
pc.removeEventListener('connectionstatechange', check);
|
||||
signal?.removeEventListener('abort', aborted);
|
||||
};
|
||||
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const aborted = () => finish(new Error('Connection cancelled.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || pc.connectionState === 'closed') aborted();
|
||||
else if (pc.iceGatheringState === 'complete') finish();
|
||||
};
|
||||
pc.addEventListener('icegatheringstatechange', check);
|
||||
pc.addEventListener('connectionstatechange', check);
|
||||
signal?.addEventListener('abort', aborted, { once: true });
|
||||
timer = setTimeout(() => finish(new Error('Connection gathering timed out. Check the server settings and try again.')), timeout);
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<IceOptions, 'allowTurn'> = {}) {
|
||||
if (typeof sdp !== 'string' || sdp.length > MAX_SIGNAL_LENGTH || /[^\x09\x0A\x0D\x20-\x7E]/.test(sdp)) {
|
||||
throw new Error('Invalid connection description.');
|
||||
}
|
||||
const lines = sdp.split(/\r?\n/);
|
||||
const media = lines.filter(line => line.startsWith('m='));
|
||||
if (media.length !== 1 || !/^m=application \d+ (?:UDP\/DTLS\/SCTP|DTLS\/SCTP) (?:webrtc-datachannel|\d+)$/.test(media[0])) {
|
||||
throw new Error('Only a single file data channel is supported.');
|
||||
}
|
||||
// Deliberately reject ambiguous fingerprints rather than guessing SDP scope.
|
||||
const fingerprints = lines.filter(line => line.startsWith('a=fingerprint:'));
|
||||
if (fingerprints.length !== 1 || !/^a=fingerprint:sha-256 (?:[\da-f]{2}:){31}[\da-f]{2}$/i.test(fingerprints[0])) {
|
||||
throw new Error('A single full SHA-256 fingerprint is required.');
|
||||
}
|
||||
if (!allowTurn && lines.some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line))) {
|
||||
throw new Error('This code contains a TURN relay. Both people must explicitly enable TURN and create new codes to use a relay.');
|
||||
}
|
||||
return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
|
||||
}
|
||||
|
||||
export function getFingerprints(pc: { localDescription: { sdp: string } | null; remoteDescription: { sdp: string } | null }, options?: Pick<IceOptions, 'allowTurn'>): Fingerprints {
|
||||
return {
|
||||
local: validateDescription(pc.localDescription?.sdp, options),
|
||||
remote: validateDescription(pc.remoteDescription?.sdp, options),
|
||||
};
|
||||
}
|
||||
|
||||
// Each step validates the description it produces or applies.
|
||||
export async function createOffer(pc: RTCPeerConnection, options: SignalOptions = {}) {
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return pc.localDescription.sdp;
|
||||
}
|
||||
|
||||
export async function createAnswer(pc: RTCPeerConnection, offer: string, options: SignalOptions = {}) {
|
||||
validateDescription(offer, options);
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp: offer });
|
||||
await pc.setLocalDescription(await pc.createAnswer());
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return pc.localDescription.sdp;
|
||||
}
|
||||
|
||||
export function acceptAnswer(pc: RTCPeerConnection, answer: string, options?: SignalOptions) {
|
||||
validateDescription(answer, options);
|
||||
return pc.setRemoteDescription({ type: 'answer', sdp: answer });
|
||||
}
|
||||
|
||||
export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
dc.removeEventListener('bufferedamountlow', check);
|
||||
dc.removeEventListener('close', check);
|
||||
dc.removeEventListener('error', failed);
|
||||
signal?.removeEventListener('abort', failed);
|
||||
};
|
||||
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const failed = () => finish(new Error('Transfer interrupted.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || dc.readyState !== 'open') failed();
|
||||
else if (dc.bufferedAmount <= MAX_BUFFERED / 2) finish();
|
||||
};
|
||||
dc.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||
dc.addEventListener('bufferedamountlow', check);
|
||||
dc.addEventListener('close', check);
|
||||
dc.addEventListener('error', failed);
|
||||
signal?.addEventListener('abort', failed, { once: true });
|
||||
timer = setTimeout(() => finish(new Error('Transfer stalled.')), timeout);
|
||||
check();
|
||||
});
|
||||
}
|
||||
+5
-363
@@ -1,369 +1,11 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #0f1117;
|
||||
--panel: #181b24;
|
||||
--border: #2a2f3d;
|
||||
--accent: #ff9b3d;
|
||||
--accent-soft: rgba(255, 155, 61, 0.15);
|
||||
--text: #e8eaf0;
|
||||
--muted: #a0a7b8;
|
||||
--space-sm: 0.6rem;
|
||||
--space-md: 0.9rem;
|
||||
--space-lg: 1.25rem;
|
||||
--space-xl: 1.5rem;
|
||||
--space-2xl: 2rem;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
color-scheme: light dark;
|
||||
font-family: system-ui, sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
#app { height: 100dvh; min-height: 420px; }
|
||||
|
||||
.skip-link {
|
||||
position: absolute;
|
||||
left: 0.9rem;
|
||||
top: 0.5rem;
|
||||
transform: translateY(-200%);
|
||||
z-index: 10;
|
||||
padding: 0.55rem 0.8rem;
|
||||
border-radius: 8px;
|
||||
background: var(--accent);
|
||||
color: var(--bg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.skip-link:focus {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.panel {
|
||||
width: 100%;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: var(--space-lg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-family: ui-monospace, 'Cascadia Code', monospace;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: var(--muted);
|
||||
margin: 0 0 1.5rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
button {
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.55rem 1rem;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
:where(a, button, input, select, textarea):focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: var(--bg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.tabs button.active {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: var(--bg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.step {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
min-height: 90px;
|
||||
resize: vertical;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.6rem;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.75rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.dropzone {
|
||||
border: 2px dashed var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dropzone.dragover {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.progress {
|
||||
height: 10px;
|
||||
background: var(--bg);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress > div {
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
transition: width 0.15s linear;
|
||||
}
|
||||
|
||||
.status {
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #ff6b5e;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.file-chip {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.6rem 0.9rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
a.download {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.fingerprint {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.75rem 0.9rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.fp-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.fp-row code {
|
||||
font-family: ui-monospace, monospace;
|
||||
color: var(--accent);
|
||||
letter-spacing: 0.12em;
|
||||
}
|
||||
|
||||
.fingerprint .status {
|
||||
margin: 0.2rem 0 0;
|
||||
}
|
||||
|
||||
.stun-select,
|
||||
.stun-input {
|
||||
width: 100%;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.55rem 0.75rem;
|
||||
font-size: 0.95rem;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.stun-input {
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.stun-select:focus,
|
||||
.stun-input:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
p.stun-hint {
|
||||
margin: -0.35rem 0 0;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.network-settings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-sm);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
min-width: 0;
|
||||
padding: var(--space-sm) var(--space-md) var(--space-md);
|
||||
}
|
||||
.network-settings legend { color: var(--muted); }
|
||||
.checkbox { display: flex; align-items: start; gap: var(--space-sm); }
|
||||
.fp-row { flex-direction: column; align-items: start; }
|
||||
.fp-row code { overflow-wrap: anywhere; line-height: 1.7; font-size: 0.8rem; }
|
||||
.file-chip span { overflow-wrap: anywhere; min-width: 0; }
|
||||
.incoming { display: flex; flex-direction: column; gap: 0.7rem; overflow-wrap: anywhere; }
|
||||
|
||||
.transfer-section { display: flex; flex-direction: column; gap: var(--space-md); scroll-margin-top: 1rem; min-width: 0; }
|
||||
.transfer-section:focus-visible { outline: 2px solid var(--accent); outline-offset: 6px; border-radius: 4px; }
|
||||
|
||||
.device-settings { display: flex; flex-direction: column; gap: var(--space-sm); min-width: 0; border: 1px solid var(--border); border-radius: 8px; padding: var(--space-sm) var(--space-md) var(--space-md); }
|
||||
.config-details > :not(summary) { margin-block: var(--space-sm) 0; }
|
||||
.config-details fieldset .status { margin-block: 0; line-height: 1.5; }
|
||||
.device-settings input:not([type=checkbox]) { box-sizing: border-box; max-width: 100%; padding: 0.6rem; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; }
|
||||
|
||||
/* The connection shell stays in place while each workspace scrolls. */
|
||||
.app-shell { display: grid; grid-template-columns: 264px minmax(0, 1fr); height: 100%; }
|
||||
.sidebar { display: flex; flex-direction: column; gap: var(--space-lg); background: #13161e; border-right: 1px solid var(--border); padding: 1.6rem 1rem 1rem; min-height: 0; overflow-y: auto; }
|
||||
.brand { display: flex; align-items: center; gap: 0.8rem; padding: 0 0.5rem var(--space-lg); }
|
||||
.brand img { object-fit: contain; }
|
||||
.brand-name { display: block; font-family: ui-monospace, monospace; font-weight: 700; font-size: 1.45rem; letter-spacing: -0.05em; }
|
||||
.brand p { font-size: 0.75rem; color: var(--muted); margin: 0.25rem 0 0; }
|
||||
.sidebar-section-heading { display: flex; align-items: center; justify-content: space-between; padding: 0 0.65rem; }
|
||||
.sidebar-section-heading h2 { text-transform: uppercase; font-size: 0.68rem; letter-spacing: 0.12em; color: var(--muted); margin: 0; font-weight: 650; }
|
||||
.sidebar-section-heading > span { font-size: 0.72rem; color: var(--muted); }
|
||||
.connection-nav { display: flex; flex-direction: column; gap: 0.35rem; }
|
||||
.connection-item { position: relative; border: 1px solid transparent; border-radius: 9px; }
|
||||
.connection-item.selected { background: var(--accent-soft); border-color: #65472e; }
|
||||
.connection-link, .connection-edit { display: flex; flex-direction: column; align-items: stretch; justify-content: center; gap: 0.4rem; min-width: 0; width: 100%; min-height: 64px; padding: 0.55rem 4.2rem 0.55rem 0.7rem; }
|
||||
.connection-link { text-align: left; background: transparent; border: 0; border-radius: 8px; }
|
||||
.connection-link:hover:not(:disabled) { background: #ffffff08; }
|
||||
.connection-edit { padding-right: 2.4rem; }
|
||||
.connection-name { color: var(--text); font-size: 0.87rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.connection-status-line { display: flex; align-items: center; gap: 0.45rem; min-width: 0; color: var(--muted); font-size: 0.72rem; }
|
||||
.connection-status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.connection-action { position: absolute; top: 0.45rem; display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 0; background: transparent; color: var(--muted); font-size: 0.9rem; }
|
||||
.connection-action:hover:not(:disabled), .connection-action:focus-visible { color: var(--accent); }
|
||||
.edit-action { right: 2.25rem; }
|
||||
.remove-action { right: 0.35rem; }
|
||||
.remove-action:hover:not(:disabled), .remove-action:focus-visible { color: #ff9185; }
|
||||
.connection-rename-input { width: 100%; min-width: 0; border: 1px solid var(--accent); border-radius: 6px; padding: 0.28rem 0.35rem; background: var(--bg); color: var(--text); font: inherit; font-size: 0.87rem; font-weight: 600; }
|
||||
.connection-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: #7c8495; flex-shrink: 0; }
|
||||
.connection-dot.connected { background: #69d6a4; }
|
||||
.connection-dot.connecting { background: var(--accent); }
|
||||
.add-connection { display: flex; align-items: center; justify-content: center; gap: 0.5rem; font-size: 0.82rem; background: transparent; border-style: dashed; }
|
||||
.add-connection > span { font-size: 1.1rem; }
|
||||
.sidebar-footer { margin-top: auto; padding: var(--space-xl) 0.65rem 0.25rem; color: var(--muted); font-size: 0.72rem; line-height: 1.65; }
|
||||
.sidebar-tag { font-weight: 600; color: var(--text); }
|
||||
.sidebar-footer p { margin: 0.5rem 0 1rem; }
|
||||
.source-link { display: inline-flex; align-items: center; gap: 0.35rem; margin-top: 0.4rem; color: var(--muted); text-decoration: none; }
|
||||
.source-link:hover { color: var(--text); }
|
||||
.source-link img { filter: grayscale(1); opacity: 0.6; }
|
||||
.source-link:hover img { opacity: 0.9; }
|
||||
summary { cursor: pointer; color: var(--muted); font-size: 0.83rem; padding: 0.4rem 0; }
|
||||
summary:hover { color: var(--text); }
|
||||
summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
.privacy-details summary { font-size: 0.72rem; }
|
||||
.main-pane { min-width: 0; min-height: 0; display: flex; flex-direction: column; }
|
||||
.workspace-scroll { flex: 1; overflow-y: auto; padding: var(--space-2xl) 2.25rem; }
|
||||
.connection-workspace { width: 100%; max-width: 720px; min-width: 0; margin-inline: auto; }
|
||||
.workspace-intro { margin-bottom: 1.4rem; }
|
||||
.workspace-intro h2 { font-size: 1.05rem; font-weight: 600; margin: 0 0 0.4rem; }
|
||||
.workspace-intro p { font-size: 0.85rem; color: var(--muted); line-height: 1.6; margin: 0; }
|
||||
.tabs { width: fit-content; padding: 4px; gap: 4px; background: #1b1f2a; border: 1px solid var(--border); border-radius: 10px; }
|
||||
.tabs button { padding: 0.45rem var(--space-xl); font-size: 0.85rem; border: none; background: transparent; }
|
||||
.tabs button.active { background: #3e3025; color: #ffb575; }
|
||||
.panel { box-shadow: 0 6px 28px #00000012; }
|
||||
.panel > .status { line-height: 1.6; margin: 0.1rem 0; }
|
||||
.panel > button { align-self: start; font-size: 0.88rem; }
|
||||
.dropzone { padding: 1.35rem 1rem; background: #141720; border-color: #414858; }
|
||||
.dropzone p { font-size: 0.85rem; line-height: 1.65; margin: 0 0 1rem; }
|
||||
input[type=file] { max-width: 100%; font-size: 0.8rem; }
|
||||
input[type=file]::file-selector-button { border: 1px solid #505667; border-radius: 6px; padding: 0.45rem 0.65rem; margin-right: 0.6rem; background: #242a36; color: var(--text); cursor: pointer; }
|
||||
.session-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
|
||||
.reconnect-setup { display: flex; flex-direction: column; gap: var(--space-sm); min-width: 0; border-top: 1px solid var(--border); padding-top: var(--space-md); }
|
||||
.reconnect-setup .status { margin: 0; line-height: 1.6; }
|
||||
.session-actions button { font-size: 0.88rem; }
|
||||
.storage-error { color: #ffb4a9; background: #422725; border: 1px solid #8e5147; border-radius: 8px; padding: 1rem; font-size: 0.85rem; line-height: 1.6; }
|
||||
.mobile-bar { display: none; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
|
||||
@media (max-width: 1150px) {
|
||||
.app-shell { grid-template-columns: 230px minmax(0, 1fr); }
|
||||
.workspace-scroll { padding: var(--space-xl); }
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
#app { height: auto; min-height: 100dvh; }
|
||||
.app-shell { display: flex; flex-direction: column; min-height: 100dvh; }
|
||||
.sidebar { display: none; border-right: 0; border-bottom: 1px solid var(--border); max-height: 60dvh; }
|
||||
.sidebar-open .sidebar { display: flex; }
|
||||
.brand { padding-bottom: 0; }
|
||||
.sidebar-footer { padding-top: 0; }
|
||||
.mobile-bar { display: flex; align-items: center; gap: 0.75rem; margin: 0.75rem 1rem 0; }
|
||||
.mobile-current { display: flex; flex-direction: column; gap: 0.3rem; flex: 1; min-width: 0; }
|
||||
.mobile-current-name { font-size: 0.95rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.mobile-current-status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.sidebar-toggle { flex-shrink: 0; margin-left: auto; font-size: 0.8rem; background: transparent; padding: 0.5rem; }
|
||||
.workspace-scroll { padding: var(--space-lg) 1rem; overflow: visible; }
|
||||
.panel { padding: 1rem; }
|
||||
}
|
||||
.app-dialog { width: min(460px, calc(100% - 2rem)); max-height: calc(100dvh - 2rem); margin: auto; padding: 1.5rem; border: 1px solid #414858; border-radius: 14px; color: var(--text); background: var(--panel); box-shadow: 0 24px 100px #0009; overflow-y: auto; }
|
||||
.app-dialog::backdrop { background: #080b12b8; backdrop-filter: blur(4px); }
|
||||
.dialog-header { display: flex; align-items: start; justify-content: space-between; gap: 1rem; }
|
||||
.dialog-header h2 { margin: 0; font-size: 1.15rem; font-weight: 600; line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.dialog-close { flex-shrink: 0; border-color: transparent; background: transparent; color: var(--muted); padding: 0 0.4rem; font-size: 1.4rem; line-height: 1.2; }
|
||||
.dialog-body { color: var(--muted); font-size: 0.88rem; line-height: 1.7; margin-block: 1rem 1.5rem; }
|
||||
.dialog-body p { margin: 0.75rem 0; }
|
||||
.dialog-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 0.6rem; }
|
||||
.dialog-actions button { font-size: 0.85rem; }
|
||||
button.danger { border-color: #b84d42; background: #672f2b; color: #ffe3df; }
|
||||
button.danger:hover:not(:disabled) { border-color: #ff9185; background: #813b34; }
|
||||
@media (max-width: 700px) { .app-dialog { padding: 1.2rem; } }
|
||||
Reference in new issue
Block a user