taper / client /device.js
abr00kx's picture
Round 2 security fixes
b6ae8c3 verified
Raw History Blame Contribute Delete
6.95 kB
// A device that stays signed in ("keep this device signed in").
//
// Nothing about the account is stored in the clear. The access token, the
// gateway address, the crypto store's passphrase and the backup key are
// sealed (AES-256-GCM) under a key made from a device passphrase the user
// chooses (PBKDF2-HMAC-SHA-256, 600,000 iterations). Without the passphrase
// the record is noise, and there is no way to recover it: forgetting the
// passphrase means signing in again, which is the point.
//
// The server never sees any of this. Wiping removes the record and the
// crypto store. There is no automatic wipe after failed attempts: an
// attacker who copies the record can guess offline anyway, so it would only
// let someone else destroy your data.
const RECORD = 'taper-device';
const ITERATIONS = 600_000;
const MIN_PASSPHRASE = 10;
const AAD = new TextEncoder().encode('taper-device|v1');
const STORE_PREFIX = 'taper-crypto-';
const SEEN_PREFIX = 'taper-seen-';
// Chunked: String.fromCharCode(...bytes) throws on large arrays, and the replay
// table grows with every message.
const b64 = (bytes) => {
let s = '';
for (let i = 0; i < bytes.length; i += 8192) s += String.fromCharCode(...bytes.subarray(i, i + 8192));
return btoa(s);
};
const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
async function wrapKey(passphrase, salt, iterations) {
const base = await crypto.subtle.importKey('raw', new TextEncoder().encode(passphrase.normalize('NFKC')), 'PBKDF2', false, ['deriveKey']);
return crypto.subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
}
/** Whether a sealed device record exists here. */
export function hasDevice() {
try { return Boolean(localStorage.getItem(RECORD)); } catch { return false; }
}
async function write(key, salt, iterations, payload) {
const iv = crypto.getRandomValues(new Uint8Array(12));
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: AAD }, key, new TextEncoder().encode(JSON.stringify(payload))));
localStorage.setItem(RECORD, JSON.stringify({ v: 1, kdf: 'PBKDF2-SHA256', iter: iterations, salt: b64(salt), iv: b64(iv), ct: b64(ct) }));
}
/**
* Seal `payload` ({url, userId, deviceId, storeName, storePass, token,
* backupKey}) under a passphrase and keep it. Returns a handle that re-saves
* the record while this device is unlocked.
*/
export async function remember(passphrase, payload) {
if (typeof passphrase !== 'string' || passphrase.length < MIN_PASSPHRASE) throw new Error(`The device passphrase needs at least ${MIN_PASSPHRASE} characters`);
const salt = crypto.getRandomValues(new Uint8Array(16));
const key = await wrapKey(passphrase, salt, ITERATIONS);
await write(key, salt, ITERATIONS, payload);
return { key, salt, iterations: ITERATIONS, payload };
}
/** Open the record. Throws 'Wrong passphrase' if it doesn't open. */
export async function unlock(passphrase) {
let rec;
try { rec = JSON.parse(localStorage.getItem(RECORD)); } catch { rec = null; }
if (!rec || rec.v !== 1 || rec.kdf !== 'PBKDF2-SHA256') throw new Error('This device has no saved sign-in');
// Never trust a stored cost below what we write: it would make guessing cheap.
if (!Number.isInteger(rec.iter) || rec.iter < ITERATIONS) throw new Error('This device\'s saved sign-in was made with weak settings; wipe it and sign in again');
const salt = unb64(rec.salt);
const key = await wrapKey(passphrase, salt, rec.iter);
try {
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(rec.iv), additionalData: AAD }, key, unb64(rec.ct));
return { key, salt, iterations: rec.iter, payload: JSON.parse(new TextDecoder().decode(pt)) };
} catch {
throw new Error('Wrong passphrase');
}
}
/** Save changed contents (a new backup key after a password change). */
export async function update(handle, changes) {
handle.payload = { ...handle.payload, ...changes };
await write(handle.key, handle.salt, handle.iterations, handle.payload);
}
// The replay table, kept for as long as the device keeps its keys, sealed
// under the crypto store's own passphrase (which is itself sealed above).
async function seenKey(storePass) {
const base = await crypto.subtle.importKey('raw', new TextEncoder().encode(storePass), 'HKDF', false, ['deriveKey']);
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('taper-seen-v1'), info: new Uint8Array() }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
}
export async function saveSeen(deviceId, storePass, list, sessions = []) {
try {
const iv = crypto.getRandomValues(new Uint8Array(12));
const data = { seen: list, sessions };
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(deviceId) }, await seenKey(storePass), new TextEncoder().encode(JSON.stringify(data))));
localStorage.setItem(SEEN_PREFIX + deviceId, JSON.stringify({ iv: b64(iv), ct: b64(ct) }));
return true;
} catch {
return false; // storage full or unavailable: the caller says so
}
}
export async function loadSeen(deviceId, storePass) {
try {
const rec = JSON.parse(localStorage.getItem(SEEN_PREFIX + deviceId));
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(rec.iv), additionalData: new TextEncoder().encode(deviceId) }, await seenKey(storePass), unb64(rec.ct));
const parsed = JSON.parse(new TextDecoder().decode(pt));
if (Array.isArray(parsed)) return { seen: parsed, sessions: [] };
return { seen: Array.isArray(parsed?.seen) ? parsed.seen : [], sessions: Array.isArray(parsed?.sessions) ? parsed.sessions : [] };
} catch { return { seen: [], sessions: [] }; }
}
/** Remove everything this device kept: the sealed record, preferences, replay table, sessionStorage and every crypto store. */
export async function wipe() {
try {
localStorage.removeItem(RECORD);
for (const k of ['taper-backup', 'taper-idle-ms', 'taper-cover-traffic']) localStorage.removeItem(k);
for (let i = localStorage.length - 1; i >= 0; i--) {
const k = localStorage.key(i);
if (k?.startsWith(SEEN_PREFIX)) localStorage.removeItem(k);
}
} catch { /* nothing stored, or not allowed */ }
try { sessionStorage.clear(); } catch { /* ignore */ }
try {
// Settles once deleted, or once blocked by a connection still open (the browser finishes when it closes).
const gone = (name) => new Promise((resolve) => Object.assign(indexedDB.deleteDatabase(name), { onsuccess: resolve, onerror: resolve, onblocked: resolve }));
await Promise.all((await indexedDB.databases()).filter((db) => db.name?.startsWith(STORE_PREFIX)).map((db) => gone(db.name)));
} catch { /* not supported: the store is encrypted with a passphrase that is now gone */ }
}