WIP IV improve UX [snapshot task 2]

This commit is contained in:
Schluffe committed 2026-10-17 00:59:12 +02:00
1 parent 28c90d1d71
commit 58c3e2af86
16 files changed
+779 -36

No files matched your search

+5
View File
@@ -2,6 +2,11 @@
## Unreleased
- Add opt-in hosted device identities and saved contacts, with fresh mutual
signatures bound to both connection fingerprints before remembered verification.
- Add contact removal, identity reset, and password-encrypted backup/restore.
Identity-enabled signaling uses v4; temporary v3 sessions remain available.
- Keep verified sessions open for “Send another file”, with separate acceptance
and storage for each file.
- Preserve the previous memory download until the next file is accepted.
+30 -1
View File
@@ -22,6 +22,8 @@ explicit opt-in by both people; no relay is configured automatically.
Your fingerprint must equal their “Their fingerprint”, and vice versa.
Compare every byte. Cancel on any mismatch. Both people must explicitly
confirm before the app sends the filename, size, MIME metadata, or contents.
On later connections, a remembered device’s fresh proof can replace manual
comparison (see Remembered devices below).
4. The receiver sees the filename and size and explicitly accepts the file.
On the hosted app (HTTPS or localhost), **Receive as download** shows the incoming file size and streams into the browser's download manager using a same-origin service worker.
It requires transferable streams and service-worker support; Chromium and
@@ -60,7 +62,7 @@ Keep both tabs open. Switching browser tabs or apps does not explicitly cancel
the session, although browsers and mobile operating systems can suspend pages.
Pending verification/acceptance expires after five minutes; stalled transfers
expire after one minute. Idle verified sessions stay open. Lost connections need
fresh codes. Both peers must use protocol **v3**; older connection codes are
fresh codes. File transfers use protocol **v3**; pre-v3 connection codes are
rejected before connecting. The local HTML supports the same manual flow.
If an answer is rejected as invalid, correct the pasted answer and click Connect
@@ -93,6 +95,33 @@ ports plus a 20-second answer delay; it is **not a cross-device test**. Add
`--normal-candidates` to preserve the real candidate ports. No firewall changes,
TURN credentials or public STUN service are required.
## Remembered devices
On the hosted app, expand **Remembered devices** and choose **Create device
identity** on both browsers. Enable **Use my device identity for this connection**,
exchange codes, and compare both full fingerprints for the first pairing. Once
connected, give the peer a local nickname and choose **Remember device**.
For later connections, enable your identity and select the **Expected device**
on each side before exchanging fresh codes. HellCon checks fresh signed proofs
bound to both device keys and both connection fingerprints. A matching saved key
can replace manual fingerprint comparison; file acceptance is still required.
A changed or missing identity requires manual comparison and never overwrites a
saved contact. Nicknames stay local. Public identities in codes can link sessions.
Use **Forget** to remove a contact, or explicitly delete your identity and contacts.
Encrypted backup/restore includes both, protected by a password of at least 12
characters. Keep that password separately. Clearing site data loses saved trust;
restoring a backup on another browser gives it the same identity. Browser-stored
keys remain accessible to trusted app code and are not protection against a
malicious host. Identity use defaults off after reload. Storage failure leaves
temporary connections available; downloaded local HTML stays manual.
Identity-enabled codes use signaling version **4** and require the new build.
Temporary codes retain version **3**. If only one peer enables identity, the
current build uses manual comparison without remembering that connection.
See [the identity protocol and backup format](docs/device-identities.md).
## Network privacy and optional TURN
STUN discovers externally reachable addresses. Its operator can see your public
+20
View File
@@ -98,3 +98,23 @@ and current-without-immediate-cleanup all delivered the fixed probe at roughly
receiver did not report checking until the delayed answer was applied on the
sender, unlike the reported physical-device attempt. It does not reproduce that
attempt or establish that its answer-exchange timing is safe.
## Subsequent successful transfer report
The next supplied receiver/sender logs show a completed transfer. The receiver
created its answer at 0.1 s, sampled two in-progress pairs with no incoming checks
or responses through 12.0 s, then connected at 13.3 s. The sender applied the
answer at 40.3 s on its own clock and connected by 40.4 s. These are independent
time origins; the initial zero-response samples alone do not establish failure.
Both final snapshots show one selected, nominated, succeeded srflx/UDP to
srflx/UDP pair, with DTLS connected and no relay candidates. The receiver reports
download storage and transfer done at 36.9 s; the sender reports awaiting-receipt
followed by done at 64.0 s. This establishes successful direct connectivity and
application-level completion for this attempt. The user also confirmed that the downloaded file saved and opened correctly.
The supplied logs do not identify the browser, STUN provider, or whether any
network/setup settings changed. This success does not identify the cause of the
earlier failures or demonstrate a connectivity fix in the diagnostic changes.
The user identified the accompanying console warnings as stale and unrelated;
they are excluded from this result.
+90
View File
@@ -0,0 +1,90 @@
# Remembered-device protocol and storage
Phase 3 adds optional hosted-browser identities. Temporary sessions still use
manual fingerprint comparison. The local HTML never opens identity storage.
This is an application protocol design and implementation review, not an
independent cryptographic audit.
## Authentication transcript
A device has an ECDSA P-256 key pair. An identity-enabled connection code uses
signaling envelope version 4 with a public key (65-byte uncompressed point,
lowercase hex) and a fresh 32-byte cryptographically random nonce. Both local
and remote SDP fingerprints continue to be validated as full SHA-256 values.
Temporary codes use version 3. Old builds reject version 4 before connecting.
Current builds accept both; if either participant uses a temporary identity,
both must manually verify fingerprints and no device is remembered.
When both codes advertise identities, each FileSession ready frame includes an
ECDSA/SHA-256 signature. The signed UTF-8 bytes are JSON.stringify of this ordered
array, with no optional fields:
```
["HellCon device proof", 1, 4, role,
offerPublicKey, offerNonce, answerPublicKey, answerNonce,
offerFingerprint, answerFingerprint]
```
The role is `offerer` or `answerer`. Fingerprints are uppercase hex bytes separated
by one space. Signatures use Web Crypto's 64-byte P1363 encoding, lowercase hex.
The recipient verifies the other role with the other public key. Both keys,
both fresh nonces, and both DTLS certificate fingerprints are bound to the proof.
Roles and domain/version separation prevent reflection and cross-protocol use;
fresh contributions from both peers prevent replay into a new connection.
The signed fingerprints bind the identity to the encrypted transport. A proof
from another connection cannot authenticate an attacker-controlled DTLS peer.
A local user either compares both full fingerprints or explicitly selects an
expected saved public key. A nickname alone has no protocol meaning. A matching
expected key permits local verification to proceed automatically, but metadata
and file data stay gated until the peer's fresh signature verifies. Unknown,
changed, missing, or downgraded identities require manual fingerprint comparison.
A changed key never replaces a saved contact automatically. An invalid or missing
signature in a negotiated identity session closes the session. Each file still
requires acceptance. The session receive queue is bounded to 2 MiB while signature
verification is pending and throughout transfers; the existing 1 MiB send windows
remain unchanged.
Contacts may only be saved after both peers' ready frames pass verification.
Manual first pairing therefore authenticates the keys through the compared
transport fingerprints and proofs. Public identities in codes are linkable;
the UI makes this explicit before opt-in. No identities or nicknames are added
to diagnostic logs, and nicknames are not sent to peers.
## Storage and recovery
IndexedDB holds a CryptoKey private key, the public key, and at most 100 contacts.
Keys are extractable to support user-requested backups. Browser storage does not
protect against compromised app code, a hostile host, or compromised browser.
The identity-use checkbox defaults off after page load. Clearing site data loses
identity and contacts; an empty store never creates trust automatically. Storage
errors leave temporary sessions available. Unreadable storage can be explicitly
cleared before restoring a backup. Atomic revision checks reject stale writes
from other tabs instead of overwriting a newer identity or contact list. Controls for deletion/restoration
require explicit replacement consent and are disabled during a session.
Before each identity-enabled connection, settings are read again from storage.
A contact forgotten in another tab loses automatic verification on the next
connection; a replaced or deleted local identity requires opting in again.
A failed refresh stops setup instead of using cached trust.
The v1 backup is JSON containing `format: "hellcon-identity"`, `version: 1`,
`iterations: 600000`, a 16-byte random salt, 12-byte random IV, and ciphertext.
Salt, IV, and ciphertext use lowercase hex. PBKDF2-HMAC-SHA-256 with 600,000
iterations derives an AES-256-GCM key from the password (12–1024 characters,
UTF-8 without normalization). AES-GCM uses the default 128-bit authentication
tag and additional authenticated data `HellCon backup v1`. The encrypted JSON
contains the private JWK, public key, and contacts. Passwords are cleared from
the UI after operations and are never stored. Backup input is capped at 100 KB;
unsupported versions/iteration counts, malformed fields, wrong passwords, failed
authentication tags, invalid contacts, and mismatched private/public keys are
rejected before replacing stored data. Restoring a backup clones that identity;
there is no central revocation service. Contacts must forget a compromised key.
Review checks: both role directions, substitution of either identity, alteration
of either nonce or fingerprint, forged signatures, replay into fresh contexts,
metadata gating during asynchronous verification, backup tampering and incorrect
passwords, and persistence/reconnection with real browser CryptoKeys. These
checks do not replace an independent protocol review.
Web Crypto algorithm and key-storage reference:
https://www.w3.org/TR/WebCryptoAPI/
+18 -15
View File
@@ -45,24 +45,27 @@ queues, empty files, separate acceptance, removal, decline, stale IDs/receipts,
queue caps, storage cancellation, and verification gates. Browser checks exercise
both directions, real bytes, accessibility, streaming downloads, and the local HTML.
## 3. Remember trusted devices
## 3. Remember trusted devices — implemented
Add opt-in local device identity and a contact list on the hosted app, backed by
browser storage. After authenticated first pairing, offer “Remember this device”
and a local nickname. Store public identities for contacts and protect the local
private identity using available browser cryptographic storage; this does not
protect against compromised app JavaScript. Temporary sessions remain available.
The hosted app offers opt-in device identities and up to 100 named contacts in
browser storage. First pairing requires manual fingerprint comparison; contacts
can be saved only after successful mutual verification. Later connections can
select an expected saved public key and verify fresh signed proofs bound to both
keys, both nonces, both DTLS fingerprints, and participant roles. Nicknames and
saved codes never authenticate a peer. Changed or missing identities require
manual comparison and never replace saved contacts automatically.
Specify and review mutual proof of identity bound to fresh session information,
both DTLS fingerprints, participant roles, and replay protection before building
automatic verification. Never infer trust from a nickname or saved connection
code. Changed identities require explicit re-verification. Continue requiring
file acceptance. Add contact removal, identity reset, storage-unavailable behavior,
and password-encrypted identity export/import with a reviewed backup format.
Temporary sessions remain the default, and every file still requires acceptance.
Contact removal, identity deletion, encrypted backup/restore, storage failure
fallback, unreadable-storage recovery, and conflicting-tab write protection are
implemented. The local HTML remains manual. Identity-enabled signaling uses v4;
temporary connections retain v3. Browser keys remain accessible to app code.
Test impersonation, replay, identity changes, wrong backup passwords, storage
loss, and mixed-version peers. Local HTML may remain temporary/manual; do not
block delivery on persistent identity support for file URLs.
Tests cover proof forgery and replay, altered session bindings, metadata gating,
wrong backup passwords and tampering, persistence across reload, changed identities,
storage denial/recovery, and protocol-version validation. Design and review notes
are in [the device identity protocol](device-identities.md); this is not an
independent cryptographic audit.
## 4. Shareable invitations
+146 -1
View File
@@ -125,7 +125,7 @@ const enableTurn = (session: string) => evaluate(session, () => {
const checkbox = window.__hellcon.element<HTMLInputElement>('.checkbox input');
if (!checkbox.checked) checkbox.click();
});
async function connect(sender: string, receiver: string, size: number) {
async function connect(sender: string, receiver: string, size: number, changedIdentity = false) {
await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size);
await input(sender, '#stun-provider', provider);
await input(receiver, '#stun-provider', provider);
@@ -150,6 +150,7 @@ async function connect(sender: string, receiver: string, size: number) {
const rf = await evaluate(receiver, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
assert.equal(sf[0], rf[1]); assert.equal(sf[1], rf[0]); assert.equal(sf[0]?.split(' ').length, 32);
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
if (changedIdentity) assert.ok(await evaluate(sender, () => document.body.textContent?.includes('Device identity differs from the expected contact')));
await click(sender, 'Both fingerprints match — confirm');
await new Promise(resolve => setTimeout(resolve, 100));
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
@@ -324,6 +325,150 @@ try {
await click(receiver, 'Receive in memory (up to 64 MiB)');
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
if (!turn) {
const identitySender = await page();
const identityReceiver = await page(origin.replace('127.0.0.1', 'localhost'));
await click(identityReceiver, 'Receive');
for (const session of [identitySender, identityReceiver]) {
await evaluate(session, () => { const details = [...document.querySelectorAll('details')].find(el => el.querySelector('summary')?.textContent === 'Remembered devices'); if (details) details.open = true; });
await wait(session, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity' && !button.disabled));
await click(session, 'Create device identity');
await wait(session, () => document.querySelector<HTMLInputElement>('#use-device-identity')?.checked);
}
await connect(identitySender, identityReceiver, 2048);
for (const session of [identitySender, identityReceiver]) {
await wait(session, () => !!document.querySelector('#contact-name'));
await input(session, '#contact-name', 'Paired device');
await click(session, 'Remember device');
await wait(session, () => !document.querySelector('#contact-name'));
}
await checkAccessibility(identitySender, 'remembered identity');
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
await click(identitySender, 'Disconnect');
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reset'));
// Reload both pages to exercise persisted CryptoKeys and contacts.
for (const [session, url] of [[identitySender, origin], [identityReceiver, origin.replace('127.0.0.1', 'localhost')]]) {
await call('Page.navigate', { url }, session);
await wait(session, () => !!document.querySelector('#stun-provider'));
}
await click(identityReceiver, 'Receive');
for (const session of [identitySender, identityReceiver]) {
await wait(session, () => !!document.querySelector('#use-device-identity'));
assert.equal(await evaluate(session, () => document.querySelector<HTMLInputElement>('#use-device-identity')!.checked), false, 'Reload defaults to a temporary connection');
await evaluate(session, () => document.querySelector<HTMLInputElement>('#use-device-identity')!.click());
const key = await evaluate(session, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options[1]!.value);
await input(session, '#expected-device', key);
await input(session, '#stun-provider', 'none');
}
await evaluate(identitySender, () => window.__hellcon.chooseFile(4096, 'remembered.bin'));
await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code'));
const offer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.equal(JSON.parse(atob(offer)).version, 4);
await input(identityReceiver, '#offer-input', offer); await click(identityReceiver, 'Accept & create answer');
await wait(identityReceiver, () => !!document.querySelector('#output-code'));
const answer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
await input(identitySender, '#answer-input', answer); await click(identitySender, 'Connect');
await wait(identityReceiver, () => !!document.querySelector('.incoming'));
for (const session of [identitySender, identityReceiver]) assert.ok(await evaluate(session, () => document.body.textContent?.includes('Remembered device authenticated')));
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
const rememberedBytes = await evaluate(identityReceiver, async () => { const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer()); return { length: bytes.length, valid: bytes.every(byte => byte === 123) }; });
assert.deepEqual(rememberedBytes, { length: 4096, valid: true });
console.log('PASS: identities and contacts persist across reload; fresh mutual proofs authenticate remembered devices and transfer exact bytes without manual reconfirmation.');
await click(identitySender, 'Disconnect');
await wait(identityReceiver, () => !document.querySelector('.incoming'));
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
for (const forgottenSide of [identitySender, identityReceiver]) {
const editor = await page(forgottenSide === identitySender ? origin : origin.replace('127.0.0.1', 'localhost'));
await wait(editor, () => !!document.querySelector('#expected-device'));
await click(editor, 'Forget');
await wait(editor, () => document.querySelector<HTMLSelectElement>('#expected-device')?.options.length === 1);
assert.ok(await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.value), 'Original tab still has the stale expected contact before connection setup');
await evaluate(identitySender, () => window.__hellcon.chooseFile(128, 'forgotten-contact.bin'));
await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code'));
const freshOffer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
await input(identityReceiver, '#offer-input', freshOffer); await click(identityReceiver, 'Accept & create answer');
await wait(identityReceiver, () => !!document.querySelector('#output-code'));
const freshAnswer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
await input(identitySender, '#answer-input', freshAnswer); await click(identitySender, 'Connect');
await wait(forgottenSide, () => document.body.textContent?.includes('New device. Compare both fingerprints manually'));
assert.equal(await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.value), '');
assert.equal(await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options.length), 1);
assert.equal(await evaluate(identityReceiver, () => !!document.querySelector('.incoming')), false, 'Forgotten trust must not release file metadata');
await click(forgottenSide, 'Both fingerprints match — confirm');
await wait(identityReceiver, () => !!document.querySelector('.incoming'));
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
await input(forgottenSide, '#contact-name', 'Paired device'); await click(forgottenSide, 'Remember device');
await wait(forgottenSide, () => !document.querySelector('#contact-name'));
await click(identitySender, 'Disconnect');
await wait(identityReceiver, () => !document.querySelector('.incoming'));
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
const key = await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options[1]!.value);
await input(forgottenSide, '#expected-device', key);
}
console.log('PASS: forgetting a device in another tab removes stale trust before either role reconnects; manual confirmation gates metadata and permits pairing again.');
await evaluate(identitySender, () => { indexedDB.open = () => { throw new DOMException('Storage denied during refresh', 'SecurityError'); }; });
await evaluate(identitySender, () => window.__hellcon.chooseFile(1, 'storage-failure.bin'));
await click(identitySender, 'Create code');
await wait(identitySender, () => document.body.textContent?.includes('Storage denied during refresh'));
assert.equal(await evaluate(identitySender, () => !!document.querySelector('#output-code')), false, 'Failed storage refresh must not use cached trust');
await evaluate(identitySender, () => { Reflect.deleteProperty(indexedDB, 'open'); });
await click(identitySender, 'Reset');
console.log('PASS: unreadable storage during connection setup cannot reuse a cached identity or contact.');
await evaluate(identityReceiver, () => {
const label = [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Replace or delete'));
label?.querySelector<HTMLInputElement>('input')?.click();
});
await click(identityReceiver, 'Delete identity and contacts');
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity'));
await click(identityReceiver, 'Create device identity');
await wait(identityReceiver, () => document.querySelector<HTMLInputElement>('#use-device-identity')?.checked);
await connect(identitySender, identityReceiver, 512, true);
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
assert.equal(await evaluate(identitySender, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options.length), 2, 'Changed identity must not replace or append saved contacts automatically');
console.log('PASS: replaced peer identity requires manual comparison and preserves the original saved contact.');
const stale = await page();
await wait(stale, () => !!document.querySelector('#use-device-identity'));
await evaluate(stale, async () => {
const db = await new Promise<IDBDatabase>((resolve, reject) => { const request = indexedDB.open('hellcon-devices', 1); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });
await new Promise<void>((resolve, reject) => {
const tx = db.transaction('settings', 'readwrite'), store = tx.objectStore('settings'), request = store.get('state');
request.onsuccess = () => store.put({ ...request.result, revision: crypto.randomUUID() }, 'state');
tx.oncomplete = () => resolve(); tx.onabort = () => reject(tx.error);
}); db.close();
});
await click(stale, 'Forget');
await wait(stale, () => document.body.textContent?.includes('Device settings changed in another tab'));
await evaluate(stale, async () => {
const db = await new Promise<IDBDatabase>(resolve => { const request = indexedDB.open('hellcon-devices', 1); request.onsuccess = () => resolve(request.result); });
await new Promise<void>(resolve => { const tx = db.transaction('settings', 'readwrite'); tx.objectStore('settings').put({ identity: null, contacts: 'broken', revision: 'broken' }, 'state'); tx.oncomplete = () => resolve(); }); db.close();
});
await call('Page.navigate', { url: origin }, stale);
await wait(stale, () => document.body.textContent?.includes('Invalid contact list'));
await evaluate(stale, () => [...document.querySelectorAll('label')].find(label => label.textContent?.includes('Delete unreadable device storage'))?.querySelector<HTMLInputElement>('input')?.click());
await click(stale, 'Clear device storage');
await wait(stale, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity' && !button.disabled));
console.log('PASS: stale contact edits cannot overwrite newer settings; unreadable storage can be cleared with explicit consent.');
const denied = await page();
await call('Page.addScriptToEvaluateOnNewDocument', { source: "indexedDB.open = () => { throw new DOMException('Storage denied', 'SecurityError'); };" }, denied);
await call('Page.navigate', { url: origin }, denied);
await wait(denied, () => document.body.textContent?.includes('Storage denied'));
await evaluate(denied, () => window.__hellcon.chooseFile(1, 'temporary.bin'));
await input(denied, '#stun-provider', 'none'); await click(denied, 'Create code');
await wait(denied, () => !!document.querySelector('#output-code'));
const temporary = await evaluate(denied, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.equal(JSON.parse(atob(temporary)).version, 3);
await click(denied, 'Cancel connection');
console.log('PASS: denied identity storage still allows temporary v3 connection setup.');
}
if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`);
assert.deepEqual(browserErrors, []);
}
+1 -1
View File
@@ -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.
+108
View File
@@ -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>
+75 -6
View File
@@ -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>
+141
View File
@@ -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
View File
@@ -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
View File
@@ -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;
}
+3
View File
@@ -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; }
+49
View File
@@ -0,0 +1,49 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createIdentity, hello, signIdentity, verifyIdentity, exportBackup, importBackup, parseHello, validateContacts, type IdentityContext } from '../src/lib/identity.ts';
const fingerprint = (byte: string) => Array(32).fill(byte).join(' ');
async function setup() {
const first = await createIdentity(), second = await createIdentity();
const context: IdentityContext = { offer: hello(first), answer: hello(second), offerFingerprint: fingerprint('AA'), answerFingerprint: fingerprint('BB') };
return { first, second, context };
}
test('device proof binds both keys, fresh nonces, roles, and both DTLS fingerprints', async () => {
const { first, second, context } = await setup();
const proof = await signIdentity(first, context, true);
await verifyIdentity(proof, context, true);
await verifyIdentity(await signIdentity(second, context, false), context, false);
await assert.rejects(verifyIdentity(proof, context, false));
for (const changed of [
{ ...context, offer: hello(first) }, { ...context, answer: hello(second) },
{ ...context, offer: hello(second) }, { ...context, answer: hello(first) },
{ ...context, offerFingerprint: fingerprint('CC') }, { ...context, answerFingerprint: fingerprint('CC') },
]) await assert.rejects(verifyIdentity(proof, changed, true));
const imposter = await createIdentity();
await assert.rejects(signIdentity(imposter, context, true));
await assert.rejects(verifyIdentity('00'.repeat(64), context, true));
});
test('identity input is bounded and contacts cannot supply duplicate identities', async () => {
const identity = await createIdentity();
assert.throws(() => parseHello({ key: identity.publicKey, nonce: 'bad' }));
assert.throws(() => parseHello({ key: 'ff'.repeat(65), nonce: '00'.repeat(32) }));
assert.throws(() => validateContacts([{ key: identity.publicKey, name: ' ' }]));
assert.throws(() => validateContacts(Array(101).fill({ key: identity.publicKey, name: 'friend' })));
assert.throws(() => validateContacts(Array(2).fill({ key: identity.publicKey, name: 'friend' })));
});
test('encrypted backup restores signing identity and contacts; wrong password and tampering fail', async () => {
const { first, second, context } = await setup();
const state = { identity: first, contacts: [{ key: second.publicKey, name: 'Other device' }] };
const password = 'a long private backup passphrase';
const backup = await exportBackup(state, password);
assert.doesNotMatch(backup, /Other device|privateKey/);
const restored = await importBackup(backup, password);
assert.deepEqual(restored.contacts, state.contacts);
assert.equal(restored.identity!.publicKey, first.publicKey);
await verifyIdentity(await signIdentity(restored.identity!, context, true), context, true);
await assert.rejects(importBackup(backup, 'the incorrect password'));
const damaged = JSON.parse(backup); damaged.data = (damaged.data.startsWith('00') ? 'ff' : '00') + damaged.data.slice(2);
await assert.rejects(importBackup(JSON.stringify(damaged), password));
damaged.iterations = 1; await assert.rejects(importBackup(JSON.stringify(damaged), password));
await assert.rejects(importBackup('x'.repeat(100001), password));
await assert.rejects(exportBackup(state, 'short'));
});
+26
View File
@@ -108,6 +108,7 @@ test('reused file IDs and stale receipts fail closed', async t => {
await until(() => first.state.results.length === 1);
const target = stale === 'start' ? second : first;
target.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: stale, id: 1, data: JSON.stringify({ v: 2, type: 'complete', bytes: 0 }) }) }));
await until(() => target.state.closed);
assert.equal(target.state.closed, true); assert.equal(target.state.errors.length, 1);
}
});
@@ -116,5 +117,30 @@ test('unsolicited offers before verification and excess binary payload fail clos
const { first, second } = pair(t);
first.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: 'start', id: 2 }) }));
second.channel.onmessage?.(new MessageEvent('message', { data: new ArrayBuffer(100000) }));
await until(() => first.state.closed && second.state.closed);
assert.equal(first.state.closed, true); assert.equal(second.state.closed, true);
});
test('identity proofs gate metadata even when a remembered contact requests automatic verification', async t => {
const { first, second } = pair(t);
let release!: () => void;
const pending = new Promise<void>(resolve => { release = resolve; });
first.session.authenticate({ sign: async () => 'sender-proof', verify: async proof => { assert.equal(proof, 'receiver-proof'); await pending; } });
second.session.authenticate({ sign: async () => 'receiver-proof', verify: async proof => { assert.equal(proof, 'sender-proof'); await pending; } });
first.session.add([file('private-name')]); first.session.verify(); second.session.verify();
await tick();
assert.equal(first.state.ready, false); assert.equal(second.state.ready, false);
assert.doesNotMatch(first.channel.frames.join(''), /private-name/);
release(); await until(() => second.state.receive === 'choose-storage');
second.session.accept(); await until(() => first.state.results.length === 1);
assert.deepEqual(first.state.errors, []); assert.deepEqual(second.state.errors, []);
});
test('invalid or missing identity proof closes the session without releasing file metadata', async t => {
const { first, second } = pair(t);
first.session.authenticate({ sign: async () => 'proof', verify: async () => { throw new Error('Device proof failed'); } });
first.session.add([file('private-name')]); first.session.verify(); second.session.verify();
await until(() => first.state.closed);
assert.match(first.state.errors.join(''), /Device proof failed/);
assert.doesNotMatch(first.channel.frames.join(''), /private-name/);
});
+15 -1
View File
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { iceConfiguration, validateDescription, getFingerprints, encodeSignal, decodeSignal, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.ts';
import { iceConfiguration, validateDescription, getFingerprints, signalIdentity, encodeSignal, decodeSignal, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.ts';
const fingerprint = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(':');
const sdp = `v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 ${fingerprint}\r\n`;
@@ -62,3 +62,17 @@ test('buffer wait resolves when already drained and rejects close or cancellatio
const cancelled = waitForBufferDrain(channel, { signal: controller.signal }); controller.abort();
await assert.rejects(cancelled, /interrupted/);
});
test('identity signaling is versioned, bounded, and optional for temporary sessions', () => {
const identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) };
const code = encodeSignal(sdp, identity);
assert.equal(JSON.parse(atob(code)).version, 4);
assert.equal(decodeSignal(code), sdp);
assert.deepEqual(signalIdentity(code), identity);
assert.equal(signalIdentity(encodeSignal(sdp)), undefined);
assert.equal(JSON.parse(atob(encodeSignal(sdp))).version, 3);
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 4, sdp }))));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 4, sdp, identity: { ...identity, nonce: 'bad' } }))));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 5, sdp, identity }))));
});