Download client/app.js from abr00kx/taper: direct link, hf CLI and curl.
- Browser
- Download file 53.4 kB
-
https://huggingface.co/abr00kx/taper/resolve/main/client/app.js
- Command line
-
hf download hf://abr00kx/taper/client/app.js
-
curl -L -o app.js https://huggingface.co/abr00kx/taper/resolve/main/client/app.js
53.4 kB
// Taper development web client.
//
// Talks to the Taper WebSocket gateway directly, with no build step. Messages
// are end-to-end encrypted with Olm/Megolm (vodozemac, via
// @matrix-org/matrix-sdk-crypto-wasm); see crypto.js for the room version 13
// checks layered on top.
import * as sdk from './node_modules/@matrix-org/matrix-sdk-crypto-wasm/index.mjs';
import { TaperCrypto, padJson, verifyRoomState } from './crypto.js';
import { solveChallenge } from './pow.js';
import * as opaque from './opaque.js';
import * as account from './account.js';
import * as webauthn from './webauthn.js';
import * as device from './device.js';
import { encryptFile, decryptFile, upload, download, parseBinaryFrame, BIN_DOWNLOAD } from './media.js';
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
// When a Taper server hosts this client under its secret gateway path, it
// marks the page, and the client connects back to that same path.
const HOSTED = document.querySelector('meta[name="taper-gateway"]')?.content === 'same-origin';
const DEFAULT_GATEWAY = HOSTED
? `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}${location.pathname.replace(/\/(index\.html)?$/, '')}`
: 'ws://127.0.0.1:8080/_taper/gateway/v1';
const STORAGE_KEY = 'taper-dev-session';
const REQUEST_TIMEOUT_MS = 15_000;
// ---------------------------------------------------------------------------
// Small DOM helpers. User-controlled text only ever goes in via text nodes.
// ---------------------------------------------------------------------------
const $ = (sel) => document.querySelector(sel);
function h(tag, props = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value === undefined || value === null || value === false) continue;
if (key === 'class') node.className = value;
else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);
else node.setAttribute(key, value === true ? '' : value);
}
for (const child of children.flat()) {
if (child === null || child === undefined || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
function toast(message) {
console.info(`[taper] ${message}`);
const t = h('div', { class: 'toast' }, message);
$('#toasts').append(t);
setTimeout(() => t.remove(), 5000);
}
function randomB64(bytes) {
const buf = crypto.getRandomValues(new Uint8Array(bytes));
return btoa(String.fromCharCode(...buf)).replace(/=+$/, '');
}
const localpart = (userId) => (userId ?? '').replace(/^@/, '').split(':')[0];
// A colored circle with an initial. The hue comes from the ID, so a person
// keeps their color everywhere, with nothing fetched from a server.
function avatar(id, label = id) {
let hash = 0;
for (const ch of id ?? '') hash = (hash * 31 + ch.codePointAt(0)) >>> 0;
const initial = [...(label ?? '').replace(/^[@!#]/, '')][0]?.toUpperCase() ?? '?';
return h('span', { class: `avatar hue-${hash % 8}`, 'aria-hidden': 'true' }, initial);
}
function relativeExpiry(ts) {
const ms = ts - Date.now();
if (ms <= 0) return 'expired';
const d = Math.floor(ms / 86_400_000);
const hrs = Math.floor((ms % 86_400_000) / 3_600_000);
if (d > 0) return `expires in ${d}d ${hrs}h`;
const m = Math.floor((ms % 3_600_000) / 60_000);
return hrs > 0 ? `expires in ${hrs}h ${m}m` : `expires in ${m}m`;
}
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
const state = {
url: DEFAULT_GATEWAY,
token: null,
userId: null,
sessionId: null,
seq: 0,
ws: null,
heartbeat: null,
helloWaiters: [],
pending: new Map(),
nextId: 1,
reconnectDelay: 1000,
reconnectTimer: null,
intentionalClose: false,
sessionGen: 0, // bumped by leave(): async work from before a lock is dropped
rooms: new Map(), // room_id -> { roomId, state: Map, timeline: [], ids: Set, more: bool }
invites: new Map(), // room_id -> { inviter, state }
current: null,
deviceId: null,
// The crypto store lives in IndexedDB, encrypted with a passphrase that only
// exists in this tab's sessionStorage. Closing the tab makes it unreadable.
storeName: null,
storePass: null,
crypto: null,
cryptoReady: null,
cryptoUp: false, // cryptoReady has resolved: replay/session tables are loaded
decrypted: new Map(), // event_id -> { kind, text, retry?, trust? }
decrypting: new Set(),
trust: new Map(), // user_id -> identity trust (see TaperCrypto.identityTrust)
downloads: new Map(), // download_id -> Map(chunk index -> bytes)
media: new Map(), // event_id -> object URL of decrypted media
pendingExportKey: null, // OPAQUE export key, held only until crypto is set up after login
pendingPassphrase: null, // device passphrase, held only until the device is sealed
deviceHandle: null, // set while a device that stays signed in is unlocked (see device.js)
seenLoaded: null, // replay table loaded at unlock
keysInfo: null, // this account's security keys, from the server
hardware: new Map(), // user_id -> 'attested' | 'unattested': whose servers say they hold a key
backupKey: null, // room-key backup key (raw bytes), from the password
backed: new Set(), // Megolm session IDs already in the backup
backupDay: null,
backupParts: 0,
verification: null,
verifiedOnlyRooms: new Set(), // room_ids where sending requires all members to be verified
roomIntegrity: new Map(), // room_id -> string[] of client-side Room v13 state warnings
newUnverified: new Map(), // room_id -> Set(user_id) of unverified members who joined live
devicesList: [],
};
const TRUST_LABEL = {
you: 'you', verified: '✓ verified', unverified: 'unverified', changed: '⚠ identity changed',
violation: '⚠ changed since verified', none: 'no identity', unknown: '…',
};
function saveSession() {
// A device that stays signed in keeps its session sealed instead (device.js).
if (state.deviceHandle) return;
try {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify({
url: state.url, token: state.token, userId: state.userId,
deviceId: state.deviceId, storeName: state.storeName, storePass: state.storePass,
backupKey: state.backupKey ? btoa(String.fromCharCode(...state.backupKey)) : null,
seen: state.crypto ? state.crypto.exportSeen() : (state.seenLoaded?.seen ?? []),
sessions: state.crypto ? state.crypto.exportSessionAges() : (state.seenLoaded?.sessions ?? []),
verifiedOnly: [...state.verifiedOnlyRooms],
}));
} catch { /* storage may be unavailable */ }
}
function loadSession() {
try { return JSON.parse(sessionStorage.getItem(STORAGE_KEY) ?? 'null'); } catch { return null; }
}
function clearSession() {
try { sessionStorage.removeItem(STORAGE_KEY); } catch { /* ignore */ }
}
function ensureRoom(roomId) {
if (!state.rooms.has(roomId)) {
state.rooms.set(roomId, { roomId, state: new Map(), timeline: [], ids: new Set(), more: true, knownMembers: new Set() });
}
return state.rooms.get(roomId);
}
// Throws if the room is forged or not version 13; sending checks this first.
async function checkRoomIntegrity(room) {
const { warnings, fatal } = await verifyRoomState(room.roomId, [...room.state.values()]);
state.roomIntegrity.set(room.roomId, warnings);
if (room.roomId === state.current) renderWarnings(room);
if (fatal) throw new Error('This room failed its integrity check: sending is blocked.');
}
// Encrypt `content` (or state, with `stateKey`) for everyone joined to `room`.
async function encryptFor(room, type, content, { stateKey, attachments } = {}) {
await checkRoomIntegrity(room);
const verifiedOnly = state.verifiedOnlyRooms.has(room.roomId);
return withCrypto((c) => (stateKey === undefined
? c.encrypt(room.roomId, joinedMembers(room), type, content, { attachments, verifiedOnly })
: c.encryptState(room.roomId, joinedMembers(room), type, stateKey, content, { verifiedOnly })));
}
function roomPowerLevel(room, userId) {
const create = room.state.get('t.room.create|');
if (create?.sender === userId || (Array.isArray(create?.content?.additional_creators) && create.content.additional_creators.includes(userId))) {
return Infinity;
}
const pl = room.state.get('t.room.power_levels|')?.content;
if (pl?.users && Object.hasOwn(pl.users, userId) && Number.isSafeInteger(pl.users[userId])) return pl.users[userId];
return Number.isSafeInteger(pl?.users_default) ? pl.users_default : 0;
}
function canModerate(room, action, targetUser) {
if (targetUser === state.userId) return false;
const pl = room.state.get('t.room.power_levels|')?.content;
const need = Number.isSafeInteger(pl?.[action]) ? pl[action] : 50;
const mine = roomPowerLevel(room, state.userId);
return mine >= need && mine > roomPowerLevel(room, targetUser);
}
// The room name is encrypted state (room version 13): decrypt and cache it.
function roomName(room) {
const ev = room.state.get('t.room.encrypted|t.room.name:');
if (!ev) return room.roomId;
const d = state.decrypted.get(ev.event_id);
if (d?.kind === 'state' && typeof d.content?.name === 'string' && d.content.name) return d.content.name;
if (!d) scheduleDecrypt(ev);
return room.roomId;
}
async function setEncryptedState(roomId, type, stateKey, content) {
const enc = await encryptFor(ensureRoom(roomId), type, content, { stateKey });
return request('t.room.state.set', { room_id: roomId, ...enc });
}
// New members can't read state encrypted before they joined, so an authorized
// member sends it again. In verified-only rooms, wait until the new member is
// verified before sharing room details.
async function resendEncryptedState(room) {
const pl = room.state.get('t.room.power_levels|')?.content;
const stateNeed = Number.isSafeInteger(pl?.state_default) ? pl.state_default : 50;
if (roomPowerLevel(room, state.userId) < stateNeed) return;
if (state.verifiedOnlyRooms.has(room.roomId)) {
const anyUnverified = joinedMembers(room).some((u) => u !== state.userId && state.trust.get(u) !== 'verified');
if (anyUnverified) return;
}
for (const ev of [...room.state.values()]) {
if (ev.type !== 't.room.encrypted') continue;
try {
const d = await withCrypto((c) => c.decrypt(ev));
await setEncryptedState(room.roomId, d.type, d.state_key, d.content);
} catch (e) {
toast(`Couldn't share room details with the new member: ${e.message}`);
}
}
}
function addEvent(room, ev, { prepend = false } = {}) {
// The creation event is fixed: a later one can't replace it.
if (ev.state_key !== undefined && !(ev.type === 't.room.create' && room.state.has('t.room.create|'))) {
room.state.set(`${ev.type}|${ev.state_key}`, ev);
}
if (ev.type === 't.room.redaction') {
const target = room.timeline.find((e) => e.event_id === ev.content.redacts);
if (target) target.content = {};
state.decrypted.delete(ev.content.redacts);
}
if (room.ids.has(ev.event_id)) return;
room.ids.add(ev.event_id);
if (prepend) room.timeline.unshift(ev);
else room.timeline.push(ev);
}
// ---------------------------------------------------------------------------
// Gateway connection
// ---------------------------------------------------------------------------
function setStatus(kind) {
const s = $('#conn-status');
s.className = `status ${kind}`;
s.title = { online: 'Connected', connecting: 'Connecting…', offline: 'Disconnected' }[kind];
s.setAttribute('aria-label', `Connection: ${s.title}`);
}
// Plain ws:// only to this machine or an onion service (Tor encrypts that).
function checkGateway(url) {
const u = new URL(url);
const local = ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname) || u.hostname.endsWith('.onion');
if (u.protocol === 'wss:' || (u.protocol === 'ws:' && local)) return url;
throw new Error('The gateway must use wss://, or ws:// to localhost or a .onion address');
}
function openSocket() {
return new Promise((resolve, reject) => {
setStatus('connecting');
let ws;
try { ws = new WebSocket(checkGateway(state.url)); } catch (e) { reject(e); return; }
ws.binaryType = 'arraybuffer';
state.ws = ws;
state.intentionalClose = false;
state.helloWaiters.push(resolve);
ws.addEventListener('message', (e) => {
if (typeof e.data !== 'string') {
const bin = parseBinaryFrame(new Uint8Array(e.data));
if (bin?.op === BIN_DOWNLOAD) state.downloads.get(bin.id)?.set(bin.index, bin.data.slice());
return;
}
let frame;
try { frame = JSON.parse(e.data); } catch { return; }
onFrame(frame);
});
ws.addEventListener('close', (e) => onClose(e, reject));
});
}
function send(frame) {
if (state.ws?.readyState === WebSocket.OPEN) state.ws.send(JSON.stringify(padJson(frame)));
}
async function request(method, body = {}, { attempt = 0, extra = {} } = {}) {
const id = state.nextId++;
const res = await new Promise((resolve, reject) => {
const timer = setTimeout(() => {
state.pending.delete(id);
reject(new Error(`${method} timed out`));
}, REQUEST_TIMEOUT_MS);
state.pending.set(id, { resolve, reject, timer });
send({ op: 'request', id, method, body, ...extra });
});
if (res.ok) return res.body;
const e = res.error ?? {};
// Short rate limits are waited out; a used-up daily budget is reported.
if (e.errcode === 'T_LIMIT_EXCEEDED' && attempt < 3 && (e.retry_after_ms ?? 0) <= 10_000) {
await new Promise((r) => setTimeout(r, e.retry_after_ms ?? 1000));
return request(method, body, { attempt: attempt + 1 });
}
// Proof-of-work challenges are answered automatically.
if (e.errcode === 'T_CHALLENGE_REQUIRED' && attempt < 3) {
const slow = setTimeout(() => toast('Solving an anti-abuse challenge…'), 1000);
try {
const response = await solveChallenge(e.challenge, state.sessionId ?? state.connectionId);
return await request(method, body, { attempt: attempt + 1, extra: { challenge_response: response } });
} finally {
clearTimeout(slow);
}
}
const err = new Error(e.error ?? 'Request failed');
err.errcode = e.errcode;
throw err;
}
function onFrame(frame) {
switch (frame.op) {
case 'hello': {
clearTimeout(state.heartbeat);
state.connectionId = frame.body.connection_id;
state.serverName = frame.body.server_name;
// Heartbeats are jittered by ±20%: a fixed interval is a fingerprint.
const base = Math.max(1000, frame.body.heartbeat_interval_ms * 0.7);
const beat = () => {
send({ op: 'heartbeat' });
state.heartbeat = setTimeout(beat, base * (0.8 + Math.random() * 0.4));
};
state.heartbeat = setTimeout(beat, base * (0.8 + Math.random() * 0.4));
state.helloWaiters.splice(0).forEach((resolve) => resolve(frame.body));
return;
}
case 'response': {
const p = state.pending.get(frame.id);
if (!p) return;
clearTimeout(p.timer);
state.pending.delete(frame.id);
p.resolve(frame);
return;
}
case 'ready':
onReady(frame.body);
return;
case 'resumed':
state.reconnectDelay = 1000;
setStatus('online');
return;
case 'dispatch':
state.seq = frame.seq;
onDispatch(frame.type, frame.body);
return;
case 'reconnect':
// The server is about to close; onClose reconnects and resumes.
return;
default:
// heartbeat_ack and anything newer than this client: ignore.
}
}
function onClose(event, rejectHello) {
clearTimeout(state.heartbeat);
for (const p of state.pending.values()) { clearTimeout(p.timer); p.reject(new Error('Disconnected')); }
state.pending.clear();
if (state.helloWaiters.length) { state.helloWaiters = []; rejectHello(new Error('Could not connect to the gateway')); }
setStatus('offline');
if (state.intentionalClose) return;
if (event.code === 4004) { // token rejected or logged out elsewhere
signedOut('Your session ended. Log in again.');
return;
}
if (event.code === 4007) state.sessionId = null; // can't resume; identify fresh
if (!state.token) return;
const delay = state.reconnectDelay;
state.reconnectDelay = Math.min(delay * 2, 30_000);
state.reconnectTimer = setTimeout(reconnect, delay);
}
async function reconnect() {
if (state.intentionalClose || !state.token) return;
try {
await openSocket();
if (state.intentionalClose || !state.token) { state.ws?.close(); return; }
if (state.sessionId) {
send({ op: 'resume', body: { access_token: state.token, session_id: state.sessionId, seq: state.seq } });
} else {
send({ op: 'identify', body: { access_token: state.token } });
}
} catch {
state.reconnectTimer = setTimeout(reconnect, state.reconnectDelay);
}
}
// ---------------------------------------------------------------------------
// End-to-end encryption
// ---------------------------------------------------------------------------
async function deleteCryptoStore(name) {
if (!name) return;
try {
for (const db of await indexedDB.databases()) {
if (db.name?.startsWith(name)) indexedDB.deleteDatabase(db.name);
}
} catch { /* nothing to delete, or not supported */ }
}
async function startCrypto(body) {
if (state.crypto && state.deviceId === body.device_id) {
await state.crypto.receive({ oneTimeKeyCounts: body.one_time_key_counts });
return;
}
state.crypto?.close();
state.crypto = null;
if (state.deviceId !== body.device_id || !state.storePass) {
await deleteCryptoStore(state.storeName);
state.deviceId = body.device_id;
state.storeName = `taper-crypto-${body.device_id}`;
state.storePass = randomB64(32);
}
saveSession();
await sdk.initAsync();
state.crypto = await TaperCrypto.create(sdk, {
userId: body.user_id, deviceId: body.device_id, request,
storeName: state.storeName, storePassphrase: state.storePass,
});
state.crypto.onVerificationRequest = (v) => {
// Don't let another request replace a verification in progress.
if (state.verification) { v.cancel().catch(() => {}); return; }
showVerification(v, { incoming: true });
};
state.crypto.onTrustChanged = (u) => refreshTrust([u]);
// Messages the server replays and expired session tombstones must survive a reload/restart.
const loaded = state.seenLoaded ?? { seen: [], sessions: [] };
state.crypto.restoreSeen(loaded.seen ?? [], loaded.sessions ?? []);
if (!state.deviceHandle) state.crypto.onSeenChanged = () => saveSession();
await state.crypto.receive({ oneTimeKeyCounts: body.one_time_key_counts });
const exportKey = state.pendingExportKey;
state.pendingExportKey = null;
// Never replace an existing identity on login: that is an explicit choice in Settings.
const cs = await state.crypto.ensureCrossSigning({ exportKey });
if (cs === 'recovered') toast('Your encryption identity was restored with your password.');
if (cs === 'needs-password') {
toast("This device couldn't recover your encryption identity. Log in with your password again, or replace it in Settings → Replace encryption identity.");
}
await account.afterCrypto({ exportKey });
}
// Run once crypto is ready; dispatches can arrive while it is starting.
function withCrypto(fn) {
return (state.cryptoReady ?? Promise.reject(new Error('Encryption is not ready'))).then(() => fn(state.crypto));
}
function onCryptoDispatch(type, body) {
const input = type === 't.to_device' ? { toDevice: body.events }
: type === 't.device_lists' ? { changed: body.changed ?? [], left: body.left ?? [] }
: { oneTimeKeyCounts: body.one_time_key_counts };
withCrypto((c) => c.receive(input)).then(() => {
if (type === 't.device_lists') {
// Trust shown on these users' messages may be out of date: re-check it,
// and rotate outbound Megolm sessions in any shared room (security.md).
const changed = new Set([...(body.changed ?? []), ...(body.left ?? [])]);
for (const room of state.rooms.values()) {
if (joinedMembers(room).some((u) => changed.has(u))) {
withCrypto((c) => c.invalidateRoomSession(room.roomId)).catch(() => {});
}
for (const ev of room.timeline) {
const d = state.decrypted.get(ev.event_id);
if (d?.trust && d.trust !== 'verified' && changed.has(ev.sender)) state.decrypted.delete(ev.event_id);
}
}
refreshTrust([...changed]);
if (state.current) renderTimeline();
}
if (type !== 't.to_device') return;
// New room keys may have arrived: retry messages we couldn't decrypt.
for (const [id, d] of state.decrypted) if (d.retry) state.decrypted.delete(id);
if (state.current) renderTimeline();
}).catch((e) => toast(`Encryption error: ${e.message}`));
}
function joinedMembers(room) {
const out = [];
for (const ev of room.state.values()) {
if (ev.type === 't.room.member' && ev.content.membership === 'join') out.push(ev.state_key);
}
return out;
}
function onReady(body) {
state.sessionId = body.session_id;
state.userId = body.user_id;
state.seq = 0;
state.reconnectDelay = 1000;
state.rooms.clear();
state.invites.clear();
for (const r of body.rooms.joined) {
const room = ensureRoom(r.room_id);
for (const ev of r.state) room.state.set(`${ev.type}|${ev.state_key}`, ev);
for (const m of joinedMembers(room)) room.knownMembers.add(m);
for (const ev of r.timeline) addEvent(room, ev);
checkRoomIntegrity(room).catch(() => {});
}
for (const inv of body.rooms.invited) state.invites.set(inv.room_id, inv);
if (state.current && !state.rooms.has(state.current)) state.current = null;
saveSession();
setStatus('online');
showApp();
render();
setCryptoReady(false);
const gen = state.sessionGen;
state.cryptoReady = startCrypto(body);
state.cryptoReady.then(() => {
if (gen !== state.sessionGen) return;
setCryptoReady(true);
if (state.current) renderTimeline();
}).catch((e) => {
if (/cannot change/.test(e.message)) {
signedOut('This device lost its encryption keys. Log in again to start a new device.');
} else {
toast(`Couldn't start encryption: ${e.message}`);
}
});
}
// Sending waits until this device's encryption (including cross-signing) is
// set up. Otherwise the first messages would go out before other people's
// clients can see that this device belongs to us.
function setCryptoReady(ready) {
state.cryptoUp = ready;
document.body.dataset.crypto = ready ? 'ready' : 'starting';
const msg = $('#message');
msg.disabled = !ready;
msg.placeholder = ready ? 'Message' : 'Setting up encryption…';
$('#attach').disabled = !ready;
$('#composer button[type="submit"]').disabled = !ready;
}
function onDispatch(type, body) {
if (type === 't.to_device' || type === 't.device_lists' || type === 't.keys.counts') {
onCryptoDispatch(type, body);
return;
}
if (type === 't.room.invite') {
state.invites.set(body.room_id, body);
renderSidebar();
return;
}
if (type === 't.room.joined') {
state.invites.delete(body.room_id);
const room = ensureRoom(body.room_id);
for (const ev of body.state) room.state.set(`${ev.type}|${ev.state_key}`, ev);
for (const m of joinedMembers(room)) room.knownMembers.add(m);
checkRoomIntegrity(room).catch(() => {});
if (!state.current) state.current = body.room_id;
render();
return;
}
if (type === 't.room.event') {
const ev = body.event;
const mine = ev.type === 't.room.member' && ev.state_key === state.userId;
if (mine && ['leave', 'ban'].includes(ev.content.membership)) {
state.rooms.delete(body.room_id);
state.invites.delete(body.room_id);
state.roomIntegrity.delete(body.room_id);
state.newUnverified.delete(body.room_id);
if (state.current === body.room_id) state.current = null;
render();
return;
}
if (mine && ev.content.membership === 'invite') return; // handled by t.room.invite
const room = ensureRoom(body.room_id);
addEvent(room, ev);
if (ev.state_key !== undefined) checkRoomIntegrity(room).catch(() => {});
if (ev.type === 't.room.member') {
const m = ev.content?.membership;
if (m === 'leave' || m === 'ban') {
// Immediate forward secrecy: rotate outbound Megolm session when any member leaves/is removed.
room.knownMembers.delete(ev.state_key);
state.newUnverified.get(body.room_id)?.delete(ev.state_key);
withCrypto((c) => c.invalidateRoomSession(body.room_id)).catch(() => {});
} else if (m === 'join' && ev.state_key !== state.userId) {
if (!room.knownMembers.has(ev.state_key)) {
room.knownMembers.add(ev.state_key);
if (state.trust.get(ev.state_key) !== 'verified') {
(state.newUnverified.get(body.room_id) ?? state.newUnverified.set(body.room_id, new Set()).get(body.room_id)).add(ev.state_key);
}
}
}
}
if (body.room_id === state.current) {
renderTimeline({ stickToBottom: true });
if (ev.type === 't.room.member') {
renderMembers(room);
renderWarnings(room);
refreshTrust([ev.state_key]);
if (ev.content.membership === 'join' && ev.state_key !== state.userId) resendEncryptedState(room);
}
} else {
renderSidebar();
}
}
}
// ---------------------------------------------------------------------------
// Messages
// ---------------------------------------------------------------------------
function decodeMessage(ev) {
if (!ev.content?.ciphertext) return { kind: 'gone', text: 'Message deleted' };
const done = state.decrypted.get(ev.event_id);
if (done) return done;
scheduleDecrypt(ev);
return { kind: 'pending', text: 'Decrypting…' };
}
// Only once crypto is up: decrypting earlier could stamp sessions before
// their saved ages (and tombstones) are loaded.
function scheduleDecrypt(ev) {
if (!state.cryptoUp || state.decrypting.has(ev.event_id)) return;
const gen = state.sessionGen;
state.decrypting.add(ev.event_id);
state.crypto.decrypt(ev)
.then((r) => {
if (gen !== state.sessionGen) return;
if (ev.state_key !== undefined) {
state.decrypted.set(ev.event_id, { kind: 'state', content: r.content, type: r.type });
return;
}
const ok = r.type === 't.room.message' && typeof r.content?.body === 'string';
const hasFile = ok && ['t.image', 't.file'].includes(r.content.msgtype) && r.content.file?.url;
state.decrypted.set(ev.event_id, ok
? {
kind: 'ok', text: hasFile ? `📎 ${r.content.body}` : r.content.body, trust: r.trust, trustMessage: r.trustMessage,
...(hasFile ? { file: r.content.file, info: r.content.info ?? {}, msgtype: r.content.msgtype } : {}),
}
: { kind: 'warn', text: `Unsupported message type ${r.type}` });
})
.catch((e) => {
if (gen !== state.sessionGen) return;
// A missing room key may still arrive; integrity failures are final.
const retry = !/moved from another event|another room|someone else|known device|unsigned device|relation does not match|expired past retention|Replayed|valid timestamp|changed identity|Malformed|does not match its state key|state sent as a message|does not list in attachments|Unsupported encryption/.test(e.message);
state.decrypted.set(ev.event_id, { kind: 'warn', text: retry ? 'Waiting for the key to this message…' : `Rejected: ${e.message}`, retry });
})
.finally(() => {
if (gen !== state.sessionGen) return;
state.decrypting.delete(ev.event_id);
if (ev.state_key !== undefined) {
renderSidebar();
if (ev.room_id === state.current) $('#room-name').textContent = roomName(state.rooms.get(ev.room_id));
} else if (ev.room_id === state.current) {
renderTimeline();
}
});
}
function describeState(ev) {
const who = localpart(ev.sender);
switch (ev.type) {
case 't.room.create': return `${who} created the room`;
case 't.room.name': return `${who} named the room “${ev.content.name ?? ''}”`;
case 't.room.topic': return `${who} set the topic`;
case 't.room.encrypted': return ev.state_key?.startsWith('t.room.name:') ? `${who} set the room name` : null;
case 't.room.join_rules': return `${who} made the room ${ev.content.join_rule === 'public' ? 'joinable by anyone with its ID' : 'invite-only'}`;
case 't.room.member': {
const target = localpart(ev.state_key);
const m = ev.content.membership;
if (m === 'join') return `${target} joined`;
if (m === 'invite') return `${who} invited ${target}`;
if (m === 'leave') return ev.sender === ev.state_key ? `${target} left` : `${who} removed ${target}`;
if (m === 'ban') return `${who} banned ${target}`;
return null;
}
default: return null; // encryption, history visibility: not worth a line
}
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
function showLogin(message = '') {
$('#app-view').hidden = true;
$('#login-view').hidden = false;
$('#gateway-url').value = state.url;
// Hosted by a server, the gateway is filled in: keep it out of the way.
$('#gateway-adv').open = !state.url;
$('#login-error').textContent = message;
}
function showApp() {
$('#login-view').hidden = true;
$('#app-view').hidden = false;
$('#me-id').textContent = state.userId;
$('#me-id').title = state.userId;
$('#me-avatar').replaceWith(Object.assign(avatar(state.userId, localpart(state.userId)), { id: 'me-avatar' }));
}
function render() {
renderSidebar();
renderRoom();
}
function renderSidebar() {
const invites = $('#invite-list');
invites.replaceChildren();
if (!state.invites.size) invites.append(h('li', { class: 'none' }, 'No invites'));
for (const [roomId, inv] of state.invites) {
const name = inv.state?.find((e) => e.type === 't.room.name')?.content?.name || roomId;
invites.append(h('li', { class: 'invite' },
h('span', {}, name),
h('span', { class: 'mono' }, `from ${inv.inviter}`),
h('div', { class: 'row' },
h('button', { onclick: () => act(() => withCrypto(() => request('t.room.join', { room_id: roomId })).then(() => { state.current = roomId; render(); })) }, 'Accept'),
h('button', { class: 'secondary', onclick: () => act(() => request('t.room.leave', { room_id: roomId }).then(() => { state.invites.delete(roomId); renderSidebar(); })) }, 'Decline'),
)));
}
const list = $('#room-list');
list.replaceChildren();
if (!state.rooms.size) list.append(h('li', { class: 'none' }, 'No rooms yet'));
const sorted = [...state.rooms.values()].sort((a, b) => (b.timeline.at(-1)?.origin_server_ts ?? 0) - (a.timeline.at(-1)?.origin_server_ts ?? 0));
for (const room of sorted) {
list.append(h('li', {},
h('button', { 'aria-current': room.roomId === state.current ? 'true' : 'false', title: room.roomId, onclick: () => selectRoom(room.roomId) },
avatar(room.roomId, roomName(room)), h('span', { class: 'name' }, roomName(room)))));
}
}
function selectRoom(roomId) {
state.current = roomId;
render();
$('#message').focus();
}
function renderRoom() {
const room = state.rooms.get(state.current);
$('#no-room').hidden = Boolean(room);
$('#room-pane').hidden = !room;
if (!room) return;
$('#room-name').textContent = roomName(room);
$('#room-id').textContent = room.roomId;
renderTimeline({ stickToBottom: true, force: true });
renderMembers(room);
renderWarnings(room);
refreshTrust(joinedMembers(room).filter((u) => !state.trust.has(u)));
}
// ---------------------------------------------------------------------------
// Media
// ---------------------------------------------------------------------------
// Media is never fetched automatically: fetching would tell the server when
// you looked at a message.
function renderAttachment(ev, msg) {
const url = state.media.get(ev.event_id);
if (url && msg.msgtype === 't.image') return h('img', { class: 'attachment', src: url, alt: msg.text.replace(/^📎 /, '') });
if (url) return h('a', { href: url, download: msg.text.replace(/^📎 /, ''), class: 'attachment-link' }, 'Save file');
return h('button', { class: 'link attachment-load', onclick: () => act(() => fetchMedia(ev, msg)) },
msg.msgtype === 't.image' ? 'Show image' : 'Decrypt file');
}
const SAFE_IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
async function fetchMedia(ev, msg) {
const gen = state.sessionGen;
const ciphertext = await download(msg.file.url, { request, downloads: state.downloads });
const bytes = await decryptFile(msg.file, ciphertext, msg.info.size ?? ciphertext.length);
if (gen !== state.sessionGen) return;
const safeType = msg.msgtype === 't.image' && SAFE_IMAGE_MIMES.has(msg.info?.mimetype)
? msg.info.mimetype
: 'application/octet-stream';
const blob = new Blob([bytes], { type: safeType });
state.media.set(ev.event_id, URL.createObjectURL(blob));
renderTimeline();
}
async function sendFile(file) {
const room = state.rooms.get(state.current);
if (!room) return;
if (file.size > MAX_UPLOAD_BYTES) throw new Error('Files can be at most 10 MiB');
const bytes = new Uint8Array(await file.arrayBuffer());
const enc = await encryptFile(bytes);
const url = await upload(enc.ciphertext, { request, sendBinary: (b) => state.ws.send(b) });
const isImage = /^image\/(png|jpeg|gif|webp)$/.test(file.type);
const content = await encryptFor(room, 't.room.message', {
msgtype: isImage ? 't.image' : 't.file', body: file.name,
file: { ...enc.file, url }, info: { size: bytes.length, mimetype: file.type || 'application/octet-stream' },
}, { attachments: [url] });
await request('t.room.send', { room_id: room.roomId, type: 't.room.encrypted', txn_id: randomB64(12), content });
}
// ---------------------------------------------------------------------------
// Trust and verification
// ---------------------------------------------------------------------------
async function refreshTrust(users) {
const others = users.filter((u) => u !== state.userId);
if (!others.length) return;
const gen = state.sessionGen;
try {
await withCrypto(async (c) => {
await c.trackUsers(others);
for (const u of others) {
const t = await c.identityTrust(u);
if (gen === state.sessionGen) state.trust.set(u, t);
}
});
} catch { return; }
if (gen !== state.sessionGen) return;
const room = state.rooms.get(state.current);
if (room) { renderMembers(room); renderWarnings(room); }
}
// "This person's server says they hold a security key." Not a claim about a person.
function hardwareBadge(userId) {
const level = state.hardware.get(userId);
return level && Object.hasOwn(account.HW_LABEL, level) ? h('span', { class: `badge hw ${level}`, title: account.HW_TITLE[level] }, account.HW_LABEL[level]) : null;
}
function renderMembers(room) {
const vo = state.verifiedOnlyRooms.has(room.roomId);
$('#opt-verified-only').checked = vo;
$('#verified-only-badge').hidden = !vo;
const list = $('#member-list');
list.replaceChildren();
for (const u of joinedMembers(room)) {
const t = u === state.userId ? 'you' : (state.trust.get(u) ?? 'unknown');
list.append(h('li', { class: 'member' },
h('span', { class: 'mono' }, u),
h('span', { class: `badge ${t}` }, TRUST_LABEL[t] ?? t),
hardwareBadge(u),
t === 'changed' ? h('button', { class: 'link', onclick: () => approveIdentity(u) }, 'Accept change') : null,
u !== state.userId && t !== 'verified' && t !== 'none'
? h('button', { class: 'link', onclick: () => verifyUser(u) }, t === 'violation' ? 'Verify again' : 'Verify')
: null,
canModerate(room, 'kick', u)
? h('button', { class: 'link', onclick: () => act(() => request('t.room.kick', { room_id: room.roomId, user_id: u })) }, 'Kick')
: null,
canModerate(room, 'ban', u)
? h('button', { class: 'link', onclick: () => act(() => request('t.room.ban', { room_id: room.roomId, user_id: u })) }, 'Ban')
: null));
}
}
function renderWarnings(room) {
const box = $('#room-warnings');
box.replaceChildren();
for (const w of state.roomIntegrity.get(room.roomId) ?? []) {
box.append(h('p', { class: 'warning' }, `Room integrity warning: ${w}`));
}
const newlyJoined = state.newUnverified.get(room.roomId);
for (const u of newlyJoined ?? []) {
if (state.trust.get(u) === 'verified') { newlyJoined.delete(u); continue; }
box.append(h('p', { class: 'warning' },
`New unverified member ${u} joined this room. Verify them before sending sensitive messages. `,
h('button', { class: 'link', onclick: () => verifyUser(u) }, 'Verify'), ' ',
h('button', { class: 'link', onclick: () => { newlyJoined.delete(u); renderWarnings(room); } }, 'Dismiss')));
}
for (const u of joinedMembers(room)) {
const t = state.trust.get(u);
if (t === 'violation') {
box.append(h('p', { class: 'warning' },
`${u} has a new identity since you verified them. This room is blocked for sending until you verify them again. `,
h('button', { class: 'link', onclick: () => verifyUser(u) }, 'Verify again')));
} else if (t === 'changed') {
box.append(h('p', { class: 'warning' },
`${u}'s identity changed. If you didn't expect this, verify them before trusting their messages. `,
h('button', { class: 'link', onclick: () => approveIdentity(u) }, 'Accept'), ' ',
h('button', { class: 'link', onclick: () => verifyUser(u) }, 'Verify')));
}
}
}
async function approveIdentity(userId) {
await act(async () => {
await withCrypto((c) => c.approveIdentity(userId));
await refreshTrust([userId]);
});
}
async function verifyUser(userId) {
try {
const v = await withCrypto((c) => c.startVerification(userId));
showVerification(v, { incoming: false });
} catch (e) {
toast(e.message);
}
}
function showVerification(v, { incoming }) {
state.verification = { v, incoming, starting: false };
v.onChange = () => renderVerification();
renderVerification();
}
function closeVerification() {
$('#verify-dialog').hidden = true;
state.verification = null;
}
function renderVerification() {
const current = state.verification;
if (!current) return;
const { v, incoming } = current;
const st = v.state();
const body = $('#verify-body');
$('#verify-dialog').hidden = false;
body.replaceChildren(h('h3', { id: 'verify-title' }, `Verify ${v.userId}`));
const cancel = (label) => h('button', { class: 'secondary', onclick: () => act(async () => { await v.cancel(); closeVerification(); }) }, label);
if (st === 'waiting') {
body.append(
h('p', {}, incoming ? `${v.userId} wants to verify with you.` : `Waiting for ${v.userId} to accept…`),
incoming
? h('div', { class: 'row' }, h('button', { onclick: () => act(() => v.accept()) }, 'Accept'), cancel('Decline'))
: cancel('Cancel'));
} else if (st === 'ready') {
body.append(h('p', {}, 'Accepted. Preparing emoji…'));
if (!incoming && !current.starting) {
current.starting = true;
act(() => v.start());
}
} else if (st === 'emoji') {
body.append(
h('p', {}, 'Check that the other person sees the same emoji, in the same order. Compare them in person or over a call, not in this chat.'),
h('ol', { class: 'emoji' }, v.emoji().map((e) => h('li', {}, h('span', { class: 'symbol' }, e.symbol), h('span', { class: 'label' }, e.description)))),
h('div', { class: 'row' }, h('button', { onclick: () => act(() => v.confirm()) }, 'They match'), cancel("They don't match")));
} else if (st === 'confirmed') {
body.append(h('p', {}, 'Waiting for the other side to confirm…'));
} else if (st === 'done') {
body.append(h('p', { class: 'verified' }, `✓ ${v.userId} is verified.`), h('button', { onclick: closeVerification }, 'Done'));
refreshTrust([v.userId]);
} else {
body.append(h('p', {}, 'Verification was cancelled.'), h('button', { onclick: closeVerification }, 'Close'));
}
}
function renderTimeline({ stickToBottom = false, force = false } = {}) {
const room = state.rooms.get(state.current);
if (!room) return;
const box = $('#timeline');
const nearBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 80;
const ol = $('#events');
ol.replaceChildren();
let prev = null; // the last message shown, to group a run from one sender
for (const ev of room.timeline) {
if (ev.state_key !== undefined) {
const text = describeState(ev);
if (text) { ol.append(h('li', { class: 'system' }, text)); prev = null; }
continue;
}
if (ev.type !== 't.room.encrypted') continue; // redactions render through their targets
const msg = decodeMessage(ev);
const own = ev.sender === state.userId;
const time = new Date(ev.origin_server_ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const cont = prev && prev.sender === ev.sender && ev.origin_server_ts - prev.origin_server_ts < 5 * 60_000;
prev = ev;
ol.append(h('li', { class: `msg ${own ? 'own' : ''} ${cont ? 'cont' : ''} ${msg.kind}` },
own ? null : avatar(ev.sender, localpart(ev.sender)),
h('div', { class: 'meta' },
h('span', { class: 'sender', title: ev.sender }, localpart(ev.sender)),
hardwareBadge(ev.sender),
Number.isFinite(ev.origin_server_ts) ? h('time', { datetime: new Date(ev.origin_server_ts).toISOString() }, time) : null,
ev.unsigned?.expires_ts ? h('span', { class: 'expiry' }, relativeExpiry(ev.unsigned.expires_ts)) : null,
msg.trust && msg.trust !== 'verified'
? h('span', { class: `badge ${msg.trust}`, title: msg.trustMessage ?? '' }, msg.trust === 'warning' ? '⚠ warning' : 'unverified')
: null,
own && msg.kind !== 'gone'
? h('button', { class: 'link delete', onclick: () => deleteMessage(ev) }, 'Delete')
: null),
h('div', { class: 'body' }, msg.text),
msg.file ? renderAttachment(ev, msg) : null));
}
$('#load-older').hidden = !room.more;
if (force || (stickToBottom && nearBottom)) box.scrollTop = box.scrollHeight;
renderSidebar();
}
// ---------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------
async function act(fn) {
try { await fn(); } catch (e) { toast(e.message); }
}
async function loadOlder() {
const room = state.rooms.get(state.current);
if (!room) return;
const first = room.timeline[0];
const res = await request('t.room.messages', { room_id: room.roomId, limit: 50, ...(first ? { before: first.event_id } : {}) });
const box = $('#timeline');
const fromBottom = box.scrollHeight - box.scrollTop;
for (const ev of [...res.chunk].reverse()) addEvent(room, ev, { prepend: true });
room.more = Boolean(res.before);
renderTimeline();
box.scrollTop = box.scrollHeight - fromBottom;
}
async function deleteMessage(ev) {
await act(() => request('t.room.send', {
room_id: ev.room_id, type: 't.room.redaction', txn_id: randomB64(12), content: { redacts: ev.event_id },
}));
}
async function signIn(action) {
const username = $('#username').value.trim();
const password = $('#password').value;
state.url = $('#gateway-url').value.trim();
$('#login-error').textContent = '';
try {
if (state.ws?.readyState !== WebSocket.OPEN) await openSocket();
// OPAQUE: the password never leaves this browser.
const remember = $('#remember').checked;
const passphrase = $('#device-pass').value;
if (remember && passphrase.length < 10) throw new Error('Choose a device passphrase of at least 10 characters');
const inviteToken = $('#invite-token')?.value.trim() || undefined;
const auth = await (action === 'register'
? opaque.register(request, state.serverName, username, password, { inviteToken })
: opaque.login(request, state.serverName, username, password));
if (auth.second_factor) {
// The password was right; this account also wants one of its keys.
$('#login-error').textContent = 'Touch your security key…';
const credential = await webauthn.get(auth.second_factor.options);
Object.assign(auth, await request('t.webauthn.login', { ticket: auth.second_factor.ticket, credential }));
$('#login-error').textContent = '';
}
state.pendingPassphrase = remember ? passphrase : null;
state.token = auth.access_token;
state.userId = auth.user_id;
// For identity recovery and the backup key; cleared once used.
state.pendingExportKey = auth.exportKey;
$('#password').value = '';
$('#device-pass').value = '';
if ($('#invite-token')) $('#invite-token').value = '';
send({ op: 'identify', body: { access_token: state.token } });
} catch (e) {
$('#login-error').textContent = e.message;
}
}
// Forget everything held in memory. `keepDevice` leaves the saved keys and the
// sealed sign-in on disk (Lock); otherwise they are deleted too.
function leave({ keepDevice }) {
account.stopTimers();
state.sessionGen++; // in-flight decrypts, downloads and trust checks are dropped
state.intentionalClose = true;
clearTimeout(state.heartbeat);
clearTimeout(state.reconnectTimer);
state.ws?.close();
state.crypto?.close();
if (!keepDevice) deleteCryptoStore(state.storeName);
closeVerification();
for (const url of state.media.values()) URL.revokeObjectURL(url);
for (const k of ['trust', 'hardware', 'backed', 'verifiedOnlyRooms', 'roomIntegrity', 'newUnverified',
'decrypted', 'decrypting', 'media', 'downloads', 'rooms', 'invites']) state[k].clear();
Object.assign(state, {
url: DEFAULT_GATEWAY, token: null, userId: null, serverName: null, sessionId: null, reconnectTimer: null,
crypto: null, cryptoReady: null, cryptoUp: false, pendingExportKey: null, pendingPassphrase: null,
backupKey: null, backupDay: null, backupParts: 0, keysInfo: null, devicesList: [],
deviceId: null, storeName: null, storePass: null, deviceHandle: null, seenLoaded: null, current: null,
});
clearSession();
// Decrypted text and typed secrets must not stay in the page behind a lock screen.
for (const sel of ['#events', '#member-list', '#room-list', '#invite-list', '#room-warnings', '#toasts', '#me-id']) $(sel).replaceChildren();
for (const sel of ['#message', '#settings-password', '#new-password', '#new-password2', '#key-nickname', '#create-name', '#join-id', '#invite-user']) $(sel).value = '';
$('#room-name').textContent = '';
$('#room-id').textContent = '';
$('#room-pane').hidden = true;
$('#no-room').hidden = false;
$('#settings-dialog').hidden = true;
$('#app-view').hidden = true;
}
function signedOut(message) {
leave({ keepDevice: false });
device.wipe(); // the sealed sign-in, if any, and every local preference
showLogin(message);
}
async function logout() {
try { await request('t.logout'); } catch { /* closing anyway */ }
state.intentionalClose = true;
state.ws?.close();
signedOut('');
}
// ---------------------------------------------------------------------------
// Wiring
// ---------------------------------------------------------------------------
function wire() {
account.init({
state, request, toast, h, $, leave, showLogin,
clearSession, saveSession,
sendNoop: () => send({ op: 'noop' }),
resume: () => { state.intentionalClose = false; showApp(); reconnect(); },
retryDecrypt: () => {
for (const [id, d] of state.decrypted) if (d.retry) state.decrypted.delete(id);
if (state.current) renderTimeline();
},
refreshBadges: () => {
const room = state.rooms.get(state.current);
if (room) renderMembers(room);
if (state.current) renderTimeline();
},
});
$('#opt-verified-only')?.addEventListener('change', (e) => {
const room = state.rooms.get(state.current);
if (!room) return;
if (e.target.checked) state.verifiedOnlyRooms.add(room.roomId);
else state.verifiedOnlyRooms.delete(room.roomId);
$('#verified-only-badge').hidden = !e.target.checked;
saveSession();
if (state.deviceHandle) device.update(state.deviceHandle, { verifiedOnly: [...state.verifiedOnlyRooms] }).catch((err) => toast(err.message));
withCrypto((c) => c.invalidateRoomSession(room.roomId)).catch(() => {});
toast(e.target.checked ? 'Verified-only sending enabled for this room.' : 'Verified-only sending disabled for this room.');
});
$('#login-form').addEventListener('submit', (e) => {
e.preventDefault();
signIn(e.submitter?.dataset.action ?? 'login');
});
$('#logout').addEventListener('click', logout);
$('#create-form').addEventListener('submit', (e) => {
e.preventDefault();
const name = $('#create-name').value.trim();
act(async () => {
const { room_id } = await request('t.room.create', { join_rule: $('#create-public').checked ? 'public' : 'invite' });
state.current = room_id;
// The creation events go out before this client knows the room: load its full state.
const full = await request('t.room.state', { room_id });
const room = ensureRoom(room_id);
for (const ev of full.state) room.state.set(`${ev.type}|${ev.state_key}`, ev);
await checkRoomIntegrity(room);
if (name) await setEncryptedState(room_id, 't.room.name', '', { name });
$('#create-name').value = '';
e.target.closest('details').open = false;
render();
});
});
$('#join-form').addEventListener('submit', (e) => {
e.preventDefault();
const roomId = $('#join-id').value.trim();
act(async () => {
await withCrypto(() => request('t.room.join', { room_id: roomId }));
state.current = roomId;
$('#join-id').value = '';
e.target.closest('details').open = false;
render();
});
});
$('#invite-form').addEventListener('submit', (e) => {
e.preventDefault();
const userId = $('#invite-user').value.trim();
act(async () => {
await request('t.room.invite', { room_id: state.current, user_id: userId });
$('#invite-user').value = '';
toast(`Invited ${userId}`);
});
});
$('#leave-room').addEventListener('click', () => act(() => request('t.room.leave', { room_id: state.current })));
$('#room-id').addEventListener('click', () => act(async () => {
await navigator.clipboard.writeText(state.current);
toast('Room ID copied');
}));
$('#load-older').addEventListener('click', () => act(loadOlder));
$('#attach').addEventListener('click', () => $('#file-input').click());
$('#file-input').addEventListener('change', (e) => {
const file = e.target.files?.[0];
e.target.value = '';
if (file) act(() => sendFile(file));
});
const message = $('#message');
$('#composer').addEventListener('submit', (e) => {
e.preventDefault();
const text = message.value.trim();
const room = state.rooms.get(state.current);
if (!text || !room) return;
message.value = '';
message.style.height = '';
act(async () => {
const content = await encryptFor(room, 't.room.message', { msgtype: 't.text', body: text });
await request('t.room.send', { room_id: room.roomId, type: 't.room.encrypted', txn_id: randomB64(12), content });
});
});
message.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
e.preventDefault();
$('#composer').requestSubmit();
}
});
message.addEventListener('input', () => {
message.style.height = '';
message.style.height = `${Math.min(message.scrollHeight, 160)}px`;
});
// Keep expiry labels honest and prune expired replay/session entries.
setInterval(() => {
state.crypto?.pruneExpiredSessions();
if (state.current) renderTimeline();
}, 60_000);
}
function start() {
wire();
const saved = loadSession();
if (saved?.token) {
Object.assign(state, {
url: saved.url, token: saved.token, userId: saved.userId,
deviceId: saved.deviceId ?? null, storeName: saved.storeName ?? null, storePass: saved.storePass ?? null,
backupKey: saved.backupKey ? Uint8Array.from(atob(saved.backupKey), (c) => c.charCodeAt(0)) : null,
seenLoaded: { seen: saved.seen ?? [], sessions: saved.sessions ?? [] },
});
for (const r of saved.verifiedOnly ?? []) state.verifiedOnlyRooms.add(r);
showApp();
reconnect();
} else if (device.hasDevice()) {
account.showUnlock();
} else {
// A page the server hosts connects only back to that server: a link must not point it elsewhere.
const fromQuery = HOSTED ? null : new URLSearchParams(location.search).get('gateway');
if (fromQuery) state.url = fromQuery;
showLogin();
}
}
start();
// Taper development web client.
//
// Talks to the Taper WebSocket gateway directly, with no build step. Messages
// are end-to-end encrypted with Olm/Megolm (vodozemac, via
// @matrix-org/matrix-sdk-crypto-wasm); see crypto.js for the room version 13
// checks layered on top.
import * as sdk from './node_modules/@matrix-org/matrix-sdk-crypto-wasm/index.mjs';
import { TaperCrypto, padJson, verifyRoomState } from './crypto.js';
import { solveChallenge } from './pow.js';
import * as opaque from './opaque.js';
import * as account from './account.js';
import * as webauthn from './webauthn.js';
import * as device from './device.js';
import { encryptFile, decryptFile, upload, download, parseBinaryFrame, BIN_DOWNLOAD } from './media.js';
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
// When a Taper server hosts this client under its secret gateway path, it
// marks the page, and the client connects back to that same path.
const HOSTED = document.querySelector('meta[name="taper-gateway"]')?.content === 'same-origin';
const DEFAULT_GATEWAY = HOSTED
? `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}${location.pathname.replace(/\/(index\.html)?$/, '')}`
: 'ws://127.0.0.1:8080/_taper/gateway/v1';
const STORAGE_KEY = 'taper-dev-session';
const REQUEST_TIMEOUT_MS = 15_000;
// ---------------------------------------------------------------------------
// Small DOM helpers. User-controlled text only ever goes in via text nodes.
// ---------------------------------------------------------------------------
const $ = (sel) => document.querySelector(sel);
function h(tag, props = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value === undefined || value === null || value === false) continue;
if (key === 'class') node.className = value;
else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);
else node.setAttribute(key, value === true ? '' : value);
}
for (const child of children.flat()) {
if (child === null || child === undefined || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
function toast(message) {
console.info(`[taper] ${message}`);
const t = h('div', { class: 'toast' }, message);
$('#toasts').append(t);
setTimeout(() => t.remove(), 5000);
}
function randomB64(bytes) {
const buf = crypto.getRandomValues(new Uint8Array(bytes));
return btoa(String.fromCharCode(...buf)).replace(/=+$/, '');
}
const localpart = (userId) => (userId ?? '').replace(/^@/, '').split(':')[0];
// A colored circle with an initial. The hue comes from the ID, so a person
// keeps their color everywhere, with nothing fetched from a server.
function avatar(id, label = id) {
let hash = 0;
for (const ch of id ?? '') hash = (hash * 31 + ch.codePointAt(0)) >>> 0;
const initial = [...(label ?? '').replace(/^[@!#]/, '')][0]?.toUpperCase() ?? '?';
return h('span', { class: `avatar hue-${hash % 8}`, 'aria-hidden': 'true' }, initial);
}
function relativeExpiry(ts) {
const ms = ts - Date.now();
if (ms <= 0) return 'expired';
const d = Math.floor(ms / 86_400_000);
const hrs = Math.floor((ms % 86_400_000) / 3_600_000);
if (d > 0) return `expires in ${d}d ${hrs}h`;
const m = Math.floor((ms % 3_600_000) / 60_000);
return hrs > 0 ? `expires in ${hrs}h ${m}m` : `expires in ${m}m`;
}
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
const state = {
url: DEFAULT_GATEWAY,
token: null,
userId: null,
sessionId: null,
seq: 0,
ws: null,
heartbeat: null,
helloWaiters: [],
pending: new Map(),
nextId: 1,
reconnectDelay: 1000,
reconnectTimer: null,
intentionalClose: false,
sessionGen: 0, // bumped by leave(): async work from before a lock is dropped