@cruxpay/js-sdk
Version:
CruxPay Javascript SDK
363 lines (362 loc) • 20.9 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 __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
import { publicKeyToAddress } from "blockstack";
import { CruxSpec } from "../../core/entities/crux-spec";
import { CruxUser, SubdomainRegistrationStatus } from "../../core/entities/crux-user";
import { BaseError, ErrorHelper, PackageError, PackageErrorCode } from "../../packages/error";
import { CruxDomainId, CruxId } from "../../packages/identity-utils";
import { getLogger } from "../../packages/logger";
import { cloneValue } from "../../packages/utils";
import { BlockstackService } from "../services/blockstack-service";
import { GaiaService } from "../services/gaia-service";
import { BlockstackCruxDomainRepository } from "./blockstack-crux-domain-repository";
var log = getLogger(__filename);
var BlockstackCruxUserRepository = /** @class */ (function () {
function BlockstackCruxUserRepository(options) {
var _this = this;
this.create = function (cruxIdSubdomain, keyManager) { return __awaiter(_this, void 0, void 0, function () {
var cruxUserData, cruxUserInformation;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
cruxUserData = {
configuration: { enabledAssetGroups: [] },
privateAddresses: {},
};
return [4 /*yield*/, this.putCruxpayObject(this.getCruxDomain().id, {}, keyManager)];
case 1:
_a.sent();
return [4 /*yield*/, this.blockstackService.registerCruxId(this.getCruxIdFromSubdomain(cruxIdSubdomain), this.infrastructure.gaiaHub, keyManager)];
case 2:
cruxUserInformation = _a.sent();
return [2 /*return*/, new CruxUser(cruxIdSubdomain, this.getCruxDomain(), {}, cruxUserInformation, cruxUserData)];
}
});
}); };
this.isCruxIdAvailable = function (cruxIdSubdomain) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.blockstackService.isCruxIdAvailable(this.getCruxIdFromSubdomain(cruxIdSubdomain))];
});
}); };
this.getByCruxId = function (cruxID, tag, onlyRegistered) {
if (onlyRegistered === void 0) { onlyRegistered = false; }
return __awaiter(_this, void 0, void 0, function () {
var cruxUserInformation, addressMap, cruxUserData, cruxpayPubKey, cruxpayJson, cruxpayObject, dereferencedCruxpayObject, _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0: return [4 /*yield*/, this.blockstackService.getCruxIdInformation(cruxID, tag, onlyRegistered)];
case 1:
cruxUserInformation = _c.sent();
if (cruxUserInformation.registrationStatus.status === SubdomainRegistrationStatus.NONE) {
return [2 /*return*/];
}
addressMap = {};
cruxUserData = {
configuration: {
enabledAssetGroups: [],
},
privateAddresses: {},
};
if (!(cruxUserInformation.registrationStatus.status === SubdomainRegistrationStatus.DONE)) return [3 /*break*/, 3];
return [4 /*yield*/, this.getCruxpayObjectAndPubKey(cruxID, tag)];
case 2:
cruxpayJson = _c.sent();
cruxpayObject = cruxpayJson.cruxpayObject;
cruxpayPubKey = cruxpayJson.pubKey;
dereferencedCruxpayObject = this.dereferenceCruxpayObject(cruxpayObject);
addressMap = dereferencedCruxpayObject.addressMap;
if (dereferencedCruxpayObject.cruxUserData) {
cruxUserData = dereferencedCruxpayObject.cruxUserData;
}
_c.label = 3;
case 3:
_a = CruxUser.bind;
_b = [void 0, cruxID.components.subdomain];
return [4 /*yield*/, this.getUserCruxDomain(cruxID)];
case 4: return [2 /*return*/, new (_a.apply(CruxUser, _b.concat([_c.sent(), addressMap, cruxUserInformation, cruxUserData, cruxpayPubKey])))()];
}
});
});
};
this.getWithKey = function (keyManager) { return __awaiter(_this, void 0, void 0, function () {
var cruxID, cruxUserInformation, addressMap, cruxUserData, cruxpayPubKey, cruxpayJson, cruxpayObject, dereferencedCruxpayObject;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.blockstackService.getCruxIdWithKeyManager(keyManager, this.getCruxDomain().id)];
case 1:
cruxID = _a.sent();
if (!cruxID) {
return [2 /*return*/];
}
return [4 /*yield*/, this.blockstackService.getCruxIdInformation(cruxID)];
case 2:
cruxUserInformation = _a.sent();
if (cruxUserInformation.registrationStatus.status === SubdomainRegistrationStatus.NONE) {
return [2 /*return*/];
}
addressMap = {};
cruxUserData = {
configuration: {
enabledAssetGroups: [],
},
privateAddresses: {},
};
return [4 /*yield*/, keyManager.getPubKey()];
case 3:
cruxpayPubKey = _a.sent();
if (![SubdomainRegistrationStatus.DONE, SubdomainRegistrationStatus.PENDING].includes(cruxUserInformation.registrationStatus.status)) return [3 /*break*/, 5];
return [4 /*yield*/, this.getCruxpayObjectAndPubKey(cruxID, undefined, cruxpayPubKey)];
case 4:
cruxpayJson = _a.sent();
cruxpayObject = cruxpayJson.cruxpayObject;
cruxpayPubKey = cruxpayJson.pubKey;
dereferencedCruxpayObject = this.dereferenceCruxpayObject(cruxpayObject);
addressMap = dereferencedCruxpayObject.addressMap;
if (dereferencedCruxpayObject.cruxUserData) {
cruxUserData = dereferencedCruxpayObject.cruxUserData;
}
_a.label = 5;
case 5: return [2 /*return*/, new CruxUser(cruxID.components.subdomain, this.getCruxDomain(), addressMap, cruxUserInformation, cruxUserData, cruxpayPubKey)];
}
});
}); };
this.save = function (cruxUser, keyManager) { return __awaiter(_this, void 0, void 0, function () {
var cruxpayObject;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
cruxpayObject = this.constructCruxpayObject(cruxUser.getAddressMap(), cruxUser.info, cruxUser.config, cruxUser.privateAddresses);
return [4 /*yield*/, this.putCruxpayObject(cruxUser.domain.id, cruxpayObject, keyManager)];
case 1:
_a.sent();
return [2 /*return*/, cruxUser];
}
});
}); };
this.getCruxDomain = function () {
if (!_this.cruxDomain) {
throw new BaseError(null, "Repository requires domain context");
}
return _this.cruxDomain;
};
this.getCruxIdFromSubdomain = function (subdomain) {
return new CruxId({
domain: _this.getCruxDomain().id.components.domain,
subdomain: subdomain,
});
};
this.getUserCruxDomain = function (cruxId) {
return new BlockstackCruxDomainRepository({ cacheStorage: _this.cacheStorage, blockstackInfrastructure: _this.infrastructure }).get(new CruxDomainId(cruxId.components.domain));
};
this.getCruxpayObjectAndPubKey = function (cruxId, tag, publicKey) { return __awaiter(_this, void 0, void 0, function () {
var cruxPayFileName, cruxpay, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
cruxPayFileName = CruxSpec.blockstack.getCruxPayFilename(new CruxDomainId(cruxId.components.domain));
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.getContentByFilename(cruxId, cruxPayFileName, tag, publicKey && publicKeyToAddress(publicKey))];
case 2:
cruxpay = _a.sent();
return [3 /*break*/, 4];
case 3:
error_1 = _a.sent();
if (error_1 instanceof PackageError && error_1.errorCode === PackageErrorCode.GaiaEmptyResponse && publicKey) {
// in case of no cruxpay.json found, assuming empty json and user provided pubkey
return [2 /*return*/, {
cruxpayObject: {},
pubKey: publicKey,
}];
}
else {
throw error_1;
}
return [3 /*break*/, 4];
case 4: return [2 /*return*/, {
cruxpayObject: cruxpay.payload.claim,
pubKey: cruxpay.payload.subject.publicKey,
}];
}
});
}); };
this.putCruxpayObject = function (cruxDomainId, cruxpayObject, keyManager) { return __awaiter(_this, void 0, void 0, function () {
var cruxPayFileName, url;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
cruxPayFileName = CruxSpec.blockstack.getCruxPayFilename(cruxDomainId);
return [4 /*yield*/, this.putContentByFilename(cruxDomainId, cruxPayFileName, cruxpayObject, keyManager)];
case 1:
url = _a.sent();
log.debug("Address Map saved to: " + url);
return [2 /*return*/, url];
}
});
}); };
this.getContentByFilename = function (cruxId, filename, tag, ownerAddress) { return __awaiter(_this, void 0, void 0, function () {
var gaiaHub, error_2, nameDetails;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.blockstackService.getGaiaHub(cruxId, tag)];
case 1:
gaiaHub = _a.sent();
return [3 /*break*/, 3];
case 2:
error_2 = _a.sent();
if (error_2 instanceof PackageError && [PackageErrorCode.MissingZoneFile, PackageErrorCode.MissingNameOwnerAddress].includes(error_2.errorCode)) {
log.debug("missing nameDetails, assuming the id to be in pending state and moving forward with the gaia fallback");
}
else {
throw error_2;
}
return [3 /*break*/, 3];
case 3:
if (!gaiaHub) {
gaiaHub = this.infrastructure.gaiaHub;
}
if (!!ownerAddress) return [3 /*break*/, 5];
return [4 /*yield*/, this.blockstackService.getNameDetails(cruxId, tag)];
case 4:
nameDetails = _a.sent();
if (!nameDetails.address) {
throw ErrorHelper.getPackageError(null, PackageErrorCode.MissingNameOwnerAddress, cruxId.toString());
}
return [2 /*return*/, new GaiaService(gaiaHub, this.cacheStorage).getContentFromGaiaHub(nameDetails.address, filename)];
case 5: return [2 /*return*/, new GaiaService(gaiaHub, this.cacheStorage).getContentFromGaiaHub(ownerAddress, filename)];
}
});
}); };
this.putContentByFilename = function (cruxDomainId, filename, content, keyManager) { return __awaiter(_this, void 0, void 0, function () {
var cruxId, gaiaHub, error_3, finalURL;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.blockstackService.getCruxIdWithKeyManager(keyManager, cruxDomainId)];
case 1:
cruxId = _a.sent();
if (!cruxId) return [3 /*break*/, 5];
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, this.blockstackService.getGaiaHub(cruxId)];
case 3:
gaiaHub = _a.sent();
return [3 /*break*/, 5];
case 4:
error_3 = _a.sent();
if (error_3 instanceof PackageError && [PackageErrorCode.MissingZoneFile, PackageErrorCode.MissingNameOwnerAddress].includes(error_3.errorCode)) {
log.debug("missing nameDetails, assuming the id to be in pending state and moving forward with the gaia fallback");
}
else {
throw error_3;
}
return [3 /*break*/, 5];
case 5:
if (!gaiaHub) {
gaiaHub = this.infrastructure.gaiaHub;
}
return [4 /*yield*/, new GaiaService(gaiaHub, this.cacheStorage).uploadContentToGaiaHub(filename, content, keyManager)];
case 6:
finalURL = _a.sent();
return [2 /*return*/, finalURL];
}
});
}); };
this.constructCruxpayObject = function (addressMap, userInformation, userConfiguration, privateAddresses) {
var cruxpayObject = cloneValue(addressMap);
cruxpayObject.__userData__ = {
configuration: userConfiguration,
privateAddresses: privateAddresses,
};
return cruxpayObject;
};
this.dereferenceCruxpayObject = function (cruxpayObject) {
var cruxpayObjectClone = cloneValue(cruxpayObject);
var cruxUserData = cruxpayObjectClone.__userData__;
// after extracting the userData from the cruxpayObject, delete the key from the property and assume the rest is valid addressMap
delete cruxpayObjectClone.__userData__;
var addressMap = cloneValue(cruxpayObjectClone);
return {
addressMap: addressMap,
cruxUserData: cruxUserData,
};
};
this.cacheStorage = options && options.cacheStorage;
var infrastructure = options.blockstackInfrastructure;
if (options.cruxDomain) {
this.cruxDomain = options.cruxDomain;
var domainBnsOverrides = options.cruxDomain.config.nameserviceConfiguration ? options.cruxDomain.config.nameserviceConfiguration.bnsNodes : undefined;
infrastructure.bnsNodes = domainBnsOverrides && __spread(new Set(__spread(infrastructure.bnsNodes, domainBnsOverrides))) || infrastructure.bnsNodes;
var gaiaHubOverride = options.cruxDomain.config.nameserviceConfiguration ? options.cruxDomain.config.nameserviceConfiguration.gaiaHub : undefined;
infrastructure.gaiaHub = gaiaHubOverride || infrastructure.gaiaHub;
var subdomainRegistrarOverride = options.cruxDomain.config.nameserviceConfiguration ? options.cruxDomain.config.nameserviceConfiguration.subdomainRegistrar : undefined;
infrastructure.subdomainRegistrar = subdomainRegistrarOverride || infrastructure.subdomainRegistrar;
}
this.infrastructure = infrastructure;
this.blockstackService = new BlockstackService({
bnsNodes: this.infrastructure.bnsNodes,
cacheStorage: this.cacheStorage,
subdomainRegistrar: this.infrastructure.subdomainRegistrar,
});
log.debug("BlockstackCruxUserRepository initialised");
}
return BlockstackCruxUserRepository;
}());
export { BlockstackCruxUserRepository };