UNPKG

@jmcanterafonseca-iota/anchoring-channels

Version:

Powered by IOTA Streams, Anchor Channels is an easy to be used library that allows to anchor messages to the Tangle.

1,436 lines (1,311 loc) 146 kB
'use strict'; var require$$0 = require('@jmcanterafonseca-iota/iota_streams_wasm'); var require$$1 = require('crypto'); var require$$1$1 = require('node-fetch'); var require$$1$4 = require('jsonld'); var require$$1$2 = require('path'); var require$$2 = require('fs'); var require$$0$1 = require('bs58'); var require$$1$3 = require('elliptic'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0); var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1); var require$$1__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$1$4); var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2); var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1); var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var es = {}; var iotaAnchoringChannel = {}; var anchoringChannelError = {}; Object.defineProperty(anchoringChannelError, "__esModule", { value: true }); class AnchoringChannelError extends Error { constructor(name, message) { super(); this.type = AnchoringChannelError.ERR_TYPE; this.name = name; this.message = message; } } anchoringChannelError.default = AnchoringChannelError; AnchoringChannelError.ERR_TYPE = "AnchoringChannelError"; var anchoringChannelErrorNames = {}; Object.defineProperty(anchoringChannelErrorNames, "__esModule", { value: true }); class AnchoringChannelErrorNames { } anchoringChannelErrorNames.default = AnchoringChannelErrorNames; AnchoringChannelErrorNames.CHANNEL_NOT_BOUND = "Not_Bound"; AnchoringChannelErrorNames.ANCHORAGE_NOT_FOUND = "Anchorage_Not_Found"; AnchoringChannelErrorNames.MSG_NOT_FOUND = "Message_Not_Found"; AnchoringChannelErrorNames.CHANNEL_BINDING_ERROR = "Channel_Binding_Error"; AnchoringChannelErrorNames.CHANNEL_ALREADY_BOUND = "Channel_Already_Bound"; AnchoringChannelErrorNames.OTHER_ERROR = "Runtime_Error"; AnchoringChannelErrorNames.INVALID_NODE = "Invalid_Node"; AnchoringChannelErrorNames.INVALID_DID = "Invalid_DID"; AnchoringChannelErrorNames.DID_NOT_FOUND = "DID_Not_Found"; AnchoringChannelErrorNames.INVALID_DID_METHOD = "Invalid_DID_Method"; AnchoringChannelErrorNames.DID_NOT_VERIFIED = "DID_Not_Verified"; AnchoringChannelErrorNames.INVALID_SIGNING_KEY = "Invalid_Signing_Key"; AnchoringChannelErrorNames.NOT_SUPPORTED_SIGNATURE = "Not_Supported_Signature"; AnchoringChannelErrorNames.INVALID_DATA_TYPE = "Invalid_Data_Type"; AnchoringChannelErrorNames.JSON_DOC_NOT_SIGNED = "JSON_Doc_Not_Signed"; var channelHelper = {}; var __createBinding$3 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault$3 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$3 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$3(result, mod, k); __setModuleDefault$3(result, mod); return result; }; var __awaiter$9 = (commonjsGlobal && commonjsGlobal.__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()); }); }; Object.defineProperty(channelHelper, "__esModule", { value: true }); channelHelper.ChannelHelper = void 0; const iota_streams_wasm_1$4 = require$$0__default['default']; const crypto$2 = __importStar$3(require$$1__default['default']); class ChannelHelper { /** * Generates a new seed * @param length Seed length * * @returns The seed */ static generateSeed(length = 20) { const alphabet = "abcdefghijklmnopqrstuvwxyz"; let seed = ""; while (seed.length < length) { const bytes = crypto$2.randomBytes(1); seed += alphabet[bytes[0] % alphabet.length]; } return seed; } /** * Finds an anchorage message on the channel by going through the messages * * @param subs Subscriber * @param anchorageID The anchorage identifier * * @returns whether it has been found and the link to the anchorage on the Channel */ static findAnchorage(subs, anchorageID) { return __awaiter$9(this, void 0, void 0, function* () { let found = false; let anchorageLink; // First we try to read such message const candidateLink = iota_streams_wasm_1$4.Address.from_string(`${subs.clone().channel_address()}:${anchorageID}`); let response; try { response = yield subs.clone().receive_signed_packet(candidateLink); } catch (_a) { // The message has not been found } if (response) { anchorageLink = response.get_link().copy(); found = true; } // Iteratively retrieve messages until We find the one to anchor to while (!found) { const messages = yield subs.clone().fetch_next_msgs(); if (!messages || messages.length === 0) { break; } // In our case only one message is expected anchorageLink = messages[0].get_link().copy(); if (anchorageLink.msg_id === anchorageID) { found = true; } } return { found, anchorageLink }; }); } } channelHelper.ChannelHelper = ChannelHelper; var initializationHelper = {}; var __createBinding$2 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault$2 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$2 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$2(result, mod, k); __setModuleDefault$2(result, mod); return result; }; Object.defineProperty(initializationHelper, "__esModule", { value: true }); const iota_streams_wasm_1$3 = require$$0__default['default']; const fetch$1 = __importStar$2(require$$1__default$1['default']); /** * Initialization function for the Streams WASM bindings */ function initialize() { // @ts-expect-error Streams WASM bindings need it commonjsGlobal.fetch = fetch$1; // @ts-expect-error Streams WASM bindings need it commonjsGlobal.Headers = fetch$1.Headers; // @ts-expect-error Streams WASM bindings need it commonjsGlobal.Request = fetch$1.Request; // @ts-expect-error Streams WASM bindings need it commonjsGlobal.Response = fetch$1.Response; iota_streams_wasm_1$3.set_panic_hook(); } initializationHelper.default = initialize; var validationHelper = {}; Object.defineProperty(validationHelper, "__esModule", { value: true }); class ValidationHelper { static url(input) { try { // eslint-disable-next-line no-new new URL(input); } catch (_a) { return false; } return true; } static did(input) { const regex = /^did:[\da-z]+:[\w.-]+/; return regex.test(input); } } validationHelper.default = ValidationHelper; var anchorMsgService = {}; var __awaiter$8 = (commonjsGlobal && commonjsGlobal.__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 __importDefault$8 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(anchorMsgService, "__esModule", { value: true }); /* eslint-disable no-duplicate-imports */ const iota_streams_wasm_1$2 = require$$0__default['default']; const anchoringChannelError_1$8 = __importDefault$8(anchoringChannelError); const anchoringChannelErrorNames_1$8 = __importDefault$8(anchoringChannelErrorNames); const channelHelper_1$3 = channelHelper; /** * Service to deal with message anchors * */ class AnchorMsgService { /** * Anchors a message to an anchorage * * @param request The anchoring details * * @returns The result or error */ static anchor(request) { return __awaiter$8(this, void 0, void 0, function* () { try { // The address of the anchorage message const anchorageID = request.anchorageID; // The subscriber const subs = request.subscriber; const announceMsgID = request.channelID.split(":")[1]; let anchorageLink; let found = true; if (announceMsgID === anchorageID) { anchorageLink = iota_streams_wasm_1$2.Address.from_string(request.channelID).copy(); } else { // If we are not anchoring to the announce Msg ID we find the proper anchorage // Iteratively retrieve messages until We find the one to anchor to ({ found, anchorageLink } = yield channelHelper_1$3.ChannelHelper.findAnchorage(subs, anchorageID)); if (!found) { throw new anchoringChannelError_1$8.default(anchoringChannelErrorNames_1$8.default.ANCHORAGE_NOT_FOUND, `The anchorage ${anchorageID} has not been found on the channel`); } } const publicPayload = Buffer.from(request.message); const maskedPayload = Buffer.from(""); const anchoringResp = yield subs.clone().send_signed_packet(anchorageLink, publicPayload, maskedPayload); const msgID = anchoringResp.get_link().msg_id; return { anchorageID, msgID }; } catch (error) { if (error.type === anchoringChannelError_1$8.default.ERR_TYPE) { throw error; } throw new anchoringChannelError_1$8.default(anchoringChannelErrorNames_1$8.default.OTHER_ERROR, `Error while anchoring to ${request.anchorageID} on ${request.channelID} -> ${error}`); } }); } } anchorMsgService.default = AnchorMsgService; var channelService = {}; var __awaiter$7 = (commonjsGlobal && commonjsGlobal.__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 __importDefault$7 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(channelService, "__esModule", { value: true }); const iota_streams_wasm_1$1 = require$$0__default['default']; const anchoringChannelError_1$7 = __importDefault$7(anchoringChannelError); const anchoringChannelErrorNames_1$7 = __importDefault$7(anchoringChannelErrorNames); /** * Service to interact with IOTA Streams Channels * */ class ChannelService { /** * Creates a new Channel * @param node The node on which the channel is created * @param seed The channel's seed * * @returns The address of the channel created and the announce message ID * */ static createChannel(node, seed) { return __awaiter$7(this, void 0, void 0, function* () { const options = new iota_streams_wasm_1$1.SendOptions(node, true); const auth = new iota_streams_wasm_1$1.Author(seed, options.clone(), iota_streams_wasm_1$1.ChannelType.SingleBranch); const response = yield auth.clone().send_announce(); const announceLink = response.get_link().copy(); return { announceMsgID: announceLink.msg_id, channelAddress: auth.channel_address() }; }); } /** * Binds to a channel by creating the corresponding IOTA Streams Subscriber and reading * the announce message * * @param request The channel details * * @returns IOTA Streams Subscriber object */ static bindToChannel(request) { return __awaiter$7(this, void 0, void 0, function* () { try { const options = new iota_streams_wasm_1$1.SendOptions(request.node, true); const subs = new iota_streams_wasm_1$1.Subscriber(request.seed, options.clone()); // Channel contains the channel address and the announce messageID const channel = request.channelID; const announceLink = iota_streams_wasm_1$1.Address.from_string(channel).copy(); yield subs.clone().receive_announcement(announceLink); return subs; } catch (_a) { throw new anchoringChannelError_1$7.default(anchoringChannelErrorNames_1$7.default.CHANNEL_BINDING_ERROR, `Cannot bind to channel ${request.channelID}`); } }); } } channelService.default = ChannelService; var fetchMsgService = {}; var __awaiter$6 = (commonjsGlobal && commonjsGlobal.__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 __importDefault$6 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(fetchMsgService, "__esModule", { value: true }); /* eslint-disable no-duplicate-imports */ const iota_streams_wasm_1 = require$$0__default['default']; const anchoringChannelError_1$6 = __importDefault$6(anchoringChannelError); const anchoringChannelErrorNames_1$6 = __importDefault$6(anchoringChannelErrorNames); const channelHelper_1$2 = channelHelper; class FetchMsgService { static fetch(request) { return __awaiter$6(this, void 0, void 0, function* () { const subs = request.subscriber; const announceMsgID = request.channelID.split(":")[1]; const anchorageID = request.anchorageID; let found = true; if (anchorageID !== announceMsgID) { ({ found } = yield channelHelper_1$2.ChannelHelper.findAnchorage(subs, anchorageID)); } if (!found) { throw new anchoringChannelError_1$6.default(anchoringChannelErrorNames_1$6.default.ANCHORAGE_NOT_FOUND, `The anchorage point ${anchorageID} has not been found on the channel`); } const msgID = request.msgID; const msgLink = iota_streams_wasm_1.Address.from_string(`${subs.clone().channel_address()}:${msgID}`); let response; try { response = yield subs.clone().receive_signed_packet(msgLink); } catch (_a) { throw new anchoringChannelError_1$6.default(anchoringChannelErrorNames_1$6.default.MSG_NOT_FOUND, `The message ${msgID} has not been found on the Channel`); } const messageContent = Buffer.from(response.get_message().get_public_payload()).toString(); const receivedMsgID = response.get_link().copy().msg_id; if (receivedMsgID !== msgID) { throw new Error("Requested message ID and fetched message ID are not equal"); } const pk = response.get_message().get_pk(); return { message: messageContent, msgID, pk }; }); } } fetchMsgService.default = FetchMsgService; var __awaiter$5 = (commonjsGlobal && commonjsGlobal.__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 __importDefault$5 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(iotaAnchoringChannel, "__esModule", { value: true }); iotaAnchoringChannel.IotaAnchoringChannel = void 0; const anchoringChannelError_1$5 = __importDefault$5(anchoringChannelError); const anchoringChannelErrorNames_1$5 = __importDefault$5(anchoringChannelErrorNames); const channelHelper_1$1 = channelHelper; const initializationHelper_1 = __importDefault$5(initializationHelper); const validationHelper_1$2 = __importDefault$5(validationHelper); const anchorMsgService_1 = __importDefault$5(anchorMsgService); const channelService_1 = __importDefault$5(channelService); const fetchMsgService_1 = __importDefault$5(fetchMsgService); // Needed for the Streams WASM bindings initializationHelper_1.default(); class IotaAnchoringChannel { constructor(node, seed) { this._node = node; this._seed = seed; if (!seed) { this._seed = channelHelper_1$1.ChannelHelper.generateSeed(); } } /** * Creates a new Anchoring Channel * * @param node The node * @param seed The seed * * @returns The anchoring channel */ static create(node, seed) { if (!validationHelper_1$2.default.url(node)) { throw new anchoringChannelError_1$5.default(anchoringChannelErrorNames_1$5.default.INVALID_NODE, "The node has to be a URL"); } return new IotaAnchoringChannel(node, seed); } /** * Binds to an existing channel or creates a new binding * * @param channelID in the form of 'channel_address:announce_msg_id' * * @returns reference to the channel * */ bind(channelID) { return __awaiter$5(this, void 0, void 0, function* () { if (this._subscriber) { throw new anchoringChannelError_1$5.default(anchoringChannelErrorNames_1$5.default.CHANNEL_ALREADY_BOUND, `Channel already bound to ${this._channelID}`); } if (!channelID) { const { channelAddress, announceMsgID } = yield channelService_1.default.createChannel(this._node, this._seed); this._channelAddress = channelAddress; this._announceMsgID = announceMsgID; this._channelID = `${channelAddress}:${announceMsgID}`; } else { const components = channelID.split(":"); if (Array.isArray(components) && components.length === 2) { this._channelID = channelID; this._channelAddress = components[0]; this._announceMsgID = components[1]; } else { throw new anchoringChannelError_1$5.default(anchoringChannelErrorNames_1$5.default.CHANNEL_BINDING_ERROR, `Invalid channel identifier: ${channelID}`); } } const bindRequest = { node: this._node, seed: this._seed, channelID: this._channelID }; this._subscriber = yield channelService_1.default.bindToChannel(bindRequest); return this; }); } /** * Returns the channelID ('channelAddress:announce_msg_id') * * @returns channel ID * */ get channelID() { return this._channelID; } /** * Returns the channel's address * * @returns channel address * */ get channelAddr() { return this._channelAddress; } /** * Returns the channel's first anchorage ID * * @returns anchorageID * */ get firstAnchorageID() { return this._announceMsgID; } /** * Returns the channel's node * * @returns node * */ get node() { return this._node; } /** * Returns the channel's seed * * @returns seed * */ get seed() { return this._seed; } /** * Anchors a message to the anchoring channel * * @param anchorageID The anchorage * @param message Message to be anchored * * @returns The result of the operation * */ anchor(anchorageID, message) { return __awaiter$5(this, void 0, void 0, function* () { if (!this._channelAddress) { throw new anchoringChannelError_1$5.default(anchoringChannelErrorNames_1$5.default.CHANNEL_NOT_BOUND, "Unbound anchoring channel. Please call bind first"); } const request = { channelID: this._channelID, subscriber: this._subscriber, message, anchorageID }; const result = yield anchorMsgService_1.default.anchor(request); return result; }); } /** * Fetches a previously anchored message * * @param anchorageID The anchorage point * @param messageID The ID of the message * * @returns The fetch result */ fetch(anchorageID, messageID) { return __awaiter$5(this, void 0, void 0, function* () { if (!this._channelAddress) { throw new anchoringChannelError_1$5.default(anchoringChannelErrorNames_1$5.default.CHANNEL_NOT_BOUND, "Unbound anchoring channel. Please call bind first"); } const request = { channelID: this._channelID, subscriber: this._subscriber, msgID: messageID, anchorageID }; return fetchMsgService_1.default.fetch(request); }); } } iotaAnchoringChannel.IotaAnchoringChannel = IotaAnchoringChannel; var iotaSigner = {}; var jsonCanonicalization = {}; Object.defineProperty(jsonCanonicalization, "__esModule", { value: true }); jsonCanonicalization.JsonCanonicalization = void 0; class JsonCanonicalization { /** * Calculates the canonical serialization of a JSON document * * @param input The input * * @returns The serialization as a string * */ static calculate(input) { let buffer = ""; serialize(input); return buffer; /** * Serializes in canonical format * * @param object The object to be serialized */ function serialize(object) { if (object === null || typeof object !== "object") { // /////////////////////////////////////////////// // Primitive data type - Use ES6/JSON // // /////////////////////////////////////////////// buffer += JSON.stringify(object); } else if (Array.isArray(object)) { // /////////////////////////////////////////////// // Array - Maintain element order // // /////////////////////////////////////////////// buffer += "["; let next = false; object.forEach(element => { if (next) { buffer += ","; } next = true; // /////////////////////////////////////// // Array element - Recursive expansion // // /////////////////////////////////////// serialize(element); }); buffer += "]"; } else { // /////////////////////////////////////////////// // Object - Sort properties before serializing // // /////////////////////////////////////////////// buffer += "{"; let next = false; Object.keys(object).sort() .forEach(property => { if (next) { buffer += ","; } next = true; // ///////////////////////////////////////////// // Property names are strings - Use ES6/JSON // // ///////////////////////////////////////////// buffer += JSON.stringify(property); buffer += ":"; // //////////////////////////////////////// // Property value - Recursive expansion // // //////////////////////////////////////// serialize(object[property]); }); buffer += "}"; } } } } jsonCanonicalization.JsonCanonicalization = JsonCanonicalization; var jsonHelper = {}; var __importDefault$4 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(jsonHelper, "__esModule", { value: true }); const anchoringChannelError_1$4 = __importDefault$4(anchoringChannelError); const anchoringChannelErrorNames_1$4 = __importDefault$4(anchoringChannelErrorNames); class JsonHelper { static getDocument(doc) { if ((typeof doc !== "string" && typeof doc !== "object") || Array.isArray(doc)) { throw new anchoringChannelError_1$4.default(anchoringChannelErrorNames_1$4.default.INVALID_DATA_TYPE, "Please provide a Javascript object or string in JSON format"); } let document; if (typeof doc === "string") { try { document = JSON.parse(doc); } catch (_a) { throw new anchoringChannelError_1$4.default(anchoringChannelErrorNames_1$4.default.INVALID_DATA_TYPE, "Invalid JSON Format"); } } else { document = JSON.parse(JSON.stringify(doc)); } return document; } static getSignedDocument(doc) { const result = this.getDocument(doc); if (!result.proof) { throw new anchoringChannelError_1$4.default(anchoringChannelErrorNames_1$4.default.JSON_DOC_NOT_SIGNED, "The provided JSON document does not include a proof"); } return result; } static getJsonLdDocument(doc) { const result = this.getDocument(doc); if (!result["@context"]) { throw new anchoringChannelError_1$4.default(anchoringChannelErrorNames_1$4.default.INVALID_DATA_TYPE, "Not a JSON-LD document. Use 'signJson' instead"); } return result; } static getSignedJsonLdDocument(doc) { const result = this.getJsonLdDocument(doc); if (!result.proof) { throw new anchoringChannelError_1$4.default(anchoringChannelErrorNames_1$4.default.JSON_DOC_NOT_SIGNED, "The provided JSON document does not include a proof"); } return result; } } jsonHelper.default = JsonHelper; var jsonLdHelper = {}; var __awaiter$4 = (commonjsGlobal && commonjsGlobal.__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()); }); }; Object.defineProperty(jsonLdHelper, "__esModule", { value: true }); jsonLdHelper.customLdContextLoader = void 0; const JSON$1 = "application/json"; const JSON_LD = "application/ld+json"; /** * JSON-LD @context loader * * @param url The URL of the LD @context * @param options Options * * @returns the LD document and the final URL after following redirects * */ function customLdContextLoader(url, options) { var _a, _b; return __awaiter$4(this, void 0, void 0, function* () { const headers = new Headers(); headers.append("accept", `${JSON$1},${JSON_LD}`); const response = yield fetch(url); let document; let documentUrl = url; if (response.ok) { const respMimeType = response.headers.get("content-type").toLowerCase(); // If this is not a JSON-LD @context but there is an alternate representation // which MIME type is JSON-LD we follow our nose if (respMimeType !== JSON$1 && respMimeType !== JSON_LD) { // Let's check if there is a Link alternate header const link = response.headers.get("link"); const components = link.split(";"); if ((_a = components[1]) === null || _a === void 0 ? void 0 : _a.includes("alternate")) { if ((_b = components[2]) === null || _b === void 0 ? void 0 : _b.includes(JSON_LD)) { const bracketsLinkPath = components[0]; // Remove link's brackets const extraPath = components[0].slice(1, bracketsLinkPath.length - 1); // This is the alternate representation const contextUrl = `${url}${extraPath}`; // Only the link is followed to the alternate representation if it is a different one if (contextUrl !== url) { return customLdContextLoader(contextUrl); } } } } else { document = yield response.json(); if (response.redirected) { documentUrl = response.url; } } } else { console.error(`The JSON-LD @context ${url} cannot be retrieved`); } return { document, documentUrl // this is the actual context URL after redirects }; }); } jsonLdHelper.customLdContextLoader = customLdContextLoader; var ldContextURL = {}; Object.defineProperty(ldContextURL, "__esModule", { value: true }); ldContextURL.LdContextURL = void 0; class LdContextURL { } ldContextURL.LdContextURL = LdContextURL; LdContextURL.W3C_SECURITY = "https://w3id.org/security/v1"; var signatureTypes = {}; Object.defineProperty(signatureTypes, "__esModule", { value: true }); signatureTypes.SignatureTypes = void 0; class SignatureTypes { } signatureTypes.SignatureTypes = SignatureTypes; SignatureTypes.ED25519_2018 = "Ed25519Signature2018"; SignatureTypes.JCS_ED25519_2020 = "JcsEd25519Signature2020"; var didService = {}; var identity_wasm = {exports: {}}; (function (module) { const fetch = require$$1__default$1['default']; commonjsGlobal.Headers = fetch.Headers; commonjsGlobal.Request = fetch.Request; commonjsGlobal.Response = fetch.Response; commonjsGlobal.fetch = fetch; let imports = {}; imports['__wbindgen_placeholder__'] = module.exports; let wasm; const { TextDecoder, TextEncoder, inspect } = require(String.raw`util`); let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); cachedTextDecoder.decode(); let cachegetUint8Memory0 = null; function getUint8Memory0() { if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) { cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer); } return cachegetUint8Memory0; } function getStringFromWasm0(ptr, len) { return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } const heap = new Array(32).fill(undefined); heap.push(undefined, null, true, false); let heap_next = heap.length; function addHeapObject(obj) { if (heap_next === heap.length) heap.push(heap.length + 1); const idx = heap_next; heap_next = heap[idx]; heap[idx] = obj; return idx; } function getObject(idx) { return heap[idx]; } let WASM_VECTOR_LEN = 0; let cachedTextEncoder = new TextEncoder('utf-8'); const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' ? function (arg, view) { return cachedTextEncoder.encodeInto(arg, view); } : function (arg, view) { const buf = cachedTextEncoder.encode(arg); view.set(buf); return { read: arg.length, written: buf.length }; }); function passStringToWasm0(arg, malloc, realloc) { if (realloc === undefined) { const buf = cachedTextEncoder.encode(arg); const ptr = malloc(buf.length); getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); WASM_VECTOR_LEN = buf.length; return ptr; } let len = arg.length; let ptr = malloc(len); const mem = getUint8Memory0(); let offset = 0; for (; offset < len; offset++) { const code = arg.charCodeAt(offset); if (code > 0x7F) break; mem[ptr + offset] = code; } if (offset !== len) { if (offset !== 0) { arg = arg.slice(offset); } ptr = realloc(ptr, len, len = offset + arg.length * 3); const view = getUint8Memory0().subarray(ptr + offset, ptr + len); const ret = encodeString(arg, view); offset += ret.written; } WASM_VECTOR_LEN = offset; return ptr; } let cachegetInt32Memory0 = null; function getInt32Memory0() { if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) { cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer); } return cachegetInt32Memory0; } function dropObject(idx) { if (idx < 36) return; heap[idx] = heap_next; heap_next = idx; } function takeObject(idx) { const ret = getObject(idx); dropObject(idx); return ret; } function isLikeNone(x) { return x === undefined || x === null; } function debugString(val) { // primitive types const type = typeof val; if (type == 'number' || type == 'boolean' || val == null) { return `${val}`; } if (type == 'string') { return `"${val}"`; } if (type == 'symbol') { const description = val.description; if (description == null) { return 'Symbol'; } else { return `Symbol(${description})`; } } if (type == 'function') { const name = val.name; if (typeof name == 'string' && name.length > 0) { return `Function(${name})`; } else { return 'Function'; } } // objects if (Array.isArray(val)) { const length = val.length; let debug = '['; if (length > 0) { debug += debugString(val[0]); } for(let i = 1; i < length; i++) { debug += ', ' + debugString(val[i]); } debug += ']'; return debug; } // Test for built-in const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); let className; if (builtInMatches.length > 1) { className = builtInMatches[1]; } else { // Failed to match the standard '[object ClassName]' return toString.call(val); } if (className == 'Object') { // we're a user defined class or Object // JSON.stringify avoids problems with cycles, and is generally much // easier than looping through ownProperties of `val`. try { return 'Object(' + JSON.stringify(val) + ')'; } catch (_) { return 'Object'; } } // errors if (val instanceof Error) { return `${val.name}: ${val.message}\n${val.stack}`; } // TODO we could test for more things here, like `Set`s and `Map`s. return className; } function makeMutClosure(arg0, arg1, dtor, f) { const state = { a: arg0, b: arg1, cnt: 1, dtor }; const real = (...args) => { // First up with a closure we increment the internal reference // count. This ensures that the Rust closure environment won't // be deallocated while we're invoking it. state.cnt++; const a = state.a; state.a = 0; try { return f(a, state.b, ...args); } finally { if (--state.cnt === 0) { wasm.__wbindgen_export_2.get(state.dtor)(a, state.b); } else { state.a = a; } } }; real.original = state; return real; } function __wbg_adapter_30(arg0, arg1, arg2) { wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hbee689cb88024203(arg0, arg1, addHeapObject(arg2)); } function _assertClass(instance, klass) { if (!(instance instanceof klass)) { throw new Error(`expected instance of ${klass.name}`); } return instance.ptr; } let stack_pointer = 32; function addBorrowedObject(obj) { if (stack_pointer == 1) throw new Error('out of js stack'); heap[--stack_pointer] = obj; return stack_pointer; } /** * Initializes the console error panic hook for better error messages */ module.exports.start = function() { wasm.start(); }; /** * Publishes a DID Document to the Tangle, params looks like { node: "http://localhost:14265", network: "main" } * @param {any} document * @param {any} params * @returns {any} */ module.exports.publish = function(document, params) { var ret = wasm.publish(addHeapObject(document), addHeapObject(params)); return takeObject(ret); }; /** * Resolves the latest DID Document from the Tangle, params looks like { node: "http://localhost:14265", network: "main" } * @param {string} did * @param {any} params * @returns {any} */ module.exports.resolve = function(did, params) { var ptr0 = passStringToWasm0(did, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; var ret = wasm.resolve(ptr0, len0, addHeapObject(params)); return takeObject(ret); }; /** * Validates a credential with the DID Document from the Tangle, params looks like { node: "http://localhost:14265", network: "main" } * @param {string} data * @param {any} params * @returns {any} */ module.exports.checkCredential = function(data, params) { var ptr0 = passStringToWasm0(data, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; var ret = wasm.checkCredential(ptr0, len0, addHeapObject(params)); return takeObject(ret); }; /** * Validates a presentation with the DID Document from the Tangle, params looks like { node: "http://localhost:14265", network: "main" } * @param {string} data * @param {any} params * @returns {any} */ module.exports.checkPresentation = function(data, params) { var ptr0 = passStringToWasm0(data, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; var ret = wasm.checkPresentation(ptr0, len0, addHeapObject(params)); return takeObject(ret); }; const u32CvtShim = new Uint32Array(2); const uint64CvtShim = new BigUint64Array(u32CvtShim.buffer); function handleError(f, args) { try { return f.apply(this, args); } catch (e) { wasm.__wbindgen_exn_store(addHeapObject(e)); } } function getArrayU8FromWasm0(ptr, len) { return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len); } function __wbg_adapter_222(arg0, arg1, arg2, arg3) { wasm.wasm_bindgen__convert__closures__invoke2_mut__h5596c51b6c4da58d(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); } /** */ module.exports.Digest = Object.freeze({ Sha256:1,"1":"Sha256", }); /** */ module.exports.KeyType = Object.freeze({ Ed25519:1,"1":"Ed25519", }); /** */ class AuthenticationRequest { static __wrap(ptr) { const obj = Object.create(AuthenticationRequest.prototype); obj.ptr = ptr; return obj; } toJSON() { return { }; } toString() { return JSON.stringify(this); } [inspect.custom]() { return Object.assign(Object.create({constructor: this.constructor}), this.toJSON()); } __destroy_into_raw() { const ptr = this.ptr; this.ptr = 0; return ptr; } free() { const ptr = this.__destroy_into_raw(); wasm.__wbg_authenticationrequest_free(ptr); } /** * @returns {any} */ toJSON() { var ret = wasm.authenticationrequest_toJSON(this.ptr); return takeObject(ret); } /** * @param {any} value * @returns {AuthenticationRequest} */ static fromJSON(value) { try { var ret = wasm.authenticationrequest_fromJSON(addBorrowedObject(value)); return AuthenticationRequest.__wrap(ret); } finally { heap[stack_pointer++] = undefined; } } } module.exports.AuthenticationRequest = AuthenticationRequest; /** */ class AuthenticationResponse { static __wrap(ptr) { const obj = Object.create(AuthenticationResponse.prototype); obj.ptr = ptr; return obj; } toJSON() { return { }; } toString() { return JSON.stringify(this); } [inspect.custom]() { return Object.assign(Object.create({constructor: this.constructor}), this.toJSON()); } __destroy_into_raw() { const ptr = this.ptr; this.ptr = 0; return ptr; } free() { const ptr = this.__destroy_into_raw(); wasm.__wbg_authenticationresponse_free(ptr); } /** * @returns {any} */ toJSON() { var ret = wasm.authenticationresponse_toJSON(this.ptr); return takeObject(ret); } /** * @param {any} value * @returns {AuthenticationResponse} */ static fromJSON(value) { try { var ret = wasm.authenticationresponse_fromJSON(addBorrowedObject(value)); return AuthenticationResponse.__wrap(ret); } finally { heap[stack_pointer++] = undefined; } } } module.exports.AuthenticationResponse = AuthenticationResponse; /** */ class CredentialIssuance { static __wrap(ptr) { const obj = Object.create(CredentialIssuance.prototype); obj.ptr = ptr; return obj; } toJSON() { return { }; } toString() { return JSON.stringify(this); } [inspect.custom]() { return Object.assign(Object.create({constructor: this.constructor}), this.toJSON()); } __destroy_into_raw() { const ptr = this.ptr; this.ptr = 0; return ptr; } free() { const ptr = this.__destroy_into_raw(); wasm.__wbg_credentialissuance_free(ptr); } /** * @returns {any} */ toJSON() { var ret = wasm.credentialissuance_toJSON(this.ptr); return takeObject(ret); } /** * @param {any} value * @returns {CredentialIssuance} */ static fromJSON(value) { try { var ret = wasm.credentialissuance_fromJSON(addBorrowedObject(value)); return CredentialIssuance.__wrap(ret); } finally { heap[stack_pointer++] = undefined; } } } module.exports.CredentialIssuance = CredentialIssuance; /** */ class CredentialOptionRequest { static __wrap(ptr) { const obj = Object.create(CredentialOptionRequest.prototype); obj.ptr = ptr; return obj; } toJSON() { return { }; } toString() { return JSON.stringify(this); } [inspect.custom]() { return Object.assign(Object.create({constructor: this.constructor}), this.toJSON()); } __destroy_into_raw() { const ptr = this.ptr; this.ptr = 0; return ptr; } free() { const ptr = this.__destroy_into_raw(); wasm.__wbg_credentialoptionrequest_free(ptr); } /** * @returns {any} */ toJSON() { var ret = wasm.credentialoptionrequest_toJSON(this.ptr); return takeObject(ret); } /** * @param {any} value * @returns {CredentialOptionRequest} */ static fromJSON(value) { try { var ret = wasm.credentialoptionrequest_fromJSON(addBorrowedObject(value)); return CredentialOptionRequest.__wrap(ret); } finally { heap[stack_pointer++] = undefined; } } } module.exports.CredentialOptionRequest = CredentialOptionRequest; /** */ class CredentialOptionResponse { static __wrap(ptr) { const obj = Object.create(CredentialOptionResponse.prototype); obj.ptr = ptr; return obj; } toJSON() { return { }; } toString() { return JSON.stringify(this); } [inspect.custom]() { return Object.assign(Object.create({constructor: this.constructor}), this.toJSON()); } __destroy_into_raw() { const ptr = this.ptr; this.ptr = 0; return ptr; } free() { const ptr = this.__destroy_into_raw(); wasm.__wbg_credentialoptionresponse_free(ptr); } /** * @returns {any} */ toJSON() { var ret = wasm.credentialoptionresponse_toJSON(this.ptr); return takeObject(ret); } /** * @param {any} value * @returns {CredentialOptionResponse} */ static fromJSON(value) { try { var ret = wasm.credentialoptionresponse_fromJSON(addBorrowedObject(value)); return CredentialOptionResponse.__wrap(ret); } finally { heap[stack_pointer++] = undefined; } } } module.exports.CredentialOptionResponse = CredentialOptionResponse; /** */ class CredentialRevocation { static __wrap(ptr) { const obj = Object.create(CredentialRevocation.prototype); obj.ptr = ptr; return obj; } toJSON() { return { }; } toString(