next-auth-hashpack
Version:
Authenticate with Hashpack wallet using NextAuthJs library.
232 lines (231 loc) • 14.8 kB
JavaScript
;
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 };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.truncatePrivateKey = exports.isValidHederaAccount = exports.debugging = exports.hashpackProvider = void 0;
var sdk_1 = require("@hashgraph/sdk");
var credentials_1 = __importDefault(require("next-auth/providers/credentials"));
/**
* config the credential to be used with hashpack wallet
*
* @param userReturnCallback a callback that return verified user
* @param privateKey Server's Hedera account private key, can be an object of privatekey strings for each networks
* @param mirrorNodeAccountInfoURL the mirror node api route for fetching account's info
* @param getUserPublicKey replace the fetching client user's public key mechanism
* @param checkOriginalData check the original data
*/
var hashpackProvider = function (_a) {
var userReturnCallback = _a.userReturnCallback, privateKey = _a.privateKey, _b = _a.mirrorNodeAccountInfoURL, mirrorNodeAccountInfoURL = _b === void 0 ? {
testnet: 'https://testnet.mirrornode.hedera.com/api/v1/accounts',
mainnet: 'https://mainnet-public.mirrornode.hedera.com/api/v1/accounts',
previewnet: ""
} : _b, _c = _a.getUserPublicKey, getUserPublicKey = _c === void 0 ? null : _c, checkOriginalData = _a.checkOriginalData, _d = _a.debug, debug = _d === void 0 ? false : _d;
return (0, credentials_1.default)({
id: "hashpack",
name: 'Hashpack wallet',
credentials: {
signedPayload: { label: '', type: "hidden" },
userSignature: { label: '', type: "hidden" },
accountId: { label: '', type: "hidden" },
network: { label: '', type: "hidden" },
},
authorize: function (credentials) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var signedPayload, userSignature, accountId, network, userAccountPublicKey, userAccountInfoResponse, responseData, pv, serverVerified, clientVerified;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
signedPayload = credentials.signedPayload, userSignature = credentials.userSignature, accountId = credentials.accountId, network = credentials.network;
(0, exports.debugging)(debug, "red credentials: ", credentials);
if (!signedPayload || !userSignature || !accountId || !network) {
(0, exports.debugging)(debug, "missing credentials ");
throw new Error("unable to process your request");
}
if (!isValidHederaAccount(accountId)) {
(0, exports.debugging)(debug, "user account was invalid in format.");
throw new Error("Hedera Account is not valid.");
}
if (network !== 'mainnet' && network !== 'testnet' && network !== 'previewnet') {
(0, exports.debugging)(debug, "hedera account was invalid.");
throw new Error("Hedera network is incorrect.");
}
try {
(0, exports.debugging)(debug, "convert signedPayload and userSignature to json.");
signedPayload = JSON.parse(signedPayload);
userSignature = JSON.parse(userSignature);
}
catch (err) {
(0, exports.debugging)(debug, "one or both of them were invalid.");
throw new Error("Invalid Signature");
}
if (!(signedPayload === null || signedPayload === void 0 ? void 0 : signedPayload.originalPayload) || !(signedPayload === null || signedPayload === void 0 ? void 0 : signedPayload.serverSignature)) {
(0, exports.debugging)(debug, "one or both of them were null or undefined.");
throw new Error("Invalid entries");
}
if (!isUint8ArrayCompatible(signedPayload.serverSignature) || !isUint8ArrayCompatible(userSignature)) {
(0, exports.debugging)(debug, "one or both of were not a valid Uint8Array.");
throw new Error("Invalid Signature");
}
(0, exports.debugging)(debug, "checking data if present runs.");
if (checkOriginalData && !checkOriginalData({ accountId: accountId, network: network, originalData: signedPayload === null || signedPayload === void 0 ? void 0 : signedPayload.originalPayload })) {
(0, exports.debugging)(debug, "originalData returned error.");
throw new Error("Invalid Signature");
}
(0, exports.debugging)(debug, "originalData passed.");
(0, exports.debugging)(debug, "trying to get user public key.");
userAccountPublicKey = '';
if (!(getUserPublicKey !== null && typeof getUserPublicKey === 'function')) return [3 /*break*/, 2];
(0, exports.debugging)(debug, "getting user public key in a custom way");
return [4 /*yield*/, getUserPublicKey({ accountId: accountId, network: network })];
case 1:
userAccountPublicKey = _b.sent();
(0, exports.debugging)(debug, "result of custom public key getter: ", userAccountPublicKey);
return [3 /*break*/, 5];
case 2:
(0, exports.debugging)(debug, "getting user public key from mirror node: ", mirrorNodeAccountInfoURL[network], mirrorNodeAccountInfoURL, network);
return [4 /*yield*/, fetch("".concat(mirrorNodeAccountInfoURL[network], "/").concat(accountId))];
case 3:
userAccountInfoResponse = _b.sent();
if (!userAccountInfoResponse.ok) return [3 /*break*/, 5];
return [4 /*yield*/, userAccountInfoResponse.json()];
case 4:
responseData = _b.sent();
userAccountPublicKey = (_a = responseData === null || responseData === void 0 ? void 0 : responseData.key) === null || _a === void 0 ? void 0 : _a.key;
(0, exports.debugging)(debug, "user public key was returned successfully: ", userAccountPublicKey);
_b.label = 5;
case 5:
if (!userAccountPublicKey) {
(0, exports.debugging)(debug, "user public key wasn't present.", userAccountPublicKey);
throw new Error("User public key is missing");
}
pv = null;
if (typeof privateKey === 'function') {
(0, exports.debugging)(debug, "getting server private Key from a callback.");
pv = privateKey(network);
(0, exports.debugging)(debug, "returned private key: ", (0, exports.truncatePrivateKey)(pv));
}
else if (serverPrivateKeyIsNetworkRelated(privateKey)) {
(0, exports.debugging)(debug, "getting server private Key from an object.");
pv = privateKey[network];
if (!pv) {
(0, exports.debugging)(debug, "object didn't contained network: ", network);
throw new Error("Server Internal Error.");
}
(0, exports.debugging)(debug, "returned private key: ", (0, exports.truncatePrivateKey)(pv));
}
else {
pv = privateKey;
(0, exports.debugging)(debug, "private key: ", (0, exports.truncatePrivateKey)(pv));
}
(0, exports.debugging)(debug, "verifying validation of signatures.");
serverVerified = verifyData(signedPayload.originalPayload, sdk_1.PrivateKey.fromString(pv).publicKey, Uint8Array.from(Object.values(signedPayload.serverSignature)));
(0, exports.debugging)(debug, "server signature verifying result: ", serverVerified);
clientVerified = verifyData(signedPayload, userAccountPublicKey, Uint8Array.from(Object.values(userSignature)));
(0, exports.debugging)(debug, "user signature verifying result: ", clientVerified);
if (serverVerified && clientVerified) {
(0, exports.debugging)(debug, "successful authorization");
return [2 /*return*/, userReturnCallback(credentials, userAccountPublicKey)];
}
throw new Error("Authentication Failed");
}
});
});
}
});
};
exports.hashpackProvider = hashpackProvider;
var verifyData = function (data, publicKey, signature) {
var pubKey = publicKeyIsString(publicKey) ? sdk_1.PublicKey.fromString(publicKey) : publicKey;
var bytes = new Uint8Array(Buffer.from(JSON.stringify(data)));
var verify = pubKey.verify(bytes, signature);
return verify;
};
var serverPrivateKeyIsNetworkRelated = function (serverPublicKey) {
return typeof serverPublicKey !== 'string';
};
var publicKeyIsString = function (publicKey) {
return typeof publicKey === 'string';
};
var isUint8ArrayCompatible = function (data) {
if (typeof data === 'object' && !Array.isArray(data) && data !== null) {
data = Object.values(data);
}
if (!Array.isArray(data))
return false;
if (data.length % Uint8Array.BYTES_PER_ELEMENT !== 0)
return false;
return data.every(function (value) {
return Number.isInteger(value) && value >= 0 && value <= 255;
});
};
var debugging = function (active) {
var rest = [];
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
if (active) {
console.log.apply(console, __spreadArray(["".concat(new Date().toISOString(), ": ")], rest, false));
}
};
exports.debugging = debugging;
function isValidHederaAccount(accountId) {
var regex = /^(\d{1,10}\.){2}\d{1,10}$/;
return regex.test(accountId);
}
exports.isValidHederaAccount = isValidHederaAccount;
var truncatePrivateKey = function (privateKey) {
if (privateKey.length < 6) {
return false;
}
var firstThreeChars = privateKey.slice(0, 3);
var lastThreeChars = privateKey.slice(-3);
return "".concat(firstThreeChars, "...").concat(lastThreeChars);
};
exports.truncatePrivateKey = truncatePrivateKey;