WIP IV improve UX [snapshot task 2]
This commit is contained in:
1 parent
28c90d1d71
commit
58c3e2af86
16 files changed
+779
-36
No files matched your search
+1
-1
@@ -40,7 +40,7 @@ const canDownloadApp = import.meta.env.PROD && !isLocal;
|
||||
<footer>
|
||||
<p>
|
||||
Files travel over encrypted WebRTC data channels (SCTP over DTLS).
|
||||
Verify both full fingerprints before sharing. This requires trusted
|
||||
Compare both full fingerprints on first pairing, or authenticate an expected remembered device. This requires trusted
|
||||
browsers, a trusted copy of this app, and an authenticated comparison
|
||||
channel. The website host supplies JavaScript that can read your selected
|
||||
file; HTTPS protects delivery but cannot protect you from a malicious host.
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
|
||||
import { clearIdentityStorage, createIdentity, loadIdentityState, saveIdentityState, exportBackup, importBackup, type IdentityState } from '../lib/identity.ts';
|
||||
import { asError } from '../lib/validation.ts';
|
||||
const props = defineProps<{ disabled: boolean }>();
|
||||
const emit = defineEmits<{ change: [state: IdentityState, enabled: boolean, expected: string] }>();
|
||||
const supported = (() => { try { return location.protocol !== 'file:' && isSecureContext && !!crypto.subtle && !!window.indexedDB; } catch { return false; } })();
|
||||
const state = shallowRef<IdentityState>({ identity: null, contacts: [] });
|
||||
const enabled = ref(false), expected = ref(''), working = ref(false), loaded = ref(false);
|
||||
const error = ref(''), password = ref(''), confirmReplace = ref(false);
|
||||
const backupUrl = ref('');
|
||||
onBeforeUnmount(() => { if (backupUrl.value) URL.revokeObjectURL(backupUrl.value); });
|
||||
watch([state, enabled, expected], () => emit('change', state.value, enabled.value, expected.value));
|
||||
onMounted(async () => {
|
||||
if (!supported) return;
|
||||
try { state.value = await loadIdentityState(); loaded.value = true; }
|
||||
catch (err) { error.value = asError(err).message; }
|
||||
});
|
||||
async function store(next: IdentityState) {
|
||||
state.value = await saveIdentityState(next, state.value.revision);
|
||||
if (backupUrl.value) { URL.revokeObjectURL(backupUrl.value); backupUrl.value = ''; }
|
||||
}
|
||||
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; password.value = ''; }
|
||||
}
|
||||
function recover() { void run(async () => { if (!confirmReplace.value) return; await clearIdentityStorage(); state.value = { identity: null, contacts: [] }; loaded.value = true; confirmReplace.value = false; }); }
|
||||
function create() { void run(async () => { await store({ identity: await createIdentity(), contacts: [] }); enabled.value = true; }); }
|
||||
function remove(key: string) { void run(async () => { await store({ ...state.value, contacts: state.value.contacts.filter(item => item.key !== key) }); if (expected.value === key) expected.value = ''; }); }
|
||||
function reset() { void run(async () => { if (!confirmReplace.value) return; await store({ identity: null, contacts: [] }); enabled.value = false; expected.value = ''; confirmReplace.value = false; }); }
|
||||
function backup() { void run(async () => {
|
||||
const data = await exportBackup(state.value, password.value);
|
||||
if (backupUrl.value) URL.revokeObjectURL(backupUrl.value);
|
||||
backupUrl.value = URL.createObjectURL(new Blob([data], { type: 'application/json' }));
|
||||
}); }
|
||||
function restore(event: Event) {
|
||||
const input = event.target as HTMLInputElement, file = input.files?.[0]; input.value = '';
|
||||
if (!file) return;
|
||||
void run(async () => {
|
||||
if (state.value.identity && !confirmReplace.value) throw new Error('Confirm replacement before restoring a backup.');
|
||||
if (file.size > 100000) throw new Error('Backup is too large.');
|
||||
const next = await importBackup(await file.text(), password.value);
|
||||
await store(next); enabled.value = false; expected.value = ''; confirmReplace.value = false;
|
||||
});
|
||||
}
|
||||
async function remember(key: string, name: string) {
|
||||
if (!state.value.identity) throw new Error('Create a local identity first.');
|
||||
const next = { ...state.value, contacts: [...state.value.contacts.filter(item => item.key !== key), { key, name }] };
|
||||
await store(next);
|
||||
}
|
||||
async function refreshForConnection() {
|
||||
if (working.value) throw new Error('Wait for the device settings operation to finish before connecting.');
|
||||
if (!supported || !enabled.value) return { identity: null, expected: '' };
|
||||
try {
|
||||
const next = await loadIdentityState();
|
||||
if (next.identity?.publicKey !== state.value.identity?.publicKey) {
|
||||
enabled.value = false; expected.value = '';
|
||||
}
|
||||
if (!next.contacts.some(contact => contact.key === expected.value)) expected.value = '';
|
||||
if (next.revision !== state.value.revision) {
|
||||
if (backupUrl.value) URL.revokeObjectURL(backupUrl.value);
|
||||
backupUrl.value = ''; confirmReplace.value = false; password.value = '';
|
||||
}
|
||||
state.value = next; loaded.value = true; error.value = '';
|
||||
return { identity: enabled.value ? next.identity : null, expected: expected.value };
|
||||
} catch (err) {
|
||||
error.value = asError(err).message;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
defineExpose({ remember, refreshForConnection });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<details v-if="supported">
|
||||
<summary>Remembered devices</summary>
|
||||
<p class="status">Opt in to a device identity stored in this browser. Temporary connections remain available. Clearing site data loses your identity and contacts. Trusted app code is required: it can use and export 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>
|
||||
<label><input id="use-device-identity" v-model="enabled" type="checkbox" /> Use my device identity for this connection</label>
|
||||
<p class="status">Your public identity is included in connection codes when enabled and can link your sessions.</p>
|
||||
<label for="expected-device">Expected device</label>
|
||||
<select id="expected-device" v-model="expected" :disabled="!enabled">
|
||||
<option value="">New device — compare fingerprints manually</option>
|
||||
<option v-for="contact in state.contacts" :key="contact.key" :value="contact.key">{{ contact.name }} ({{ contact.key.slice(-12) }})</option>
|
||||
</select>
|
||||
<ul aria-label="Remembered devices"><li v-for="contact in state.contacts" :key="contact.key">{{ contact.name }} <button @click="remove(contact.key)" :aria-label="'Forget ' + contact.name">Forget</button></li></ul>
|
||||
</template>
|
||||
<label for="backup-password">Backup password (at least 12 characters)</label>
|
||||
<input id="backup-password" v-model="password" type="password" autocomplete="new-password" maxlength="1024" />
|
||||
<button :disabled="!state.identity || password.length < 12" @click="backup">Create encrypted backup</button>
|
||||
<a v-if="backupUrl" :href="backupUrl" download="hellcon-device-backup.json">Save encrypted backup</a>
|
||||
<p class="status">A backup contains your identity and contacts. Keep its password separately. Restoring the same backup on another browser gives that browser the same identity.</p>
|
||||
<label v-if="state.identity"><input v-model="confirmReplace" type="checkbox" /> Replace or delete this browser’s identity and contacts</label>
|
||||
<label for="restore-identity">Restore encrypted backup</label>
|
||||
<input id="restore-identity" type="file" accept="application/json,.json" :disabled="password.length < 12 || (!!state.identity && !confirmReplace)" @change="restore" />
|
||||
<button v-if="state.identity" :disabled="!confirmReplace" @click="reset">Delete identity and contacts</button>
|
||||
</fieldset>
|
||||
<div v-if="!loaded && error">
|
||||
<label><input v-model="confirmReplace" type="checkbox" :disabled="disabled || working" /> Delete unreadable device storage, including identity and contacts</label>
|
||||
<button :disabled="disabled || working || !confirmReplace" @click="recover">Clear device storage</button>
|
||||
</div>
|
||||
<p v-if="error" role="alert" class="error">{{ error }}</p>
|
||||
</details>
|
||||
</template>
|
||||
@@ -2,9 +2,11 @@
|
||||
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, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, onBeforeUnmount, ref, shallowRef, 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 { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, decodeSignal, signalIdentity, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.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';
|
||||
@@ -17,10 +19,28 @@ interface Session {
|
||||
controller: AbortController;
|
||||
transfer: FileSession | null;
|
||||
diagnostics: ConnectionDiagnostics;
|
||||
localHello?: IdentityHello;
|
||||
remoteHello?: IdentityHello;
|
||||
identityContext?: IdentityContext;
|
||||
identity?: IdentityState['identity'];
|
||||
expected?: string;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const props = defineProps<{ sending?: boolean }>();
|
||||
const devices = ref<InstanceType<typeof DeviceSettings> | null>(null);
|
||||
const deviceState = shallowRef<IdentityState>({ identity: null, contacts: [] });
|
||||
const identityStatus = ref(''), contactName = ref('');
|
||||
const canRemember = ref(false), savingContact = ref(false);
|
||||
function deviceChange(state: IdentityState) { deviceState.value = state; }
|
||||
async function saveContact() {
|
||||
const session = active;
|
||||
if (!session?.remoteHello || !connected.value || !canRemember.value || savingContact.value) return;
|
||||
savingContact.value = true;
|
||||
try { await devices.value?.remember(session.remoteHello.key, contactName.value.trim()); canRemember.value = false; contactName.value = ''; }
|
||||
catch (err) { error.value = asError(err).message; }
|
||||
finally { savingContact.value = false; }
|
||||
}
|
||||
const file = ref<File | null>(null);
|
||||
const selectedFiles = ref<File[]>([]);
|
||||
const queuedFiles = ref<QueueItem[]>([]);
|
||||
@@ -109,6 +129,7 @@ function reset(keepNetwork = false) {
|
||||
managedCredentials.value = null;
|
||||
if (!keepNetwork) settings.value.allowTurn = false;
|
||||
inputCode.value = outputCode.value = error.value = '';
|
||||
identityStatus.value = ''; canRemember.value = false; contactName.value = '';
|
||||
fps.value = incoming.value = null;
|
||||
verified.value = copied.value = choosing.value = false;
|
||||
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; streamedDownload.value = false;
|
||||
@@ -158,7 +179,13 @@ function attach(session: Session, channel: RTCDataChannel) {
|
||||
channel.close(); fail(session, new Error('Unexpected data channel.')); return;
|
||||
}
|
||||
session.transfer = new FileSession(channel, !!props.sending, {
|
||||
onReady: () => { if (active === session) { connected.value = true; step.value = 'session-ready'; clearTimeout(session.timer); } },
|
||||
onReady: () => { if (active === session) {
|
||||
connected.value = true; step.value = 'session-ready'; clearTimeout(session.timer);
|
||||
if (session.identityContext) {
|
||||
identityStatus.value = session.expected === session.remoteHello?.key ? 'Remembered device authenticated for this connection.' : 'Device proof checked. You can remember this manually verified device.';
|
||||
canRemember.value = !deviceState.value.contacts.some(contact => contact.key === session.remoteHello?.key);
|
||||
}
|
||||
} },
|
||||
onQueue: items => { if (active === session) queuedFiles.value = items; },
|
||||
onState: (direction, state, meta) => {
|
||||
if (active !== session) return;
|
||||
@@ -194,6 +221,7 @@ function attach(session: Session, channel: RTCDataChannel) {
|
||||
onError: err => fail(session, err),
|
||||
});
|
||||
if (props.sending) { session.transfer.add(selectedFiles.value); selectedFiles.value = []; file.value = null; }
|
||||
configureIdentity(session);
|
||||
if (verified.value) session.transfer.verify();
|
||||
}
|
||||
function start() {
|
||||
@@ -236,11 +264,19 @@ async function createCode() {
|
||||
validateMetadata({ name: file.value.name, size: file.value.size, mime: file.value.type || '' });
|
||||
}
|
||||
session = start();
|
||||
// Re-read saved trust for each connection; another tab may have forgotten
|
||||
// the expected peer or replaced the local identity since this page loaded.
|
||||
const device = await devices.value?.refreshForConnection();
|
||||
if (active !== session) return;
|
||||
if (device?.identity) {
|
||||
session.identity = device.identity; session.localHello = hello(device.identity); session.expected = device.expected;
|
||||
}
|
||||
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 options = { ...session.options, signal: session.controller.signal };
|
||||
if (!props.sending) { decodeSignal(pasted, session.options); session.remoteHello = signalIdentity(pasted); }
|
||||
const options = { ...session.options, signal: session.controller.signal, identity: session.localHello };
|
||||
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
|
||||
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
|
||||
if (active !== session) return;
|
||||
@@ -248,7 +284,7 @@ async function createCode() {
|
||||
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);
|
||||
if (!props.sending) { fps.value = getFingerprints(session.pc, options); configureIdentity(session); }
|
||||
step.value = props.sending ? 'offer-ready' : 'answer-ready';
|
||||
} catch (err) {
|
||||
if (session) fail(session, err);
|
||||
@@ -261,12 +297,15 @@ async function useAnswer() {
|
||||
error.value = '';
|
||||
step.value = 'verification';
|
||||
try {
|
||||
decodeSignal(inputCode.value, session.options);
|
||||
session.remoteHello = signalIdentity(inputCode.value);
|
||||
await acceptAnswerCode(session.pc, inputCode.value, 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);
|
||||
configureIdentity(session);
|
||||
} catch (err) {
|
||||
if (active !== session) return;
|
||||
// A rejected answer does not consume a valid local offer. Let the user
|
||||
@@ -277,6 +316,29 @@ async function useAnswer() {
|
||||
} else fail(session, err);
|
||||
}
|
||||
}
|
||||
function configureIdentity(session: Session) {
|
||||
if (!fps.value || !session.transfer || session.identityContext) return;
|
||||
if (!session.identity || !session.localHello || !session.remoteHello) {
|
||||
if (session.expected) identityStatus.value = 'Expected device identity is missing. Compare both fingerprints manually; saved trust is not being used.';
|
||||
else if (session.localHello || session.remoteHello) identityStatus.value = 'Both people must enable device identity to remember each other. Compare fingerprints manually for this connection.';
|
||||
return;
|
||||
}
|
||||
const initiator = !!props.sending;
|
||||
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 remembered device’s fresh proof…'; verify();
|
||||
} else {
|
||||
identityStatus.value = session.expected ? 'Device identity differs from the expected contact. Compare both fingerprints manually before continuing. The saved contact will not be replaced.' : 'New device. Compare both fingerprints manually before remembering it.';
|
||||
}
|
||||
}
|
||||
function verify() {
|
||||
if (!active || !fps.value || verified.value) return;
|
||||
verified.value = true; step.value = 'verification';
|
||||
@@ -349,6 +411,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<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" :disabled="busy || connected || savingContact" @change="deviceChange" />
|
||||
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
|
||||
<p class="status">Connection codes are not encrypted: they can reveal your IP address and connection details to anyone who sees them. Exchange them privately with your intended peer.</p>
|
||||
<template v-if="!sending">
|
||||
@@ -366,12 +429,18 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_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>
|
||||
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Fingerprints confirmed' : 'Both fingerprints match — confirm' }}</button>
|
||||
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Verification submitted' : 'Both fingerprints match — confirm' }}</button>
|
||||
</div>
|
||||
<div v-if="connected && canRemember">
|
||||
<label for="contact-name">Remember this device as</label>
|
||||
<input id="contact-name" v-model="contactName" maxlength="80" />
|
||||
<button :disabled="!contactName.trim() || savingContact" @click="saveContact">Remember device</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>
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
export interface Identity { publicKey: string; privateKey: CryptoKey }
|
||||
export interface IdentityHello { key: string; nonce: string }
|
||||
export interface Contact { key: string; name: string }
|
||||
export interface IdentityState { revision?: string; identity: Identity | null; contacts: Contact[] }
|
||||
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> {
|
||||
// Extractable for explicit password-encrypted backups. Stored as a CryptoKey,
|
||||
// never plaintext JSON. Same-origin JavaScript can still use/export this key.
|
||||
const pair = await crypto.subtle.generateKey(curve, true, ['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.');
|
||||
}
|
||||
export function validateContacts(value: unknown): Contact[] {
|
||||
if (!Array.isArray(value) || value.length > 100) throw new Error('Invalid contact list.');
|
||||
const keys = new Set<string>();
|
||||
return value.map(item => {
|
||||
if (!isRecord(item) || typeof item.name !== 'string' || !item.name.trim() || item.name.length > 80) throw new Error('Invalid contact name.');
|
||||
unhex(item.key, 65);
|
||||
const key = item.key as string;
|
||||
if (keys.has(key)) throw new Error('Duplicate contact identity.');
|
||||
keys.add(key); return { key, name: item.name.trim() };
|
||||
});
|
||||
}
|
||||
|
||||
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, contacts: [] };
|
||||
validateContacts(state.contacts);
|
||||
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. Reset it or restore a backup.');
|
||||
}
|
||||
return state;
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export async function saveIdentityState(state: IdentityState, expectedRevision = state.revision): Promise<IdentityState> {
|
||||
validateContacts(state.contacts);
|
||||
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(); }
|
||||
}
|
||||
const iterations = 600000;
|
||||
async function backupKey(password: string, salt: Uint8Array<ArrayBuffer>) {
|
||||
if (password.length < 12 || password.length > 1024) throw new Error('Use a backup password between 12 and 1024 characters.');
|
||||
const material = await crypto.subtle.importKey('raw', bytes(password), 'PBKDF2', false, ['deriveKey']);
|
||||
return crypto.subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
||||
}
|
||||
export async function exportBackup(state: IdentityState, password: string) {
|
||||
if (!state.identity) throw new Error('Create a device identity first.');
|
||||
const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const data = bytes(JSON.stringify({ key: await crypto.subtle.exportKey('jwk', state.identity.privateKey), publicKey: state.identity.publicKey, contacts: validateContacts(state.contacts) }));
|
||||
const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: bytes('HellCon backup v1') }, await backupKey(password, salt), data);
|
||||
return JSON.stringify({ format: 'hellcon-identity', version: 1, iterations, salt: hex(salt), iv: hex(iv), data: hex(encrypted) });
|
||||
}
|
||||
export async function importBackup(text: string, password: string): Promise<IdentityState> {
|
||||
if (text.length > 100000) throw new Error('Backup is too large.');
|
||||
try {
|
||||
const value: unknown = JSON.parse(text);
|
||||
if (!isRecord(value) || value.format !== 'hellcon-identity' || value.version !== 1 || value.iterations !== iterations || typeof value.data !== 'string' || value.data.length < 32) throw new Error();
|
||||
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unhex(value.iv, 12), additionalData: bytes('HellCon backup v1') }, await backupKey(password, unhex(value.salt, 16)), unhex(value.data, value.data.length / 2));
|
||||
const payload: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decrypted));
|
||||
if (!isRecord(payload) || !isRecord(payload.key)) throw new Error();
|
||||
const publicKey = payload.publicKey as string;
|
||||
const pub = await crypto.subtle.importKey('raw', unhex(publicKey, 65), curve, false, ['verify']);
|
||||
const privateKey = await crypto.subtle.importKey('jwk', payload.key, curve, true, ['sign']);
|
||||
const challenge = crypto.getRandomValues(new Uint8Array(32));
|
||||
if (!await crypto.subtle.verify(signing, pub, await crypto.subtle.sign(signing, privateKey, challenge), challenge)) throw new Error();
|
||||
return { identity: { publicKey, privateKey }, contacts: validateContacts(payload.contacts) };
|
||||
} catch { throw new Error('Could not restore backup. Check the password and backup file.'); }
|
||||
}
|
||||
+39
-5
@@ -14,6 +14,7 @@ export interface SessionCallbacks {
|
||||
onError(error: Error): void;
|
||||
onClose(): 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
|
||||
@@ -30,6 +31,10 @@ export class FileSession {
|
||||
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;
|
||||
@@ -38,17 +43,41 @@ export class FileSession {
|
||||
this.nextId = initiator ? 1 : 2;
|
||||
dc.binaryType = 'arraybuffer';
|
||||
dc.onopen = () => this.ready();
|
||||
dc.onmessage = event => { try { this.message(event.data); } catch (error) { this.fail(error); } };
|
||||
dc.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() {
|
||||
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; this.control({ type: 'ready' }); }
|
||||
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();
|
||||
}
|
||||
@@ -123,7 +152,7 @@ export class FileSession {
|
||||
}) };
|
||||
return item;
|
||||
}
|
||||
private message(data: unknown) {
|
||||
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.');
|
||||
@@ -134,7 +163,12 @@ export class FileSession {
|
||||
if (typeof data !== 'string' || data.length > 4096) throw new Error('Invalid session message.');
|
||||
const msg: unknown = JSON.parse(data);
|
||||
if (!isRecord(msg) || msg.v !== 3) throw new Error('Unsupported session protocol.');
|
||||
if (msg.type === 'ready' && !this.peerReady) { this.peerReady = true; this.ready(); return; }
|
||||
if (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 (typeof msg.id !== 'number' || !Number.isInteger(msg.id) || msg.id <= 0 || msg.id > 0xffffffff) throw new Error('Invalid file ID.');
|
||||
if (msg.type === 'start') {
|
||||
|
||||
+13
-6
@@ -1,3 +1,4 @@
|
||||
import { parseHello, type IdentityHello } from './identity.ts';
|
||||
import { asError, isRecord, isStringArray } from './validation.ts';
|
||||
|
||||
export interface IceOptions {
|
||||
@@ -20,7 +21,7 @@ export interface NetworkSettings {
|
||||
}
|
||||
|
||||
export interface WaitOptions { signal?: AbortSignal; timeout?: number }
|
||||
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'>;
|
||||
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'> & { identity?: IdentityHello };
|
||||
export interface Fingerprints { local: string; remote: string }
|
||||
export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>;
|
||||
export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>;
|
||||
@@ -131,8 +132,8 @@ export function getFingerprints(pc: { localDescription: { sdp: string } | null;
|
||||
};
|
||||
}
|
||||
|
||||
export function encodeSignal(sdp: string) {
|
||||
const code = btoa(JSON.stringify({ version: 3, sdp })).replace(/=+$/, '');
|
||||
export function encodeSignal(sdp: string, identity?: IdentityHello) {
|
||||
const code = btoa(JSON.stringify(identity ? { version: 4, sdp, identity: parseHello(identity) } : { version: 3, sdp })).replace(/=+$/, '');
|
||||
if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
|
||||
return code;
|
||||
}
|
||||
@@ -142,8 +143,9 @@ export function decodeSignal(text: unknown, options?: Pick<IceOptions, 'allowTur
|
||||
try {
|
||||
const clean = text.trim().replace(/\s+/g, '');
|
||||
const data: unknown = JSON.parse(atob(clean));
|
||||
if (!isRecord(data) || data.version !== 3) throw new Error('Both people need the current HellCon version.');
|
||||
if (!isRecord(data) || ![3, 4].includes(data.version as number)) throw new Error('Both people need the current HellCon version.');
|
||||
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
|
||||
if (data.version === 4) parseHello(data.identity);
|
||||
validateDescription(data.sdp, options);
|
||||
return data.sdp;
|
||||
} catch (err) {
|
||||
@@ -157,7 +159,7 @@ export async function createOfferCode(pc: RTCPeerConnection, options: SignalOpti
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return encodeSignal(pc.localDescription.sdp);
|
||||
return encodeSignal(pc.localDescription.sdp, options.identity);
|
||||
}
|
||||
|
||||
export async function createAnswerCode(pc: RTCPeerConnection, text: string, options: SignalOptions = {}) {
|
||||
@@ -166,7 +168,7 @@ export async function createAnswerCode(pc: RTCPeerConnection, text: string, opti
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return encodeSignal(pc.localDescription.sdp);
|
||||
return encodeSignal(pc.localDescription.sdp, options.identity);
|
||||
}
|
||||
|
||||
export function acceptAnswerCode(pc: RTCPeerConnection, text: string, options?: SignalOptions) {
|
||||
@@ -198,3 +200,8 @@ export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 6000
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
export function signalIdentity(text: string): IdentityHello | undefined {
|
||||
const data = JSON.parse(atob(text.trim().replace(/\s+/g, '')));
|
||||
return data.version === 4 ? parseHello(data.identity) : undefined;
|
||||
}
|
||||
@@ -294,3 +294,6 @@ p.stun-hint {
|
||||
|
||||
.transfer-section { display: flex; flex-direction: column; gap: 0.9rem; 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: 0.75rem; min-width: 0; border: 1px solid var(--border); border-radius: 8px; }
|
||||
.device-settings input:not([type=checkbox]), .device-settings select, #contact-name { box-sizing: border-box; max-width: 100%; padding: 0.6rem; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; }
|
||||
Reference in new issue
Block a user