@multiversx/sdk-nestjs-http
Version:
Multiversx SDK Nestjs http package
73 lines • 3.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NativeAuthSigner = exports.AccessTokenInfo = exports.NativeAuthSignerConfig = void 0;
const sdk_core_1 = require("@multiversx/sdk-core");
const sdk_native_auth_client_1 = require("@multiversx/sdk-native-auth-client");
const native_auth_client_config_1 = require("@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config");
require("@multiversx/sdk-nestjs-common/lib/utils/extensions/date.extensions");
const file_utils_1 = require("@multiversx/sdk-nestjs-common/lib/utils/file.utils");
class NativeAuthSignerConfig extends native_auth_client_config_1.NativeAuthClientConfig {
constructor() {
super(...arguments);
this.signerPrivateKeyPath = undefined;
this.privateKey = undefined;
}
}
exports.NativeAuthSignerConfig = NativeAuthSignerConfig;
class AccessTokenInfo {
constructor() {
this.token = "";
this.expiryDate = new Date(0);
}
}
exports.AccessTokenInfo = AccessTokenInfo;
class NativeAuthSigner {
constructor(config) {
this.config = Object.assign(new NativeAuthSignerConfig(), config);
this.nativeAuthClient = new sdk_native_auth_client_1.NativeAuthClient(this.config);
}
async getToken() {
const currentDate = new Date().addMinutes(1);
if (this.accessTokenInfo &&
currentDate <= this.accessTokenInfo.expiryDate) {
return this.accessTokenInfo;
}
const userSigner = await this.getUserSigner();
const signableToken = await this.getSignableToken();
const signerAddress = userSigner.getAddress().toBech32();
const message = this.getMessage(signerAddress, signableToken);
const messageComputer = new sdk_core_1.MessageComputer();
const signature = await userSigner.sign(messageComputer.computeBytesForSigning(message));
const token = this.nativeAuthClient.getToken(signerAddress, signableToken, Buffer.from(signature).toString("hex"));
const expiryDate = new Date().addSeconds(this.config.expirySeconds);
return (this.accessTokenInfo = {
token,
expiryDate,
});
}
async getUserSigner() {
if (this.userSigner) {
return this.userSigner;
}
if (this.config.privateKey) {
return (this.userSigner = sdk_core_1.UserSigner.fromPem(this.config.privateKey));
}
else if (this.config.signerPrivateKeyPath) {
const pemFile = await file_utils_1.FileUtils.readFile(this.config.signerPrivateKeyPath);
const pemKey = pemFile.toString();
return (this.userSigner = sdk_core_1.UserSigner.fromPem(pemKey));
}
throw new Error("Missing PrivateKey and SignerPrivateKeyPath in NativeAuthSigner.");
}
getSignableToken() {
return this.nativeAuthClient.initialize();
}
getMessage(signerAddress, signableToken) {
const messageToSign = `${signerAddress}${signableToken}`;
return new sdk_core_1.Message({
data: Buffer.from(messageToSign, "utf8"),
});
}
}
exports.NativeAuthSigner = NativeAuthSigner;
//# sourceMappingURL=native.auth.signer.js.map