notebook-ts
Version:
Prevent Sybil attacks with the click of a button.
398 lines (397 loc) • 18.9 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 aiPriseWindow = null;
var AIPRISE_BASE_ONBOARDING_URL_TEST = "https://onboard-sandbox.aiprise.com";
var AIPRISE_BASE_ONBOARDING_URL_PROD = "https://onboard.aiprise.com";
var verificationURL = "";
var TIMER_MS = 4000;
var AiPriseAPIKeyTest = "64da53952bf74bb585705d572bcdc32e";
var AiPriseTemplateTest = "14cf75fd-1dc0-4591-ad9c-3f6e941c5d41";
var AiPriseAPIKeyProd = "5afe08447ba14478a7a64d241ac63a3b";
var AiPriseTemplateProd = "12d3201e-6570-48c8-aaeb-f4158dcef91f";
var pk;
var responseText;
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() {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
genAndSignKeys();
return [2 /*return*/];
});
});
}
/* Starts the kyc process.
*/
function genAndSignKeys() {
return __awaiter(this, void 0, void 0, function () {
var AiPriseAPIKey, AiPriseTemplate, verURL, verification_response, verification_data;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, init_hashes()];
case 1:
_a.sent();
AiPriseAPIKey = AiPriseAPIKeyProd;
if (props.notebook.test_mode) {
AiPriseAPIKey = AiPriseAPIKeyTest;
}
AiPriseTemplate = AiPriseTemplateProd;
if (props.notebook.test_mode) {
AiPriseTemplate = AiPriseTemplateTest;
}
verURL = "https://api.aiprise.com/api/v1/verify/get_user_verification_url";
if (props.notebook.test_mode) {
verURL = "https://api-sandbox.aiprise.com/api/v1/verify/get_user_verification_url";
}
return [4 /*yield*/, fetch(verURL, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"X-Api-Key": AiPriseAPIKey
},
body: JSON.stringify({
"redirect_uri": "popup_close", "template_id": AiPriseTemplate
})
})];
case 2:
verification_response = _a.sent();
return [4 /*yield*/, verification_response.json()];
case 3:
verification_data = _a.sent();
verificationURL = verification_data["verification_url"];
openAiPriseWindow();
return [2 /*return*/];
}
});
});
}
function openAiPriseWindow() {
console.log("openAiPriseWindow");
var height = 650;
var width = 400;
window.addEventListener('message', kycFinishedListener);
var top = window.top.outerHeight / 2 + window.top.screenY - (height / 2);
var left = window.top.outerWidth / 2 + window.top.screenX - (width / 2);
aiPriseWindow = window.open(verificationURL, "aiprise", "toolbar=no, menubar=no, width=".concat(width, ", height=").concat(height, ", top=").concat(top, ", left=").concat(left));
}
/* runs when it gets the message from AiPrise and is just a
* wrapper for signKeyAfterKYC
*/
function kycFinishedListener(event) {
return __awaiter(this, void 0, void 0, function () {
var aiprise_onboardingurl;
return __generator(this, function (_a) {
console.log("kycFinishedListener");
console.log(event.origin, event.data);
aiprise_onboardingurl = AIPRISE_BASE_ONBOARDING_URL_PROD;
if (props.notebook.test_mode == true) {
aiprise_onboardingurl = AIPRISE_BASE_ONBOARDING_URL_TEST;
}
if (event.origin === aiprise_onboardingurl && event.data === "AiPriseVerification:Complete") {
aiPriseWindow === null || aiPriseWindow === void 0 ? void 0 : aiPriseWindow.close();
window.removeEventListener('message', kycFinishedListener);
// TODO: implement checks that user finished the onboarding process.
generateNotebook();
}
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("pkey")];
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) {
signKeyAfterKYC(keyPair.getPrivate("hex").toString(), padHexToLength(res, 64));
});
return [2 /*return*/];
}
});
});
}
/* calls the signing server to get info to send to the smart contract
*/
function signKeyAfterKYC(secret, identityHash) {
return __awaiter(this, void 0, void 0, function () {
var verification_session_id, url, response, sigjson;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
console.log("signKeyAfterKYC");
verification_session_id = verificationURL.split("verification_session_id=")[1];
url = "https://cors-everywhere.herokuapp.com/http://54.153.56.147:3000/sign_twitter/?msg=" + identityHash.slice(2) + "&verification_id=" + verification_session_id;
return [4 /*yield*/, fetch(url)];
case 1:
response = _a.sent();
return [4 /*yield*/, response.json()];
case 2:
sigjson = _a.sent();
console.log("sigjson", sigjson);
if (sigjson.hasOwnProperty("error")) {
console.log("Error: " + sigjson);
props.notebook.handleKYCError(sigjson["error"]);
return [2 /*return*/];
}
genProof(sigjson, secret, identityHash);
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*/];
}
});
});
}
if (props.dark === true) {
return (0, jsx_runtime_1.jsx)("button", __assign({ onClick: onClickKYC, style: {
display: "flex", flexDirection: "row", justifyContent: "center",
alignItems: "center",
gap: "3px",
position: "relative",
width: "200px",
padding: "0",
border: "none",
background: "none",
} }, { children: (0, jsx_runtime_1.jsx)("img", { src: "https://images-ntbk.s3.us-west-1.amazonaws.com/button_dark.png", width: "180px", onClick: onClickKYC }) }));
}
return (0, jsx_runtime_1.jsx)("button", __assign({ onClick: onClickKYC, style: {
display: "flex", flexDirection: "row", justifyContent: "center",
alignItems: "center",
gap: "3px",
position: "relative",
width: "200px",
padding: "0",
border: "none",
background: "none",
} }, { children: (0, jsx_runtime_1.jsx)("img", { src: "https://images-ntbk.s3.us-west-1.amazonaws.com/button_white.png", width: "180px", onClick: onClickKYC }) }));
};
exports.NotebookButton = NotebookButton;