var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { jweEncrypt, hkdf } from './crypto'; import { hexToUint8, uint8ToHex } from './utils'; function randomKey() { return __awaiter(this, void 0, void 0, function* () { // The key is displayed in base32 'Crockford' so the length should be // divisible by (5 bits per character) and (8 bits per byte). // 20 bytes == 160 bits == 32 base32 characters const recoveryKey = yield crypto.getRandomValues(new Uint8Array(20)); // Flip bits to set first char to base32 'A' as a version identifier. // Why 'A'? https://github.com/mozilla/fxa-content-server/pull/6323#discussion_r201211711 recoveryKey[0] = 0x50 | (0x07 & recoveryKey[0]); return recoveryKey; }); } export function generateRecoveryKey(uid, keys, forTestingOnly) { return __awaiter(this, void 0, void 0, function* () { const recoveryKey = (forTestingOnly === null || forTestingOnly === void 0 ? void 0 : forTestingOnly.testRecoveryKey) || (yield randomKey()); const encoder = new TextEncoder(); const salt = hexToUint8(uid); const encryptionKey = yield hkdf(recoveryKey, salt, encoder.encode('fxa recovery encrypt key'), 32); const recoveryKeyId = uint8ToHex(yield hkdf(recoveryKey, salt, encoder.encode('fxa recovery fingerprint'), 16)); const recoveryData = yield jweEncrypt(encryptionKey, recoveryKeyId, encoder.encode(JSON.stringify(keys)), forTestingOnly ? { testIV: forTestingOnly.testIV } : undefined); return { recoveryKey, recoveryKeyId, recoveryData, }; }); }