UNPKG

freehold

Version:

App data encryption for web3

250 lines (249 loc) 14.9 kB
"use strict"; 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()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var bytes_1 = require("@ethersproject/bytes"); var strings_1 = require("@ethersproject/strings"); var webcrypto_liner_1 = __importDefault(require("webcrypto-liner")); var crypto; if (typeof webcrypto_liner_1.default === "undefined") { crypto = require("crypto").webcrypto; } var FreeholdSigner = /** @class */ (function () { function FreeholdSigner(encrypt, decrypt) { this._encrypt = encrypt; this._decrypt = decrypt; } FreeholdSigner.prototype.encrypt = function (plaintext) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this._encrypt(plaintext)]; }); }); }; FreeholdSigner.prototype.decrypt = function (cipherText) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this._decrypt(cipherText)]; }); }); }; return FreeholdSigner; }()); function __createSignerObject(secretKey) { return __awaiter(this, void 0, void 0, function () { var enc, seed, masterKey; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: enc = new TextEncoder(); seed = Buffer.concat([ enc.encode(secretKey), //crypto.getRandomValues(new Uint8Array(16)) ]); return [4 /*yield*/, crypto.subtle.importKey("raw", seed, "PBKDF2", false, ["deriveBits", "deriveKey"]) // Just for good measure. Keep the raw data out of scope. ]; case 1: masterKey = _a.sent(); // Just for good measure. Keep the raw data out of scope. secretKey = undefined; return [2 /*return*/, new FreeholdSigner(function (plaintext) { return __awaiter(_this, void 0, void 0, function () { var iv, salt, key, ct, ctBuffer; return __generator(this, function (_a) { switch (_a.label) { case 0: iv = crypto.getRandomValues(new Uint8Array(12)); salt = crypto.getRandomValues(new Uint8Array(16)); return [4 /*yield*/, crypto.subtle.deriveKey({ name: "PBKDF2", salt: salt, iterations: 100000, hash: "SHA-256" }, masterKey, { name: "AES-GCM", length: 256 }, false, ["encrypt"]) // Encrypt the plaintext via AES using the key and the iv ]; case 1: key = _a.sent(); return [4 /*yield*/, crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, enc.encode(plaintext)) // Convert result to buffer ]; case 2: ct = _a.sent(); ctBuffer = Buffer.from(ct); // Return a base64url encoded string that includes both the iv, salt, and // cipher text. This makes the data easy to store and pass around. return [2 /*return*/, Buffer.concat([ iv, salt, ctBuffer ]).toString("base64url")]; } }); }); }, function (cipherText) { return __awaiter(_this, void 0, void 0, function () { var data, iv, salt, key, ciphertext, plainBuffer, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: data = Buffer.from(cipherText, "base64url"); iv = data.subarray(0, 12); salt = data.subarray(12, 28); return [4 /*yield*/, crypto.subtle.deriveKey({ name: "PBKDF2", salt: salt, iterations: 100000, hash: "SHA-256" }, masterKey, { name: "AES-GCM", length: 256 }, false, ["decrypt"]) // Get the remaining bytes of the cipher text as the encrypted data ]; case 1: key = _a.sent(); ciphertext = data.subarray(28); _a.label = 2; case 2: _a.trys.push([2, 4, , 5]); return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-GCM', iv: iv }, key, ciphertext) // And convert back to string. ]; case 3: plainBuffer = _a.sent(); // And convert back to string. return [2 /*return*/, new TextDecoder().decode(plainBuffer)]; case 4: e_1 = _a.sent(); throw new Error('Decrypt failed: ' + typeof e_1.message !== "undefined" ? e_1.message : e_1); case 5: return [2 /*return*/]; } }); }); })]; } }); }); } function __createSigner(provider, address, fragmentData) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, (function () { return __awaiter(_this, void 0, void 0, function () { var toSign, _i, toSign_1, fragment, _a, _b, _c, _d; var _this = this; return __generator(this, function (_e) { switch (_e.label) { case 0: toSign = JSON.parse(fragmentData); // Make sure it's an array if (!Array.isArray(toSign)) { toSign = [toSign]; } _i = 0, toSign_1 = toSign; _e.label = 1; case 1: if (!(_i < toSign_1.length)) return [3 /*break*/, 4]; fragment = toSign_1[_i]; if (!(fragment.type == "password")) return [3 /*break*/, 3]; _a = fragment; _c = (_b = Buffer).from; return [4 /*yield*/, crypto.subtle.digest('SHA-256', new TextEncoder().encode(fragment.data))]; case 2: _a.data = _c.apply(_b, [_e.sent()]).toString("hex"); _e.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: _d = __createSignerObject; return [4 /*yield*/, toSign.map(function (fragment) { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = [fragment]; return [4 /*yield*/, provider.send('personal_sign', [ (0, bytes_1.hexlify)((0, strings_1.toUtf8Bytes)(fragment.data)), address ])]; case 1: return [2 /*return*/, _a.concat([ (_b.sent()).replace("0x", "") ])]; } }); }); }).reduce(function (key, tuple) { return __awaiter(_this, void 0, void 0, function () { var _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, key]; case 1: _a = (_c.sent()); return [4 /*yield*/, tuple]; case 2: _b = _a + (_c.sent())[1]; return [4 /*yield*/, tuple]; case 3: // Add on the unsigned data + signature for this fragment. return [2 /*return*/, _b + (_c.sent())[0].data]; } }); }); }, Promise.resolve(""))]; case 5: // We try really hard to leave as little data at rest as possible // e.g., we don't store signed messages in memory for very long return [2 /*return*/, _d.apply(void 0, [_e.sent()])]; } }); }); })()]; }); }); } ; function freehold(provider, address, toSign) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { // We call a private signer just to be extra careful. // We stringify the input becasue we don't want to hold a // a reference to the original data. return [2 /*return*/, __createSigner(provider, address, JSON.stringify(toSign))]; }); }); } exports.default = freehold;