summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js
blob: a27522d1b50108d8cb1b5c38e3ab8e51acd5d033 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/**
 * MeshBay Browser Key Management — keyderive.js
 *
 * Web registration flow (avoids algorithm mismatch with Python Argon2id):
 *
 * REGISTRATION:
 *   1. Browser generates RANDOM Ed25519 + X25519 keypairs via WebCrypto
 *   2. Bundle (sk_ed || sk_x) is encrypted with AES-256-GCM
 *      using a key derived from password via PBKDF2-SHA512
 *   3. Encrypted bundle + public keys sent to hub for storage
 *
 * LOGIN (new device):
 *   1. Hub returns the encrypted bundle
 *   2. Browser decrypts it locally with the password
 *   3. Private keys loaded into memory (never leave the browser)
 *
 * Password change: re-encrypt bundle with new password-derived key.
 *
 * Keys never leave the browser in cleartext.
 * Hub stores: public keys + encrypted bundle (cannot read private keys).
 */

const PBKDF2_ITERATIONS = 600000;  // OWASP 2023 recommendation for PBKDF2-SHA512
const HUB = '';                     // same origin

// ── Auth key derivation (password split) ──────────────────────────────────────

/**
 * Derive an auth key from password + username using PBKDF2-SHA512.
 * This key is sent to the hub for authentication — the raw password never leaves the browser.
 * Uses a different salt domain than deriveEncryptionKey (bundle key), so the two
 * derived values are cryptographically independent.
 */
async function deriveAuthKey(password, username) {
  const enc = new TextEncoder();
  const km = await crypto.subtle.importKey(
    'raw', enc.encode(password), 'PBKDF2', false, ['deriveBits']);
  const salt = await crypto.subtle.digest(
    'SHA-256', enc.encode(`meshbay:auth:v1:${username}`));
  const bits = await crypto.subtle.deriveBits(
    { name: 'PBKDF2', hash: 'SHA-512', salt, iterations: PBKDF2_ITERATIONS },
    km, 256);
  return btoa(String.fromCharCode(...new Uint8Array(bits)));
}

// ── Key generation ────────────────────────────────────────────────────────────

/**
 * Generate random Ed25519 + X25519 keypairs using WebCrypto.
 * Returns raw bytes for both (not CryptoKey objects, for easier serialisation).
 */
async function generateKeypairs() {
  // Ed25519 (signing)
  const edKey = await crypto.subtle.generateKey(
    { name: 'Ed25519' }, true, ['sign', 'verify']);
  const skEdRaw = await crypto.subtle.exportKey('pkcs8', edKey.privateKey);
  const pkEdRaw = await crypto.subtle.exportKey('spki',  edKey.publicKey);

  // X25519 (key agreement)
  const xKey = await crypto.subtle.generateKey(
    { name: 'X25519' }, true, ['deriveBits']);
  const skXRaw = await crypto.subtle.exportKey('pkcs8', xKey.privateKey);
  const pkXRaw = await crypto.subtle.exportKey('spki',  xKey.publicKey);

  return { skEdRaw, pkEdRaw, skXRaw, pkXRaw };
}

// ── Password → AES key ────────────────────────────────────────────────────────

// Argon2id parameters for the keypair bundle.
//
// This is the one KDF in the browser that guards something an adversary can take
// away and attack at leisure: the bundle is stored on every node whose group its
// owner joins (finding C4). PBKDF2 was the wrong tool — it is compute-only, which
// is exactly what a GPU is good at, so 600k iterations bought far less than the
// wall-clock time suggested.
//
// 128 MB / t=3 / p=1 measured at ~640 ms through this WASM build on a desktop.
// Memory is the lever, not time: each guess must hold 128 MB, so a 24 GB card
// fits ~187 in parallel and its bandwidth caps it near 2k guesses/s, against no
// ceiling at all for PBKDF2. 256 MB would double that again at ~1.3 s, which is
// too much to ask of a phone for something paid at every sign-in.
const ARGON2_MEM_KIB = 131072;   // 128 MB
const ARGON2_TIME    = 3;
const ARGON2_LANES   = 1;

// Bundles written before this carry no marker and are read with the old KDF.
// They are re-encrypted the first time their owner signs in (see upgradeBundle).
const BUNDLE_V2_MAGIC = 'MBK2';

function _argon2() {
  const a = (typeof window !== 'undefined' && window.argon2) || globalThis.argon2;
  if (!a) throw new Error('Argon2 unavailable — vendor/argon2.min.js did not load');
  return a;
}

/** Legacy: PBKDF2-SHA512. Kept to read bundles written before the change. */
async function deriveEncryptionKeyV1(password, username) {
  const enc   = new TextEncoder();
  const km    = await crypto.subtle.importKey(
    'raw', enc.encode(password), 'PBKDF2', false, ['deriveKey']);
  const salt  = await crypto.subtle.digest(
    'SHA-256', enc.encode(`meshbay:bundle:v1:${username}`));
  return crypto.subtle.deriveKey(
    { name: 'PBKDF2', hash: 'SHA-512', salt, iterations: PBKDF2_ITERATIONS },
    km,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt'],
  );
}

/**
 * Derive the bundle key with Argon2id.
 *
 * The salt stays deterministic and domain-separated per user, as before: it is
 * what lets the key be derived once at sign-in and kept, instead of holding the
 * passphrase in memory to re-derive it whenever a bundle turns up. It is unique
 * per account, so it does what a salt is for — no shared precomputation.
 */
async function deriveEncryptionKey(password, username) {
  const enc  = new TextEncoder();
  const salt = new Uint8Array(await crypto.subtle.digest(
    'SHA-256', enc.encode(`meshbay:bundle:v2:${username}`))).slice(0, 16);
  const out = await _argon2().hash({
    pass: password, salt,
    time: ARGON2_TIME, mem: ARGON2_MEM_KIB, parallelism: ARGON2_LANES,
    hashLen: 32, type: _argon2().ArgonType.Argon2id,
  });
  return crypto.subtle.importKey(
    'raw', out.hash, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
}

// ── Bundle encryption ─────────────────────────────────────────────────────────

/**
 * Encrypt the keypair bundle with the password-derived AES key.
 * Bundle format: JSON { skEd: base64(pkcs8), skX: base64(pkcs8) }
 */
async function encryptBundle(skEdRaw, skXRaw, password, username) {
  const aesKey = await deriveEncryptionKey(password, username);
  return encryptBundleWithKey(skEdRaw, skXRaw, aesKey);
}

/** Same, when the key was already derived at sign-in. Always writes v2. */
async function encryptBundleWithKey(skEdRaw, skXRaw, aesKey) {
  const nonce  = crypto.getRandomValues(new Uint8Array(12));
  const data   = new TextEncoder().encode(JSON.stringify({
    skEd: btoa(String.fromCharCode(...new Uint8Array(skEdRaw))),
    skX:  btoa(String.fromCharCode(...new Uint8Array(skXRaw))),
  }));
  const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, aesKey, data);
  // base64( "MBK2" || nonce || ciphertext ). The marker is what tells a reader
  // which KDF produced the key, so old bundles stay readable and new ones are
  // never fed to the old derivation.
  const magic = new TextEncoder().encode(BUNDLE_V2_MAGIC);
  const out = new Uint8Array(magic.length + nonce.length + ct.byteLength);
  out.set(magic);
  out.set(nonce, magic.length);
  out.set(new Uint8Array(ct), magic.length + nonce.length);
  return btoa(String.fromCharCode(...out));
}

function bundleVersion(bundleB64) {
  try {
    return atob(bundleB64).startsWith(BUNDLE_V2_MAGIC) ? 2 : 1;
  } catch { return 1; }
}

/**
 * Decrypt a keypair bundle. Throws if password is wrong.
 */
async function decryptBundle(bundleB64, password, username) {
  const key = bundleVersion(bundleB64) === 2
    ? await deriveEncryptionKey(password, username)
    : await deriveEncryptionKeyV1(password, username);
  return decryptBundleWithKey(bundleB64, key);
}

// ── Registration ──────────────────────────────────────────────────────────────

/**
 * Full registration flow:
 * 1. Generate random keypairs
 * 2. Encrypt bundle with password
 * 3. POST to hub (public keys only — no keypair bundle)
 * 4. Store encrypted bundle locally for backup to node on first connect
 *
 * Returns the raw private keys for immediate use after registration.
 */
async function registerUser(username, email, password) {
  // No keypair here any more. Identity keys are per node: one is generated the
  // first time this account joins a given node, encrypted under the passphrase,
  // and left with that node. So an operator who cracks what sits on their own
  // disk holds a key that is worthless anywhere else — and on their own node,
  // one that unlocks nothing they did not already have.
  //
  // It also means the hub stores no user key to publish, which is what H3 read.
  const authKey = await deriveAuthKey(password, username);

  const resp = await fetch(`${HUB}/v1/users/register`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, email, auth_key: authKey }),
  });

  if (!resp.ok) throw new Error(`Registration failed: ${await resp.text()}`);
  return { registered: true };
}

/**
 * A fresh identity for one node, encrypted under the passphrase-derived key.
 *
 * Returns { skEdB64, skXB64, pkXB64, bundleEnc } — the bundle goes to that node
 * and nowhere else, and is what any other browser fetches to become the same
 * person there.
 */
async function generateNodeIdentity(bundleKey) {
  const { skEdRaw, pkEdRaw, skXRaw, pkXRaw } = await generateKeypairs();
  const b64 = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf)));
  const pkXCrypto = await crypto.subtle.importKey('spki', pkXRaw, { name: 'X25519' }, true, []);
  const pkXBytes = new Uint8Array(await crypto.subtle.exportKey('raw', pkXCrypto));
  return {
    skEdB64: b64(skEdRaw),
    skXB64: b64(skXRaw),
    pkXB64: b64(pkXBytes),
    bundleEnc: await encryptBundleWithKey(skEdRaw, skXRaw, bundleKey.v2 || bundleKey),
  };
}

/**
 * Decrypt a keypair bundle using a pre-derived AES-256 CryptoKey.
 * Used when the bundle is fetched from the node (bundleKey was derived at login).
 */
async function decryptBundleWithKey(bundleB64, aesKeyOrPair) {
  const v2  = bundleVersion(bundleB64) === 2;
  // Callers derive both keys at sign-in and pass the pair, because which one a
  // bundle needs is only known once it has been read — and the passphrase is
  // deliberately not kept around to derive the other one later.
  const key = (aesKeyOrPair && aesKeyOrPair.v2)
    ? (v2 ? aesKeyOrPair.v2 : aesKeyOrPair.v1)
    : aesKeyOrPair;
  const raw   = Uint8Array.from(atob(bundleB64), c => c.charCodeAt(0));
  const off   = v2 ? BUNDLE_V2_MAGIC.length : 0;
  const nonce = raw.slice(off, off + 12);
  const ct    = raw.slice(off + 12);
  const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, key, ct);
  return JSON.parse(new TextDecoder().decode(plain));
}

/**
 * Login and recover private keys.
 *
 * If localStorage has a keypair bundle (new registration, not yet pushed to node),
 * decrypts it and returns the keys + encrypted bundle for push to node.
 * Otherwise returns bundleKey so the caller can fetch from node during handshake.
 */
async function loginAndRecover(username, password) {
  const authKey = await deriveAuthKey(password, username);

  const resp = await fetch(`${HUB}/v1/users/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, auth_key: authKey }),
  });

  if (!resp.ok) throw new Error(`Login failed: ${await resp.text()}`);

  const data   = await resp.json();
  const result = {
    accessToken:  data.access_token,
    refreshToken: data.refresh_token,
    // Both, so a bundle written before the KDF changed can still be opened —
    // and re-written with the new one on the next backup.
    bundleKey: {
      v2: await deriveEncryptionKey(password, username),
      v1: await deriveEncryptionKeyV1(password, username),
    },
  };

  // Nothing else to recover at sign-in. Identity keys belong to a node, so they
  // are fetched from the node being connected to (or generated there on a first
  // join) — see transport.js. All that is needed here is the key that opens them.
  return result;
}

// regenerateKeys() removed. Rotating an identity is now per node: the operator
// runs `meshbay-node member unpin <user>` and issues a fresh code. A hub call
// that silently changed what every node believed about someone was the wrong
// shape for this.

async function signBytes(skEdPkcs8B64, message) {
  const skRaw = Uint8Array.from(atob(skEdPkcs8B64), c => c.charCodeAt(0));
  const sk = await crypto.subtle.importKey(
    'pkcs8', skRaw, { name: 'Ed25519' }, false, ['sign']);
  const sig = await crypto.subtle.sign('Ed25519', sk, message);
  return btoa(String.fromCharCode(...new Uint8Array(sig)));
}

window.MeshBayKeys = {
  registerUser, loginAndRecover, generateNodeIdentity, generateKeypairs, signBytes,
  deriveAuthKey, decryptBundleWithKey, encryptBundleWithKey, bundleVersion,
};