@beland/crypto-middleware
Version:
Memetaverse Authentication Middleware
214 lines (213 loc) • 10.3 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 (_) 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 });
exports.createPayload = exports.verifyExpiration = exports.verifyMetadata = exports.verifyTimestamp = exports.verifySign = exports.verifyEIP1654Sign = exports.verifyPersonalSign = exports.extractAuthChain = exports.isEIP1664AuthChain = void 0;
var types_1 = require("@beland/crypto/dist/types");
var Authenticator_1 = require("@beland/crypto/dist/Authenticator");
var types_2 = require("./types");
var errors_1 = __importDefault(require("./errors"));
var node_fetch_1 = __importDefault(require("node-fetch"));
function isEIP1664AuthChain(authChain) {
switch (authChain.length) {
case 2:
case 3:
return (authChain[0].type === types_1.AuthLinkType.SIGNER &&
authChain[1].type === types_1.AuthLinkType.ECDSA_EIP_1654_EPHEMERAL);
default:
return false;
}
}
exports.isEIP1664AuthChain = isEIP1664AuthChain;
function extractAuthChain(headers) {
var index = 0;
var chain = [];
while (headers[types_2.AUTH_CHAIN_HEADER_PREFIX + index]) {
try {
var item = Array.isArray(headers[types_2.AUTH_CHAIN_HEADER_PREFIX + index])
? headers[types_2.AUTH_CHAIN_HEADER_PREFIX + index][0]
: headers[types_2.AUTH_CHAIN_HEADER_PREFIX + index];
chain.push(JSON.parse(item));
}
catch (err) {
throw new errors_1.default("Invalid chain format: " + err.message, 400);
}
index++;
}
if (chain.length <= 1) {
throw new errors_1.default("Invalid Auth Chain", 400);
}
return chain;
}
exports.extractAuthChain = extractAuthChain;
function verifyPersonalSign(authChain, payload) {
return __awaiter(this, void 0, void 0, function () {
var verification;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Authenticator_1.Authenticator.validateSignature(payload, authChain, null)];
case 1:
verification = _a.sent();
if (!verification.ok) {
throw new errors_1.default("Invalid signature: " + verification.message, 401);
}
return [2 /*return*/, Authenticator_1.Authenticator.ownerAddress(authChain).toLowerCase()];
}
});
});
}
exports.verifyPersonalSign = verifyPersonalSign;
function verifyEIP1654Sign(authChain, payload, options) {
var _a;
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var catalyst, ownerAddress, response, verification, err_1, body, err_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
catalyst = new URL((_a = options.catalyst) !== null && _a !== void 0 ? _a : types_2.DEFAULT_CATALYST);
ownerAddress = Authenticator_1.Authenticator.ownerAddress(authChain).toLowerCase();
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, (0, node_fetch_1.default)("https://" + catalyst.host + "/lambdas/crypto/validate-signature", {
method: 'POST',
headers: {
'content-type': 'application/json',
'accept-type': 'application/json',
},
body: JSON.stringify({ authChain: authChain, timestamp: payload }),
})];
case 2:
response = _b.sent();
return [3 /*break*/, 4];
case 3:
err_1 = _b.sent();
throw new errors_1.default("Error connecting to catalyst \"https://" + catalyst.host + "\"", 503);
case 4:
body = '';
_b.label = 5;
case 5:
_b.trys.push([5, 7, , 8]);
return [4 /*yield*/, response.text()];
case 6:
body = _b.sent();
verification = JSON.parse(body);
return [3 /*break*/, 8];
case 7:
err_2 = _b.sent();
throw new errors_1.default("Invalid response from catalyst \"https://" + catalyst.host + "\": " + body, 503);
case 8:
if (!verification.valid ||
verification.ownerAddress.toLowerCase() !== ownerAddress) {
throw new errors_1.default("Invalid signature", 401);
}
return [2 /*return*/, ownerAddress];
}
});
});
}
exports.verifyEIP1654Sign = verifyEIP1654Sign;
function verifySign(authChain, payload, options) {
if (options === void 0) { options = {}; }
if (isEIP1664AuthChain(authChain)) {
return verifyEIP1654Sign(authChain, payload, options);
}
return verifyPersonalSign(authChain, payload);
}
exports.verifySign = verifySign;
function verifyTimestamp(value) {
var timestamp = Number(value || '0');
if (value && !Number.isFinite(timestamp)) {
throw new errors_1.default("Invalid chain timestamp: " + value, 400);
}
return timestamp;
}
exports.verifyTimestamp = verifyTimestamp;
function verifyMetadata(value) {
try {
return JSON.parse(value ? String(value) : '{}');
}
catch (err) {
throw new errors_1.default("Invalid chain metadata: \"" + value + "\"", 400);
}
}
exports.verifyMetadata = verifyMetadata;
function verifyExpiration(timestamp, options) {
var _a;
if (options === void 0) { options = {}; }
var expiration = (_a = options.expiration) !== null && _a !== void 0 ? _a : types_2.DEFAULT_EXPIRATION;
var now = Date.now();
if (timestamp + expiration < now) {
throw new errors_1.default("Expired signature: signature timestamp: " + timestamp + ", timestamp expiration: " + (timestamp + expiration) + ", local timestamp: " + now, 401);
}
return true;
}
exports.verifyExpiration = verifyExpiration;
function createPayload(method, path, rawTimestamp, rawMetadata) {
return [method, path, rawTimestamp, rawMetadata].join(':').toLowerCase();
}
exports.createPayload = createPayload;
function verify(method, path, headers, options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var authChain, timestamp, metadata, payload, ownerAddress;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
authChain = extractAuthChain(headers);
timestamp = verifyTimestamp(headers[types_2.AUTH_TIMESTAMP_HEADER]);
metadata = verifyMetadata(headers[types_2.AUTH_METADATA_HEADER]);
payload = createPayload(method, path, headers[types_2.AUTH_TIMESTAMP_HEADER], headers[types_2.AUTH_METADATA_HEADER]);
return [4 /*yield*/, verifySign(authChain, payload, options)];
case 1:
ownerAddress = _a.sent();
return [4 /*yield*/, verifyExpiration(timestamp, options)];
case 2:
_a.sent();
return [2 /*return*/, {
auth: ownerAddress,
authMetadata: metadata,
}];
}
});
});
}
exports.default = verify;