WIP V improve UX [snapshot task 2]

This commit is contained in:
Schluffe committed 2026-10-17 14:51:48 +02:00
1 parent 5f8c6a1916
commit a73b3075b6
16 files changed
+238 -232

No files matched your search

+5
View File
@@ -25,6 +25,11 @@
### Changed
- Each connection now remembers its own device instead of picking from a global
contact list. Opt in per connection; after manual fingerprint comparison,
“Remember this device for …” (ticked by default) pairs the verified peer.
A changed key is only replaced on explicit choice. Saved contacts are no
longer read.
- Upgrade connection/session framing to v3 with per-file identifiers. Both peers
must update; v2 codes are rejected before connection setup.
- New device identity private keys are non-extractable.
+23 -20
View File
@@ -14,13 +14,13 @@ The sidebar holds your connections, starting with **Con 1**. Use **Add connectio
for another empty slot. Edit the name directly in the header; it saves when you
leave the field or press Enter. Empty names revert to the previous name.
Use **Remove** beside the name to open a confirmation dialog. Confirming removal
ends that slot's sessions in open tabs; downloaded files and saved device identities
remain. Removing the last slot leaves a fresh **Con 1**.
ends that slot's sessions in open tabs and forgets its remembered device;
downloaded files and your device identity remain. Removing the last slot leaves a fresh **Con 1**.
Each slot has its own setup, live session, and activity timeline. Switching slots
keeps active transfers and selected files alive while this tab stays open.
On small screens, **Show connections** opens the sidebar.
Connection names, associated remembered devices, and the last 50 transfer results
Connection names, remembered devices, and the last 50 transfer results
per slot are saved in this browser. History includes filenames, sizes, directions,
times, and completion/decline/interruption results. It does not save file contents,
connection codes, or relay credentials. **Reset** clears the current session but
@@ -28,10 +28,12 @@ keeps the slot and history. Closing or reloading the page ends live sessions and
discards selected files; reconnect by exchanging fresh codes. The sidebar reports
this tab's session status, not remote device presence.
Remembering a verified device associates it with the current slot. On returning,
that device is preselected if it is still trusted; enable your identity before
exchanging fresh codes to use remembered verification. Existing saved contacts
remain available in **Remembered devices**. Clearing site data removes saved
Each slot can remember one device. Under **Remembered device**, create the
browser's device identity once, then opt each slot in. After the first manual
fingerprint comparison, **Remember this device for …** (ticked by default) pairs
the verified peer with that slot; later sessions on it authenticate the peer
automatically. The slot name is the device's name. **Forget device** unpairs it.
The same device may be paired with several slots. Clearing site data removes saved
connections and trust. Storage failures are shown explicitly; temporary sessions
remain available. Up to 100 connection slots are supported.
@@ -124,23 +126,24 @@ 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**.
On the hosted app, expand **Remembered device** and choose **Create device
identity** on both browsers; this also enables **Use my device identity on this
connection** for the current slot. Exchange codes and compare both full
fingerprints for the first pairing. Leave **Remember this device for …** ticked
before confirming, and the verified peer is paired with this connection.
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.
Later sessions on that connection need no extra steps: HellCon checks fresh
signed proofs bound to both device keys and both connection fingerprints. A
matching paired key replaces manual fingerprint comparison; file acceptance is
still required. A changed or missing identity requires manual comparison and
only replaces the paired device if you tick **Replace the paired device**.
Connection names stay local. Public identities in codes can link sessions.
Use **Forget** to remove a contact, or explicitly delete your identity and contacts.
Use **Forget device** to unpair a connection, or explicitly delete your identity.
Clearing site data loses saved trust and requires pairing again. Browser-stored
keys remain usable by trusted app code and are not protection against a malicious
host. Identity use defaults off after reload. Storage failure leaves temporary
connections available.
host. Each connection keeps its own opt-in; new connections start without it.
Storage failure leaves temporary connections available.
Identity-enabled codes use signaling version **4** and require the new build.
Temporary codes retain version **3**. If only one peer enables identity, the
+30 -24
View File
@@ -34,42 +34,48 @@ 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
Each connection opts in separately and trusts at most one public key, its paired
device. A local user either compares both full fingerprints or connects on a
paired connection. A connection name has no protocol meaning. A matching paired
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 paired device automatically: replacing it is an
explicit, unticked choice on the verification step. 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.
A peer key is only saved to a connection after both peers' ready frames pass
verification, and only if the user left **Remember this device** ticked on the
verification step. 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 connection
names are added to diagnostic logs, and connection names are not sent to peers.
## Storage and recovery
IndexedDB holds a CryptoKey private key, the public key, and at most 100 contacts.
New private keys are non-extractable; existing stored keys remain usable.
The `hellcon-devices` IndexedDB store holds one CryptoKey private key and its
public key, shared by all connections. Each record in `hellcon-connections`
holds its own opt-in flag and paired public key. New private keys are
non-extractable; existing stored keys remain usable.
Browser storage does not protect against compromised app code, a hostile host,
or compromised browser: app code can still use a stored key to sign.
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 creating a new identity and pairing again. Atomic revision checks
reject stale writes from other tabs instead of overwriting a newer identity or
contact list. Identity deletion requires explicit consent and is 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.
New connections are not opted in. Creating an identity opts in the connection it
was created from. Clearing site data loses the identity and pairings; an empty
store never creates trust automatically. Storage errors leave temporary sessions
available. Unreadable identity storage can be explicitly cleared before creating
a new identity and pairing again. Atomic revision checks reject stale identity
writes from other tabs; connection records are read and written in single
transactions. Identity deletion requires explicit consent, keeps paired devices,
and is disabled during a session. Removing a connection forgets its device.
Before each identity-enabled connection, the connection record and identity are
read again from storage. A device forgotten in another tab loses automatic
verification on the next connection, and a replaced local identity is picked up.
A failed refresh stops setup instead of using cached trust.
There is no central revocation service. Contacts must forget a compromised key.
There is no central revocation service. Peers 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,
+11 -11
View File
@@ -11,15 +11,15 @@ its setup, transfer controls, and persistent activity timeline. Cached workspace
keep live sessions and file selections intact while navigating between slots.
The sidebar collapses on mobile; network configuration is expandable.
IndexedDB stores slot names, paired-device associations, and up to 50 transfer
IndexedDB stores slot names, paired devices, and up to 50 transfer
results per slot. Each result includes its direction, filename, size, timestamp,
and completion/decline/interruption status. File contents and connection codes
are never stored. Slot mutations are transactional and other tabs refresh their
lists after changes. Storage failures show an explicit warning.
Disconnect and Reset retain history. Reloading ends live sessions and requires
fresh codes; saved identities can authenticate a remembered peer. A slot's device
association only preselects an existing trusted contact and does not grant trust.
fresh codes; a slot's paired device is authenticated by fresh signed proofs, and
setup re-reads it from storage so a device forgotten elsewhere is not trusted.
## 1. Send another file on a verified connection — implemented first
@@ -63,16 +63,16 @@ both directions, real bytes, accessibility, and streaming downloads.
## 3. Remember trusted devices — implemented
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.
The hosted app offers an opt-in device identity, and each connection slot can
remember one paired device. First pairing requires manual fingerprint comparison;
a slot is paired only after successful mutual verification. Later sessions on a
paired slot verify fresh signed proofs bound to both keys, both nonces, both DTLS
fingerprints, and participant roles. Slot names and saved codes never
authenticate a peer. Changed or missing identities require manual comparison and
never replace a paired device automatically.
Temporary sessions remain the default, and every file still requires acceptance.
Contact removal, identity deletion, storage failure
Forgetting devices, identity deletion, storage failure
fallback, unreadable-storage recovery, and conflicting-tab write protection are
implemented. Identity-enabled signaling uses v4;
temporary connections retain v3. Browser keys remain accessible to app code.
+63 -46
View File
@@ -159,11 +159,19 @@ async function connect(sender: string, receiver: string, size: number, changedId
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);
await click(receiver, 'Both fingerprints match — confirm');
if (changedIdentity) {
// The receiver still trusts the unchanged sender and verifies automatically;
// the sender must compare manually and is not offered a silent replacement.
assert.ok(await evaluate(sender, () => document.body.textContent?.includes('Device identity differs from the paired device')));
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.fingerprint label')].find(el => el.textContent?.includes('Replace the paired device'))?.querySelector('input')?.checked), false);
await wait(receiver, () => document.body.textContent?.includes('Verification submitted'));
await click(sender, 'Both fingerprints match — confirm');
} else {
await click(sender, 'Both fingerprints match — confirm');
await new Promise(resolve => setTimeout(resolve, 100));
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
await click(receiver, 'Both fingerprints match — confirm');
}
await wait(receiver, () => !!document.querySelector('.incoming'));
if (turn) {
for (const session of [sender, receiver]) {
@@ -457,39 +465,44 @@ try {
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'));
const receiverOrigin = origin.replace('127.0.0.1', 'localhost');
const identityReceiver = await page(receiverOrigin);
await click(identityReceiver, 'Receive');
const pairedKey = (session: string) => evaluate(session, () => document.querySelector('.device-settings code')?.textContent || '');
// Clears the paired device directly in storage, so this tab is not notified.
const forgetQuietly = (session: string) => evaluate(session, async () => {
const db = await new Promise<IDBDatabase>((resolve, reject) => { const request = indexedDB.open('hellcon-connections', 1); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });
await new Promise<void>((resolve, reject) => {
const tx = db.transaction('connections', 'readwrite'), store = tx.objectStore('connections'), request = store.getAll();
request.onsuccess = () => { for (const record of request.result) store.put({ ...record, peerKey: '' }); };
tx.oncomplete = () => resolve(); tx.onabort = () => reject(tx.error);
}); db.close();
});
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 evaluate(session, () => { const details = [...document.querySelectorAll('details')].find(el => el.querySelector('summary')?.textContent === 'Remembered device'); 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 wait(session, () => document.querySelector<HTMLInputElement>('#remember-device')?.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 wait(session, () => document.body.textContent?.includes('Remembered for Con 1'));
await wait(session, () => !!document.querySelector('.device-settings code'));
}
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')]]) {
// Reload both pages to exercise persisted CryptoKeys and paired connections.
for (const [session, url] of [[identitySender, origin], [identityReceiver, receiverOrigin]]) {
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);
assert.equal(await evaluate(session, () => document.querySelector<HTMLSelectElement>('#expected-device')!.value), key, 'The slot preselects its saved trusted peer after reload');
await input(session, '#expected-device', key);
await wait(session, () => !!document.querySelector('.device-settings code'));
assert.equal(await evaluate(session, () => !!document.querySelector('#remember-device')), false, 'A paired connection shows its device instead of the opt-in');
await input(session, '#stun-provider', 'none');
}
await evaluate(identitySender, () => window.__hellcon.chooseFile(4096, 'remembered.bin'));
@@ -501,24 +514,21 @@ try {
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')));
for (const session of [identitySender, identityReceiver]) assert.ok(await evaluate(session, () => document.body.textContent?.includes('Paired 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.');
console.log('PASS: identities and paired connections persist across reload; fresh mutual proofs authenticate the paired device 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 forgetQuietly(forgottenSide);
assert.ok(await pairedKey(forgottenSide), 'Original tab still shows the stale paired device before connection setup');
await evaluate(identitySender, () => window.__hellcon.chooseFile(128, 'forgotten-contact.bin'));
await evaluate(identitySender, () => window.__hellcon.chooseFile(128, 'forgotten-device.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');
@@ -526,22 +536,19 @@ try {
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 pairedKey(forgottenSide), '', 'Connection setup re-reads the forgotten pairing');
assert.equal(await evaluate(forgottenSide, () => [...document.querySelectorAll('.fingerprint label')].find(el => el.textContent?.includes('Remember this device for Con 1'))?.querySelector('input')?.checked), true);
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 wait(forgottenSide, () => !!document.querySelector('.device-settings code'));
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.');
console.log('PASS: forgetting a device in another tab removes stale trust before either role reconnects; manual confirmation gates metadata and pairs the connection again.');
await evaluate(identitySender, () => { indexedDB.open = () => { throw new DOMException('Storage denied during refresh', 'SecurityError'); }; });
await evaluate(identitySender, () => window.__hellcon.chooseFile(1, 'storage-failure.bin'));
@@ -550,23 +557,32 @@ try {
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.');
console.log('PASS: unreadable storage during connection setup cannot reuse a cached identity or paired device.');
const senderPaired = await pairedKey(identitySender);
await evaluate(identityReceiver, () => {
const label = [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Delete this browser’s identity'));
const label = [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Delete this browser’s device identity'));
label?.querySelector<HTMLInputElement>('input')?.click();
});
await click(identityReceiver, 'Delete identity and contacts');
await click(identityReceiver, 'Delete device identity');
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 wait(identityReceiver, () => !!document.querySelector('.device-settings code'));
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.');
assert.ok(await evaluate(identitySender, () => document.body.textContent?.includes('This device was not remembered.')));
assert.equal(await pairedKey(identitySender), senderPaired, 'Changed identity must not replace the paired device automatically');
console.log('PASS: replaced peer identity requires manual comparison and preserves the paired device.');
await click(identitySender, 'Disconnect');
await wait(identityReceiver, () => !document.querySelector('.incoming'));
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
const stale = await page();
await wait(stale, () => !!document.querySelector('#use-device-identity'));
await wait(stale, () => !!document.querySelector('.device-settings code'));
await click(stale, 'Forget device');
await wait(stale, () => document.querySelector<HTMLInputElement>('#remember-device')?.checked);
await wait(identitySender, () => document.querySelector<HTMLInputElement>('#remember-device')?.checked);
console.log('PASS: Forget device keeps the per-connection opt-in and reaches other tabs.');
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) => {
@@ -575,18 +591,19 @@ try {
tx.oncomplete = () => resolve(); tx.onabort = () => reject(tx.error);
}); db.close();
});
await click(stale, 'Forget');
await evaluate(stale, () => [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Delete this browser’s device identity'))?.querySelector<HTMLInputElement>('input')?.click());
await click(stale, 'Delete device identity');
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 new Promise<void>(resolve => { const tx = db.transaction('settings', 'readwrite'); tx.objectStore('settings').put({ identity: { publicKey: '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 wait(stale, () => document.body.textContent?.includes('Invalid device identity'));
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.');
console.log('PASS: stale identity 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);
+14 -5
View File
@@ -81,7 +81,16 @@ function update(id: string, change: ConnectionUpdate) {
});
}
function record(id: string, activity: ConnectionActivity) { update(id, { activity }); }
function pair(id: string, peerKey: string) { update(id, { peerKey }); }
// Connection setup re-reads the record so trust forgotten in another tab is
// never reused from this tab's copy. A failed read stops setup.
async function trust(id: string) {
await writes;
const records = persistent ? await loadConnections() : connections.value;
const record = records.find(item => item.id === id);
if (!record) throw new Error('This connection is no longer saved. Reload the page.');
if (persistent && !pending && !removing.value) applyRecords(records);
return record;
}
async function remove() {
if (!current.value || removing.value || adding.value) return;
const id = current.value.id;
@@ -120,7 +129,7 @@ async function remove() {
<p>No accounts. Your connections stay on this device.</p>
<details class="privacy-details">
<summary>About privacy &amp; connections</summary>
<p>Files travel over encrypted WebRTC data channels. Compare full fingerprints on first pairing, or authenticate a remembered device. Reconnect by exchanging fresh codes.</p>
<p>Files travel over encrypted WebRTC data channels. Compare full fingerprints on first pairing, or let a connection authenticate its remembered device. Reconnect by exchanging fresh codes.</p>
<p>Trust your browser and the app’s host: its code can read selected files and use your device identity. HTTPS protects delivery. A TURN relay is used only after opt-in.</p>
<p>Clearing site data removes saved connections, identities, and history.</p>
</details>
@@ -135,7 +144,7 @@ async function remove() {
<div class="title-line">
<h1 ref="heading" class="sr-only" tabindex="-1">{{ current.name }}</h1>
<EditableName :key="current.id" :name="current.name" :disabled="removing" @rename="update(current!.id, { name: $event })" />
<button class="header-action" :disabled="adding || removing" @click="removalError = ''; confirmingRemoval = true">Remove</button>
<button class="header-action" :disabled="adding || removing" @click="removalError = ''; confirmingRemoval = true"><span class="header-action-icon" aria-hidden="true">✕</span> Remove</button>
</div>
</div>
<span class="session-badge" :class="states[current.id] || 'ready'"><span class="connection-dot" :class="states[current.id] || 'ready'" aria-hidden="true"></span>{{ statusLabel(current.id) }}</span>
@@ -145,7 +154,7 @@ async function remove() {
<p v-if="error" class="storage-error" role="alert">{{ error }}</p>
<template v-for="item in connections" :key="item.id">
<KeepAlive>
<ConnectionWorkspace v-if="selected === item.id" :connection="item" @status="setStatus" @activity="record" @paired="pair" />
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" @status="setStatus" @activity="record" @update="update" />
</KeepAlive>
</template>
<p v-if="!current" class="status">Opening your connections…</p>
@@ -153,7 +162,7 @@ async function remove() {
</main>
</div>
<AppDialog v-model="confirmingRemoval" :title="`Remove ${current?.name || 'connection'}?`" :busy="removing">
<p>This ends its session and deletes its saved activity. Saved files and device identities are kept.</p>
<p>This ends its session and deletes its saved activity and remembered device. Saved files and your device identity are kept.</p>
<p v-if="connections.length === 1">A fresh Con 1 will replace your last connection.</p>
<p v-if="removalError" class="error" role="alert">{{ removalError }}</p>
<template #actions="{ close }">
+5 -5
View File
@@ -1,12 +1,12 @@
<script setup lang="ts">
import { ref } from 'vue';
import TransferPanel from './TransferPanel.vue';
import type { SavedConnection, ConnectionActivity } from '../lib/connections.ts';
const props = defineProps<{ connection: SavedConnection }>();
import type { SavedConnection, ConnectionActivity, ConnectionUpdate } from '../lib/connections.ts';
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection> }>();
const emit = defineEmits<{
status: [id: string, state: 'ready' | 'connecting' | 'connected'];
activity: [id: string, item: ConnectionActivity];
paired: [id: string, key: string];
update: [id: string, change: ConnectionUpdate];
}>();
const mode = ref<'send' | 'receive'>('send');
const sessionActive = ref(false), connected = ref(false);
@@ -35,9 +35,9 @@ function sizeLabel(size: number) {
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'send' }" :aria-pressed="(connected ? direction : mode) === 'send'" @click="navigate('send')">Send</button>
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'receive' }" :aria-pressed="(connected ? direction : mode) === 'receive'" @click="navigate('receive')">Receive</button>
</div>
<TransferPanel ref="panel" :key="mode" :sending="mode === 'send'" :preferred-device="connection.peerKey"
<TransferPanel ref="panel" :key="mode" :sending="mode === 'send'" :connection="connection" :load-trust="() => loadTrust(connection.id)"
@session-change="sessionActive = $event; status()" @connected-change="connected = $event; direction = mode; status()"
@activity="emit('activity', connection.id, $event)" @paired="emit('paired', connection.id, $event)" />
@activity="emit('activity', connection.id, $event)" @update="emit('update', connection.id, $event)" />
</div>
<aside class="activity-panel" aria-labelledby="activity-heading">
<div class="activity-heading"><h2 id="activity-heading">Activity</h2><span>{{ connection.history.length }}</span></div>
+30 -48
View File
@@ -1,95 +1,77 @@
<script setup lang="ts">
import { onActivated, onMounted, ref, shallowRef, watch } from 'vue';
import { onActivated, onMounted, ref, shallowRef } from 'vue';
import { clearIdentityStorage, createIdentity, loadIdentityState, saveIdentityState, type IdentityState } from '../lib/identity.ts';
import type { ConnectionUpdate } from '../lib/connections.ts';
import { asError } from '../lib/validation.ts';
const props = defineProps<{ disabled: boolean; preferredDevice?: string }>();
const emit = defineEmits<{ change: [state: IdentityState, enabled: boolean, expected: string] }>();
const props = defineProps<{ disabled: boolean; paired: string; remember: boolean }>();
const emit = defineEmits<{ update: [change: ConnectionUpdate] }>();
const supported = (() => { try { return 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 state = shallowRef<IdentityState>({ identity: null });
const working = ref(false), loaded = ref(false);
const error = ref(''), confirmDelete = ref(false);
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;
if (props.preferredDevice && state.value.contacts.some(item => item.key === props.preferredDevice)) expected.value = props.preferredDevice;
}
try { state.value = await loadIdentityState(); loaded.value = true; }
catch (err) { error.value = asError(err).message; }
});
onActivated(async () => {
// Another slot may have changed the shared identity or contact list while
// this workspace was cached. Never interrupt an active session to refresh it.
// Another slot may have replaced the shared identity while this workspace
// was cached. Never interrupt an active session to refresh it.
if (!loaded.value || props.disabled) return;
try {
const next = await loadIdentityState();
if (props.disabled) return;
if (next.identity?.publicKey !== state.value.identity?.publicKey) enabled.value = false;
if (!next.contacts.some(item => item.key === expected.value)) expected.value = '';
if (!expected.value && props.preferredDevice && next.contacts.some(item => item.key === props.preferredDevice)) expected.value = props.preferredDevice;
if (next.revision !== state.value.revision) confirmDelete.value = false;
state.value = next;
} catch (err) { error.value = asError(err).message; }
});
async function store(next: IdentityState) {
state.value = await saveIdentityState(next, state.value.revision);
}
async function run(action: () => Promise<void>) {
if (props.disabled || working.value) return;
working.value = true; error.value = '';
try { await action(); } catch (err) { error.value = asError(err).message; }
finally { working.value = false; }
}
function recover() { void run(async () => { if (!confirmDelete.value) return; await clearIdentityStorage(); state.value = { identity: null, contacts: [] }; loaded.value = true; confirmDelete.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 (!confirmDelete.value) return; await store({ identity: null, contacts: [] }); enabled.value = false; expected.value = ''; confirmDelete.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() {
function recover() { void run(async () => { if (!confirmDelete.value) return; await clearIdentityStorage(); state.value = { identity: null }; loaded.value = true; confirmDelete.value = false; }); }
// Creating an identity from a connection opts that connection in.
function create() { void run(async () => { state.value = await saveIdentityState({ identity: await createIdentity() }, state.value.revision); emit('update', { rememberDevice: true }); }); }
function reset() { void run(async () => { if (!confirmDelete.value) return; state.value = await saveIdentityState({ identity: null }, state.value.revision); confirmDelete.value = false; }); }
function toggle(event: Event) { if (!props.disabled && event.target instanceof HTMLInputElement) emit('update', { rememberDevice: event.target.checked }); }
function forget() { if (!props.disabled) emit('update', { peerKey: '' }); }
async function refreshIdentity() {
if (working.value) throw new Error('Wait for the device settings operation to finish before connecting.');
if (!supported || !enabled.value) return { identity: null, expected: '' };
if (!supported) return null;
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) confirmDelete.value = false;
state.value = next; loaded.value = true; error.value = '';
return { identity: enabled.value ? next.identity : null, expected: expected.value };
return next.identity;
} catch (err) {
error.value = asError(err).message;
throw err;
}
}
defineExpose({ remember, refreshForConnection });
defineExpose({ refreshIdentity });
</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 this identity.</p>
<summary>Remembered device</summary>
<p class="status">Optionally remember the device on this connection, so later sessions verify it automatically. This uses a device identity stored in this browser and shared by all connections. Clearing site data loses it. Trusted app code is required: it can use this identity.</p>
<fieldset class="device-settings" :disabled="disabled || working || !loaded">
<button v-if="!state.identity" @click="create">Create device identity</button>
<template v-else>
<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 v-if="paired">
<p class="status">Paired device <code>{{ paired.slice(-12) }}</code>. Later sessions verify it automatically.</p>
<button @click="forget">Forget device</button>
</template>
<label v-else><input id="remember-device" :checked="remember" type="checkbox" @change="toggle" /> Use my device identity on this connection</label>
<p class="status">When enabled, your public identity is included in this connection’s codes and can link your sessions.</p>
<label><input v-model="confirmDelete" type="checkbox" /> Delete this browser’s device identity</label>
<button :disabled="!confirmDelete" @click="reset">Delete device identity</button>
</template>
<label v-if="state.identity"><input v-model="confirmDelete" type="checkbox" /> Delete this browser’s identity and contacts</label>
<button v-if="state.identity" :disabled="!confirmDelete" @click="reset">Delete identity and contacts</button>
</fieldset>
<div v-if="!loaded && error">
<label><input v-model="confirmDelete" type="checkbox" :disabled="disabled || working" /> Delete unreadable device storage, including identity and contacts</label>
<label><input v-model="confirmDelete" type="checkbox" :disabled="disabled || working" /> Delete unreadable device storage</label>
<button :disabled="disabled || working || !confirmDelete" @click="recover">Clear device storage</button>
</div>
<p v-if="error" role="alert" class="error">{{ error }}</p>
-4
View File
@@ -1,4 +0,0 @@
<script setup lang="ts">
import TransferPanel from './TransferPanel.vue';
</script>
<template><TransferPanel /></template>
-4
View File
@@ -1,4 +0,0 @@
<script setup lang="ts">
import TransferPanel from './TransferPanel.vue';
</script>
<template><TransferPanel sending /></template>
+35 -37
View File
@@ -2,7 +2,7 @@
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, shallowRef, watch } from 'vue';
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import DeviceSettings from './DeviceSettings.vue';
import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts';
import NetworkSettings from './NetworkSettings.vue';
@@ -11,7 +11,7 @@ import { MEMORY_LIMIT, validateMetadata } from '../lib/transfer.ts';
import { FileSession, QUEUE_LIMIT, type QueueItem } from '../lib/session.ts';
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts';
import type { ConnectionActivity } from '../lib/connections.ts';
import type { ConnectionActivity, ConnectionUpdate, SavedConnection } from '../lib/connections.ts';
type Step = 'session-ready' | 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session {
@@ -28,20 +28,12 @@ interface Session {
timer?: ReturnType<typeof setTimeout>;
}
const props = defineProps<{ sending?: boolean; preferredDevice?: string }>();
const props = defineProps<{ sending?: boolean; connection: SavedConnection; loadTrust: () => Promise<SavedConnection> }>();
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()); emit('paired', session.remoteHello.key); canRemember.value = false; contactName.value = ''; }
catch (err) { error.value = asError(err).message; }
finally { savingContact.value = false; }
}
const identityStatus = ref('');
// Offered on the verification step whenever the verified peer would change
// this connection's paired device: 'new' starts ticked, 'replace' does not.
const pairing = ref<'' | 'new' | 'replace'>(''), rememberPeer = ref(false);
const file = ref<File | null>(null);
const selectedFiles = ref<File[]>([]);
const queuedFiles = ref<QueueItem[]>([]);
@@ -50,7 +42,7 @@ const receiveState = ref<TransferState | null>(null);
const outgoing = ref<FileMetadata | null>(null);
const receiveProgress = ref(0);
const lastDirection = ref<'send' | 'receive'>('send');
const emit = defineEmits<{ sessionChange: [active: boolean]; connectedChange: [connected: boolean]; activity: [item: ConnectionActivity]; paired: [key: string] }>();
const emit = defineEmits<{ sessionChange: [active: boolean]; connectedChange: [connected: boolean]; activity: [item: ConnectionActivity]; update: [change: ConnectionUpdate] }>();
const inputCode = ref('');
const outputCode = ref('');
const step = ref<Step>('idle');
@@ -133,7 +125,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 = '';
identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false;
fps.value = incoming.value = null;
verified.value = copied.value = choosing.value = false;
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; streamedDownload.value = false;
@@ -187,10 +179,12 @@ function attach(session: Session, channel: RTCDataChannel) {
session.transfer = new FileSession(channel, !!props.sending, {
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);
if (!canRemember.value && session.remoteHello && (!props.preferredDevice || props.preferredDevice === session.remoteHello.key)) emit('paired', session.remoteHello.key);
// Ready implies both fresh proofs verified, so the key may now be saved.
if (session.identityContext && session.remoteHello) {
const key = session.remoteHello.key;
if (session.expected === key) identityStatus.value = 'Paired device authenticated for this connection.';
else if (rememberPeer.value) { emit('update', { peerKey: key }); identityStatus.value = `Device proof checked. Remembered for ${props.connection.name}.`; }
else identityStatus.value = 'Device proof checked. This device was not remembered.';
}
} },
onQueue: items => { if (active === session) queuedFiles.value = items; },
@@ -272,11 +266,13 @@ async function createCode() {
}
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;
// the paired peer or replaced the local identity since this page loaded.
if (props.connection.rememberDevice) {
const trust = await props.loadTrust();
const identity = trust.rememberDevice ? await devices.value?.refreshIdentity() : null;
if (active !== session) return;
if (trust.rememberDevice) session.expected = trust.peerKey;
if (identity) { session.identity = identity; session.localHello = hello(identity); }
}
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
if (active !== session) return;
@@ -291,7 +287,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); configureIdentity(session); }
if (!props.sending) { fps.value = getFingerprints(session.pc, options); offerPairing(session); configureIdentity(session); }
step.value = props.sending ? 'offer-ready' : 'answer-ready';
} catch (err) {
if (session) fail(session, err);
@@ -312,6 +308,7 @@ async function useAnswer() {
session.diagnostics.descriptions();
void session.diagnostics.capture();
fps.value = getFingerprints(session.pc, session.options);
offerPairing(session);
configureIdentity(session);
} catch (err) {
if (active !== session) return;
@@ -323,11 +320,16 @@ async function useAnswer() {
} else fail(session, err);
}
}
function offerPairing(session: Session) {
const key = session.localHello && session.remoteHello?.key;
pairing.value = !key || key === session.expected ? '' : session.expected ? 'replace' : 'new';
rememberPeer.value = pairing.value === 'new';
}
function configureIdentity(session: Session) {
if (!fps.value || !session.transfer || session.identityContext) return;
if (!session.identity || !session.localHello || !session.remoteHello) {
if (session.expected) identityStatus.value = '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.';
if (session.expected) identityStatus.value = 'A device identity is missing. Compare both fingerprints manually; the paired device is not being used.';
else if (session.localHello || session.remoteHello) identityStatus.value = 'Both people must use their device identity to remember each other. Compare fingerprints manually for this connection.';
return;
}
const initiator = !!props.sending;
@@ -341,9 +343,9 @@ function configureIdentity(session: Session) {
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();
identityStatus.value = 'Checking the paired 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.';
identityStatus.value = session.expected ? 'Device identity differs from the paired device. Compare both fingerprints manually before continuing. The paired device is only replaced if you choose to.' : 'New device. Compare both fingerprints manually before remembering it.';
}
}
function verify() {
@@ -418,7 +420,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" :preferred-device="preferredDevice" :disabled="busy || connected || savingContact" @change="deviceChange" />
<DeviceSettings ref="devices" :paired="connection.peerKey" :remember="connection.rememberDevice" :disabled="busy || connected" @update="emit('update', $event)" />
<details class="network-details">
<summary>Network settings</summary>
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
@@ -445,13 +447,9 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<div class="fp-row"><span>Your fingerprint</span><code>{{ fps.local }}</code></div>
<div class="fp-row"><span>Their fingerprint</span><code>{{ fps.remote }}</code></div>
<p class="status">Compare every byte over an authenticated channel an attacker cannot alter (for example, an in-person comparison). Your fingerprint must match their “Their fingerprint”, and vice versa. If either differs, cancel. Both people must confirm before the filename or contents are sent.</p>
<label v-if="pairing"><input v-model="rememberPeer" type="checkbox" :disabled="verified" /> {{ pairing === 'new' ? `Remember this device for ${connection.name}` : `Replace the paired device of ${connection.name}` }}</label>
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Verification submitted' : 'Both fingerprints match — confirm' }}</button>
</div>
<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>
<p v-if="!incoming" class="status">Waiting for your peer to send a file. You can send files yourself using Send above.</p>
+8 -4
View File
@@ -14,10 +14,13 @@ export interface SavedConnection {
id: string;
number: number;
name: string;
// The peer this connection trusts. Only set after mutual verification.
peerKey: string;
// Per-connection opt-in to include this browser's identity in codes.
rememberDevice: boolean;
history: ConnectionActivity[];
}
export type ConnectionUpdate = { name: string } | { peerKey: string } | { activity: ConnectionActivity };
export type ConnectionUpdate = { name: string } | { peerKey: string } | { rememberDevice: boolean } | { activity: ConnectionActivity };
export function connectionName(value: string) {
const name = value.trim();
if (!name || name.length > 80) throw new Error('Use a connection name between 1 and 80 characters.');
@@ -29,6 +32,7 @@ export function updateConnection(current: SavedConnection, update: ConnectionUpd
if (update.peerKey && !/^04[0-9a-f]{128}$/.test(update.peerKey)) throw new Error('Invalid paired device.');
return { ...current, peerKey: update.peerKey };
}
if ('rememberDevice' in update) return { ...current, rememberDevice: update.rememberDevice === true };
const item = update.activity;
if (typeof item.id !== 'string' || !item.id || !Number.isSafeInteger(item.time) || item.time < 0 || item.time > 8640000000000000 ||
typeof item.name !== 'string' || !item.name || item.name.length > 255 ||
@@ -37,12 +41,12 @@ export function updateConnection(current: SavedConnection, update: ConnectionUpd
return { ...current, history: [...current.history.filter(previous => previous.id !== item.id), item].sort((a, b) => a.time - b.time).slice(-HISTORY_LIMIT) };
}
export function emptyConnection(number = 1): SavedConnection {
return { id: crypto.randomUUID(), number, name: `Con ${number}`, peerKey: '', history: [] };
return { id: crypto.randomUUID(), number, name: `Con ${number}`, peerKey: '', rememberDevice: false, history: [] };
}
function validateConnection(value: unknown): SavedConnection {
if (!isRecord(value) || typeof value.id !== 'string' || !value.id || !Number.isSafeInteger(value.number) || (value.number as number) < 1 ||
typeof value.name !== 'string' || typeof value.peerKey !== 'string' || !Array.isArray(value.history) || value.history.length > HISTORY_LIMIT) throw new Error('Saved connections are unreadable.');
let record: SavedConnection = { id: value.id, number: value.number as number, name: connectionName(value.name), peerKey: '', history: [] };
let record: SavedConnection = { id: value.id, number: value.number as number, name: connectionName(value.name), peerKey: '', rememberDevice: value.rememberDevice === true, history: [] };
record = updateConnection(record, { peerKey: value.peerKey });
for (const item of value.history) {
if (!isRecord(item)) throw new Error('Saved activity is unreadable.');
@@ -60,7 +64,7 @@ async function database() {
});
}
// Read and write within one transaction so other tabs cannot overwrite a rename,
// device association, or history entry with a stale copy of the entire record.
// paired device, or history entry with a stale copy of the entire record.
async function change(action: (records: SavedConnection[], store: IDBObjectStore) => void) {
const db = await database();
try {
+3 -17
View File
@@ -2,8 +2,7 @@ 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 IdentityState { revision?: string; identity: Identity | null }
export interface IdentityContext { offer: IdentityHello; answer: IdentityHello; offerFingerprint: string; answerFingerprint: string }
const curve = { name: 'ECDSA', namedCurve: 'P-256' };
const signing = { name: 'ECDSA', hash: 'SHA-256' };
@@ -42,17 +41,6 @@ export async function verifyIdentity(proof: unknown, context: IdentityContext, i
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) => {
@@ -71,17 +59,15 @@ export async function loadIdentityState(): Promise<IdentityState> {
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) return { identity: null };
if (state.identity) {
unhex(state.identity.publicKey, 65);
if (!(state.identity.privateKey instanceof CryptoKey) || state.identity.privateKey.type !== 'private') throw new Error('Stored identity is invalid. Clear device storage and create a new identity.');
}
return state;
return { revision: state.revision, identity: state.identity ?? null };
} 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 {
+4 -1
View File
@@ -261,7 +261,7 @@ p.stun-hint {
.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; }
.device-settings input:not([type=checkbox]) { box-sizing: border-box; max-width: 100%; padding: 0.6rem; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; }
/* The connection shell stays in place while each workspace scrolls. */
.app-shell { display: grid; grid-template-columns: 264px minmax(0, 1fr); height: 100%; }
@@ -299,6 +299,9 @@ summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.title-line { display: flex; align-items: center; gap: 1rem; margin-top: 0.4rem; }
.title-line h1 { margin: 0; font-size: 1.35rem; font-weight: 600; font-family: inherit; overflow-wrap: anywhere; }
.header-action { font-size: 0.72rem; padding: 0.3rem 0.5rem; color: var(--muted); background: transparent; border-color: transparent; }
.header-action-icon { margin-right: 0.15rem; opacity: 0.65; }
.header-action:hover:not(:disabled), .header-action:focus-visible { color: #ff9185; }
.header-action:hover:not(:disabled) .header-action-icon, .header-action:focus-visible .header-action-icon { opacity: 1; }
.session-badge { display: inline-flex; align-items: center; gap: 0.45rem; color: var(--muted); font-size: 0.74rem; white-space: nowrap; border: 1px solid var(--border); border-radius: 20px; padding: 0.45rem 0.7rem; }
.session-badge.connected { color: #8ddbb6; border-color: #315344; }
.workspace-scroll { flex: 1; overflow-y: auto; padding: 2rem 2.25rem; }
+5 -1
View File
@@ -7,8 +7,12 @@ test('renaming and pairing preserve a slot identity and its activity', () => {
const activity: ConnectionActivity = { id: 'transfer', time: 1, direction: 'send', name: 'example.txt', size: 123, result: 'complete' };
const withHistory = updateConnection(initial, { activity });
const renamed = updateConnection(withHistory, { name: ' Work laptop ' });
const paired = updateConnection(renamed, { peerKey: '04' + 'a'.repeat(128) });
const remembering = updateConnection(renamed, { rememberDevice: true });
const paired = updateConnection(remembering, { peerKey: '04' + 'a'.repeat(128) });
assert.equal(initial.name, 'Con 2');
assert.equal(initial.rememberDevice, false);
assert.equal(paired.rememberDevice, true);
assert.equal(updateConnection(paired, { peerKey: '' }).rememberDevice, true, 'Forgetting a device keeps the opt-in');
assert.equal(paired.id, initial.id);
assert.equal(paired.name, 'Work laptop');
assert.deepEqual(paired.history, [activity]);
+2 -5
View File
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createIdentity, hello, signIdentity, verifyIdentity, parseHello, validateContacts, type IdentityContext } from '../src/lib/identity.ts';
import { createIdentity, hello, signIdentity, verifyIdentity, parseHello, 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();
@@ -22,13 +22,10 @@ test('device proof binds both keys, fresh nonces, roles, and both DTLS fingerpri
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 () => {
test('identity input is bounded', 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('device private keys cannot be extracted and still sign after storage cloning', async () => {
const { first, context } = await setup();