UNPKG

next-auth-hashpack

Version:

Authenticate with Hashpack wallet using NextAuthJs library.

112 lines (111 loc) 7.82 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 (g && (g = 0, op[0] && (_ = 0)), _) 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.authInitializer = void 0; var sdk_1 = require("@hashgraph/sdk"); var hashpackProvider_1 = require("./hashpackProvider"); /** * call this function from a route that spouse to initiate the authentication with hashpack wallet. it signs a data and pass it to client. * @param req {NextApiRequest} * @param res {NextApiResponse} * @param ServerAccountId {string} Sever's account Id on Hedera Hashgraph network * @param ServerPrivateKey {PrivateKey} Server's account private key on Hedera Hashgraph * @param data {any} the data you are going to sign * @param network {'testnet' | 'mainnet' | previewnet} using Hedera's testnet or mainnet * @param preInitializingCallback runs after validation, receives accountId and optionally original data * @returns {Promise<void>} */ function authInitializer(req, res, ServerAccountId, ServerPrivateKey, data, network, preInitializingCallback, debug) { var _a, _b, _c, _d, _e, _f, _g; if (network === void 0) { network = "testnet"; } if (debug === void 0) { debug = false; } return __awaiter(this, void 0, void 0, function () { var csrfToken, csrfCookie, client, pk, bytes, signature, responseDate, err_1; return __generator(this, function (_h) { switch (_h.label) { case 0: _h.trys.push([0, 3, , 4]); if (req.method !== 'POST') { (0, hashpackProvider_1.debugging)(debug, "method wasn't allowed: ", req.method); return [2 /*return*/, res.status(405).send("Method not allowed.")]; } if (!((_a = req.body) === null || _a === void 0 ? void 0 : _a.accountId) || !(0, hashpackProvider_1.isValidHederaAccount)((_b = req.body) === null || _b === void 0 ? void 0 : _b.accountId)) { (0, hashpackProvider_1.debugging)(debug, "Invalid hedera account ID: ", (_c = req.body) === null || _c === void 0 ? void 0 : _c.accountId); throw new Error("Invalid hedera account ID."); } (0, hashpackProvider_1.debugging)(debug, "reading csrt-token", (_d = req.body) === null || _d === void 0 ? void 0 : _d.accountId); csrfToken = req.headers['x-csrf-token'] || ((_e = req.body) === null || _e === void 0 ? void 0 : _e.csrfToken); csrfCookie = req.cookies['__Host-next-auth.csrf-token'] || req.cookies['next-auth.csrf-token']; (0, hashpackProvider_1.debugging)(debug, "crf token: ", csrfToken, " csrf cookie: ", csrfCookie); if (!csrfToken || ((_g = (_f = (csrfCookie)) === null || _f === void 0 ? void 0 : _f.split(/[|%]/)) === null || _g === void 0 ? void 0 : _g[0]) !== csrfToken) { (0, hashpackProvider_1.debugging)(debug, "crf token and cookie didn't match."); throw new Error("Invalid token"); } if (!preInitializingCallback) return [3 /*break*/, 2]; (0, hashpackProvider_1.debugging)(debug, "preInitializingCallback is about to run"); return [4 /*yield*/, preInitializingCallback({ accountId: req.body.accountId, network: network, data: data })]; case 1: _h.sent(); (0, hashpackProvider_1.debugging)(debug, "preInitializingCallback ran"); _h.label = 2; case 2: client = network === 'testnet' ? sdk_1.Client.forTestnet() : sdk_1.Client.forMainnet(); (0, hashpackProvider_1.debugging)(debug, "hedera client was set for network: ", network); pk = sdk_1.PrivateKey.fromString(ServerPrivateKey); (0, hashpackProvider_1.debugging)(debug, "Private key instance was created from string", (0, hashpackProvider_1.truncatePrivateKey)(ServerPrivateKey)); client.setOperator(sdk_1.AccountId.fromString(ServerAccountId), pk); (0, hashpackProvider_1.debugging)(debug, "hedera client operator was set: ", ServerAccountId); bytes = new Uint8Array(Buffer.from(JSON.stringify(data))); (0, hashpackProvider_1.debugging)(debug, "bytes was generated: ", bytes); signature = pk.sign(bytes); responseDate = { signature: signature, serverSigningAccount: ServerAccountId, payload: data, }; (0, hashpackProvider_1.debugging)(debug, "response was sent: ", responseDate); return [2 /*return*/, res.status(200).send(JSON.stringify(responseDate))]; case 3: err_1 = _h.sent(); return [2 /*return*/, res.status(403).send((err_1 === null || err_1 === void 0 ? void 0 : err_1.message) ? err_1.message : "something went wrong. try again")]; case 4: return [2 /*return*/]; } }); }); } exports.authInitializer = authInitializer;