notebook-ts
Version:
Prevent Sybil attacks with the click of a button.
358 lines (357 loc) • 18.5 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NotebookButton = exports.NotebookSessionManager = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var LOGIN_URL = "https://main.d3j8dl7vahzk14.amplifyapp.com";
var PKEY_URL = "https://pkey1.s3.us-west-1.amazonaws.com/";
var circomlibjs = require('circomlibjs');
var field = require("ffjavascript");
var elliptic = require("elliptic");
var ec = new elliptic.ec('secp256k1');
var bib = require('bigint-buffer');
var AWS = require('aws-sdk');
var proveSig_1 = require("./proveSig");
var NotebookSessionManager = /** @class */ (function () {
function NotebookSessionManager(window, registerUser, handleKYCError, test_mode) {
this.proofData = null;
this.window = window;
this.registerUser = registerUser;
this.handleKYCError = handleKYCError;
this.test_mode = test_mode;
this.error = "";
}
NotebookSessionManager.prototype.deserializeProof = function (data) {
var jdata = JSON.parse(data);
for (var i = 0; i < jdata.a.length; i++) {
jdata["a"][i] = BigInt(jdata.a[i]);
}
for (var i = 0; i < jdata.b.length; i++) {
for (var j = 0; j < jdata.b[i].length; j++) {
jdata["b"][i][j] = BigInt(jdata.b[i][j]);
}
}
for (var i = 0; i < jdata.c.length; i++) {
jdata["c"][i] = BigInt(jdata.c[i]);
}
for (var i = 0; i < jdata.signals.length; i++) {
jdata["signals"][i] = BigInt(jdata.signals[i]);
}
return jdata;
};
return NotebookSessionManager;
}());
exports.NotebookSessionManager = NotebookSessionManager;
var NotebookButton = function (props) {
var verificationURL = "https://notebooklabsapi.com/authorize?leaf=";
var resultURL = "https://notebooklabsapi.com/result?leaf=";
var TIMER_MS = 4000;
var proofGenStarted = false;
var pk;
var windowOpened = false;
var notebookWindow = null;
function get_pk(cred) {
return __awaiter(this, void 0, void 0, function () {
var data, pkstrings, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetch(PKEY_URL + cred + ".txt").then(function (res) {
return res.text();
})];
case 1:
data = _a.sent();
if (data !== undefined) {
pkstrings = data.split("\n");
pk = [new Uint8Array(32), new Uint8Array(32)];
for (i = 0; i < 32; i++) {
pk[0][i] = Number(pkstrings[0].split(",")[i]);
pk[1][i] = Number(pkstrings[1].split(",")[i]);
}
}
return [2 /*return*/];
}
});
});
}
var poseidon;
var MIMC;
var bn128;
var F;
function init_hashes() {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, circomlibjs.buildPoseidonReference()];
case 1:
poseidon = _a.sent();
return [4 /*yield*/, circomlibjs.buildMimcSponge()];
case 2:
MIMC = _a.sent();
return [4 /*yield*/, field.getCurveFromName("bn128", true)];
case 3:
bn128 = _a.sent();
F = bn128.Fr;
return [2 /*return*/];
}
});
});
}
function padHexToLength(number, length) {
while (number.length < length + 2) {
number = "0x0" + number.slice(2);
}
return number;
}
function poseidonHash(secret, nonce) {
return __awaiter(this, void 0, void 0, function () {
var return_val, _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
secret = padHexToLength(secret, 64);
nonce = padHexToLength(nonce, 64);
return [4 /*yield*/, field.getCurveFromName("bn128", true)];
case 1:
bn128 = _c.sent();
F = bn128.Fr;
return [4 /*yield*/, circomlibjs.buildPoseidonReference()];
case 2:
poseidon = _c.sent();
_b = (_a = F).toObject;
return [4 /*yield*/, poseidon([secret, nonce], false, 1)];
case 3:
return_val = _b.apply(_a, [_c.sent()]).toString();
return [2 /*return*/, "0x" + BigInt(return_val).toString(16)];
}
});
});
}
function onClickKYC() {
if (windowOpened == true) {
return;
}
windowOpened = true;
var height = 650;
var width = 400;
var top = window.top.outerHeight / 2 + window.top.screenY - (height / 2);
var left = window.top.outerWidth / 2 + window.top.screenX - (width / 2);
notebookWindow = window.open("https://notebooklabs.xyz", "_blank", "toolbar=no, menubar=no, width=".concat(width, ", height=").concat(height, ", top=").concat(top, ", left=").concat(left));
genAndSignKeys();
}
/* Starts the kyc process.
*/
function genAndSignKeys() {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, init_hashes()];
case 1:
_a.sent();
return [4 /*yield*/, generateNotebook()];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
}
/* Generates key pair and then sets the identity hash to be the hash
* of the generated secret key, which is their leaf.
*/
function generateNotebook() {
return __awaiter(this, void 0, void 0, function () {
var keyPair, F2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
keyPair = ec.genKeyPair();
return [4 /*yield*/, get_pk("pkeytwittersig")];
case 1:
_a.sent();
return [4 /*yield*/, circomlibjs.buildBabyjub()];
case 2:
F2 = (_a.sent()).F;
poseidonHash("0x" + keyPair.getPrivate("hex").toString(), "0x" + F2.toObject(pk[0]).toString(16)).then(function (res) {
signKeyAfterGen(keyPair.getPrivate("hex").toString(), padHexToLength(res, 64));
});
return [2 /*return*/];
}
});
});
}
function signKeyAfterGen(secret, identityHash) {
return __awaiter(this, void 0, void 0, function () {
var resultInterval;
return __generator(this, function (_a) {
setTimeout(function () {
notebookWindow.location.replace(verificationURL + identityHash.slice(2));
});
resultInterval = setInterval(function () {
return __awaiter(this, void 0, void 0, function () {
var url, response, data, sigjson;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = resultURL + identityHash.slice(2);
return [4 /*yield*/, fetch(url)];
case 1:
response = _a.sent();
return [4 /*yield*/, response.json()];
case 2:
data = _a.sent();
if (data.hasOwnProperty("incomplete")) {
return [2 /*return*/];
}
clearInterval(resultInterval);
if (proofGenStarted == true) {
return [2 /*return*/];
}
proofGenStarted = true;
notebookWindow === null || notebookWindow === void 0 ? void 0 : notebookWindow.close();
sigjson = JSON.parse(data.res.S);
if (sigjson.hasOwnProperty("error")) {
console.log("Error: " + sigjson);
props.notebook.handleKYCError(sigjson["error"]);
}
else {
genProof(sigjson, secret, identityHash);
}
return [2 /*return*/];
}
});
});
}, 1000);
return [2 /*return*/];
});
});
}
/* Converts proof data into correct format to pass
* into the solidity verifier contract.
*/
function serializeProof(proofData) {
var serialized = {};
serialized["a"] = [];
for (var i = 0; i < proofData.a.length; i++) {
serialized["a"].push(proofData.a[i].toString());
}
serialized["b"] = [];
for (var i = 0; i < proofData.b.length; i++) {
serialized["b"].push([]);
for (var j = 0; j < proofData.b[i].length; j++) {
serialized["b"][i].push(proofData.b[i][j].toString());
}
}
serialized["c"] = [];
for (var i = 0; i < proofData.c.length; i++) {
serialized["c"].push(proofData.c[i].toString());
}
serialized["signals"] = [];
for (var i = 0; i < proofData.signals.length; i++) {
serialized["signals"].push(proofData.signals[i].toString());
}
console.log(serialized);
return JSON.stringify(serialized);
}
/* After a user has been verified, this function calls the smart contract that manages
* the merkleTree to update the new credentials.
*/
function genProof(sig, secret, identityHash) {
return __awaiter(this, void 0, void 0, function () {
var R8_0, R8_1, i, leaf, proofData;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, field.getCurveFromName("bn128", true)];
case 1:
bn128 = _a.sent();
F = bn128.Fr;
R8_0 = new Uint8Array(32);
R8_1 = new Uint8Array(32);
for (i = 0; i < 32; i++) {
R8_0[i] = sig.r[0][i];
R8_1[i] = sig.r[1][i];
}
return [4 /*yield*/, poseidonHash("0x" + F.toObject(pk[0]).toString(16), "0x" + secret)];
case 2:
leaf = _a.sent();
return [4 /*yield*/, (0, proveSig_1.getVerifyData)([BigInt("0x" + F.toObject(pk[0]).toString(16)), BigInt("0x" + F.toObject(pk[1]).toString(16))], [BigInt("0x" + F.toObject(R8_0).toString(16)), BigInt("0x" + F.toObject(R8_1).toString(16))], BigInt(sig["s"]), "0x" + secret, leaf)];
case 3:
proofData = _a.sent();
props.notebook.registerUser(serializeProof(proofData));
return [2 /*return*/];
}
});
});
}
//filter: drop-shadow(0px 0px 4 rgba(0, 0, 0, 0.084)) drop-shadow(0px 3 4 rgba(0, 0, 0, 0.168));
var css = "\n .sign-in-modal {\n background: #ffffff;\n color: #222222;\n border-radius: 12px;\n padding: 40px;\n box-shadow: 0px 0px 4px rgba(0, 0, 0, 0.084), 0px 3px 4px rgba(0, 0, 0, 0.168);\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 24px;\n max-width: 400px;\n margin: auto;\n margin-top: 24px;\n }\n \n .notebook-logo {\n height: 84px;\n }\n .sign-in-button {\n background: #FFFFFF;\n border-radius: 16px;\n padding: 12px;\n border: none;\n box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.08), 0px 4px 6px rgba(0, 0, 0, 0.12);;\n font-style: normal;\n font-weight: 500;\n font-size: 18px;\n color: #222;\n display: flex;\n align-items: center;\n gap: 8px;\n cursor: pointer;\n }\n \n .sign-in-button:hover{\n background: #fafafa;\n box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.08), 0px 4px 6px rgba(0, 0, 0, 0.12);\n }\n \n .sign-in-button:active {\n background: #fff;\n }\n \n .google-logo {\n height: 24px;\n }\n ";
return (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("style", { children: css }), (0, jsx_runtime_1.jsxs)("div", __assign({ className: "sign-in-modal" }, { children: [(0, jsx_runtime_1.jsx)("img", { src: "https://images-ntbk.s3.us-west-1.amazonaws.com/notebookLogo.png", alt: "notebook-logo", className: "notebook-logo" }), (0, jsx_runtime_1.jsxs)("button", __assign({ className: "sign-in-button", onClick: onClickKYC }, { children: [(0, jsx_runtime_1.jsx)("img", { src: "https://images-ntbk.s3.us-west-1.amazonaws.com/googleLogo.png", className: "google-logo", alt: "google-logo" }), "Sign In with Google"] }))] }))] });
// if (props.dark === true) {
// return <button onClick={onClickKYC} style={{
// display: "flex", flexDirection: "row", justifyContent: "center",
// alignItems: "center",
// gap: "3px",
// position: "relative",
// width: "200px",
// padding: "0",
// border: "none",
// background: "none",
// }} ><img src="https://images-ntbk.s3.us-west-1.amazonaws.com/button_dark.png" width="180px" onClick={onClickKYC}></img></button >
// }
// return <button onClick={onClickKYC} style={{
// display: "flex", flexDirection: "row", justifyContent: "center",
// alignItems: "center",
// gap: "3px",
// position: "relative",
// width: "200px",
// padding: "0",
// border: "none",
// background: "none",
// }} ><img src="https://images-ntbk.s3.us-west-1.amazonaws.com/button_white.png" width="180px" onClick={onClickKYC}></img></button >
};
exports.NotebookButton = NotebookButton;