UNPKG

@enbox/api

Version:

SDK for accessing the features and capabilities of Web5

471 lines 27.5 kB
"use strict"; /** * NOTE: Added reference types here to avoid a `pnpm` bug during build. * https://github.com/TBD54566975/web5-js/pull/507 */ /// <reference types="@enbox/dwn-sdk-js" /> var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; 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 __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; 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 __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)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Web5 = void 0; var user_agent_1 = require("@enbox/user-agent"); var agent_1 = require("@enbox/agent"); var did_api_js_1 = require("./did-api.js"); var dwn_api_js_1 = require("./dwn-api.js"); var vc_api_js_1 = require("./vc-api.js"); var permission_grant_js_1 = require("./permission-grant.js"); /** * The main Web5 API interface. It manages the creation of a DID if needed, the connection to the * local DWN and all the web5 main foundational APIs such as VC, syncing, etc. */ var Web5 = /** @class */ (function () { function Web5(_a) { var agent = _a.agent, connectedDid = _a.connectedDid, delegateDid = _a.delegateDid; this.agent = agent; this.did = new did_api_js_1.DidApi({ agent: agent, connectedDid: connectedDid }); this.dwn = new dwn_api_js_1.DwnApi({ agent: agent, connectedDid: connectedDid, delegateDid: delegateDid }); this.vc = new vc_api_js_1.VcApi({ agent: agent, connectedDid: connectedDid }); } /** * Connects to a {@link Web5Agent}. Defaults to creating a local {@link Web5UserAgent} if one * isn't provided. * * If `walletConnectOptions` are provided, a WalletConnect flow will be initiated to import a delegated DID from an external wallet. * If there is a failure at any point during connecting and processing grants, all created DIDs and Identities as well as the provided grants * will be cleaned up and an error thrown. This allows for subsequent Connect attempts to be made without any errors. * * @param options - Optional overrides that can be provided when calling {@link Web5.connect}. * @returns A promise that resolves to a {@link Web5} instance and the connected DID. */ Web5.connect = function (_a) { var _b, _c, _d; var _e = _a === void 0 ? {} : _a, agent = _e.agent, agentVault = _e.agentVault, connectedDid = _e.connectedDid, password = _e.password, recoveryPhrase = _e.recoveryPhrase, sync = _e.sync, techPreview = _e.techPreview, didCreateOptions = _e.didCreateOptions, registration = _e.registration, walletConnectOptions = _e.walletConnectOptions; return __awaiter(this, void 0, void 0, function () { var delegateDid, registerSync, userAgent, serviceEndpointNodes, connectedIdentity, identity, connectedProtocols, permissionRequests, connectOptions, walletPermissionRequests, _f, delegatePortableDid, connectedDid_1, delegateGrants, error_1, identities, existingIdentityCount, serviceEndpointNodes_1, serviceEndpointNodes_1_1, dwnEndpoint, serverInfo, e_1_1, error_2, web5; var e_1, _g; return __generator(this, function (_h) { switch (_h.label) { case 0: if (!(agent === undefined)) return [3 /*break*/, 36]; registerSync = false; return [4 /*yield*/, user_agent_1.Web5UserAgent.create({ agentVault: agentVault })]; case 1: userAgent = _h.sent(); agent = userAgent; // Warn the developer and application user of the security risks of using a static password. if (password === undefined) { password = 'insecure-static-phrase'; console.warn('%cSECURITY WARNING:%c ' + 'You have not set a password, which defaults to a static, guessable value. ' + 'This significantly compromises the security of your data. ' + 'Please configure a secure, unique password.', 'font-weight: bold; color: red;', 'font-weight: normal; color: inherit;'); } serviceEndpointNodes = (_c = (_b = techPreview === null || techPreview === void 0 ? void 0 : techPreview.dwnEndpoints) !== null && _b !== void 0 ? _b : didCreateOptions === null || didCreateOptions === void 0 ? void 0 : didCreateOptions.dwnEndpoints) !== null && _c !== void 0 ? _c : ['https://enbox-production.up.railway.app']; return [4 /*yield*/, userAgent.firstLaunch()]; case 2: if (!_h.sent()) return [3 /*break*/, 4]; return [4 /*yield*/, userAgent.initialize({ password: password, recoveryPhrase: recoveryPhrase, dwnEndpoints: serviceEndpointNodes })]; case 3: recoveryPhrase = _h.sent(); _h.label = 4; case 4: return [4 /*yield*/, userAgent.start({ password: password })]; case 5: _h.sent(); return [4 /*yield*/, userAgent.identity.connectedIdentity()]; case 6: connectedIdentity = _h.sent(); identity = void 0; connectedProtocols = []; if (!connectedIdentity) return [3 /*break*/, 7]; // if a connected identity is found, use it // TODO: In the future, implement a way to re-connect an already connected identity and apply additional grants/protocols identity = connectedIdentity; return [3 /*break*/, 19]; case 7: if (!walletConnectOptions) return [3 /*break*/, 15]; if (sync === 'off') { // Currently we require sync to be enabled when using WalletConnect // This is to ensure a connected app is not in a disjointed state from any other clients/app using the connectedDid throw new Error('Sync must not be disabled when using WalletConnect'); } // Since we are connecting a new identity, we will want to register sync for the connectedDid registerSync = true; _h.label = 8; case 8: _h.trys.push([8, 12, , 14]); permissionRequests = walletConnectOptions.permissionRequests, connectOptions = __rest(walletConnectOptions, ["permissionRequests"]); walletPermissionRequests = permissionRequests.map(function (_a) { var protocolDefinition = _a.protocolDefinition, permissions = _a.permissions; return agent_1.WalletConnect.createPermissionRequestForProtocol({ definition: protocolDefinition, permissions: permissions !== null && permissions !== void 0 ? permissions : [ 'read', 'write', 'delete', 'query', 'subscribe' ] }); }); return [4 /*yield*/, agent_1.WalletConnect.initClient(__assign(__assign({}, connectOptions), { permissionRequests: walletPermissionRequests }))]; case 9: _f = _h.sent(), delegatePortableDid = _f.delegatePortableDid, connectedDid_1 = _f.connectedDid, delegateGrants = _f.delegateGrants; return [4 /*yield*/, userAgent.identity.import({ portableIdentity: { portableDid: delegatePortableDid, metadata: { connectedDid: connectedDid_1, name: 'Default', uri: delegatePortableDid.uri, tenant: agent.agentDid.uri, } } })]; case 10: // Import the delegated DID as an Identity in the User Agent. // Setting the connectedDID in the metadata applies a relationship between the signer identity and the one it is impersonating. identity = _h.sent(); return [4 /*yield*/, this.processConnectedGrants({ agent: agent, delegateDid: delegatePortableDid.uri, grants: delegateGrants })]; case 11: // Attempts to process the connected grants to be used by the delegateDID // If the process fails, we want to clean up the identity // the connected grants will return a de-duped array of protocol URIs that are used to register sync for those protocols connectedProtocols = _h.sent(); return [3 /*break*/, 14]; case 12: error_1 = _h.sent(); // clean up the DID and Identity if import fails and throw // TODO: Implement the ability to purge all of our messages as a tenant return [4 /*yield*/, this.cleanUpIdentity({ identity: identity, userAgent: userAgent })]; case 13: // clean up the DID and Identity if import fails and throw // TODO: Implement the ability to purge all of our messages as a tenant _h.sent(); throw new Error("Failed to connect to wallet: ".concat(error_1.message)); case 14: return [3 /*break*/, 19]; case 15: return [4 /*yield*/, userAgent.identity.list()]; case 16: identities = _h.sent(); existingIdentityCount = identities.length; if (!(existingIdentityCount === 0)) return [3 /*break*/, 18]; // since we are creating a new identity, we will want to register sync for the created Did registerSync = true; return [4 /*yield*/, userAgent.identity.create({ didMethod: 'dht', metadata: { name: 'Default' }, didOptions: { services: [ { id: 'dwn', type: 'DecentralizedWebNode', serviceEndpoint: serviceEndpointNodes, enc: '#enc', sig: '#sig', } ], verificationMethods: [ { algorithm: 'Ed25519', id: 'sig', purposes: ['assertionMethod', 'authentication'] }, { algorithm: 'secp256k1', id: 'enc', purposes: ['keyAgreement'] } ] } })]; case 17: // Generate a new Identity for the end-user. identity = _h.sent(); return [3 /*break*/, 19]; case 18: // If multiple identities are found, use the first one. // TODO: Implement selecting a connectedDid from multiple identities identity = identities[0]; _h.label = 19; case 19: // If the stored identity has a connected DID, use it as the connected DID, otherwise use the identity's DID. connectedDid = (_d = identity.metadata.connectedDid) !== null && _d !== void 0 ? _d : identity.did.uri; // If the stored identity has a connected DID, use the identity DID as the delegated DID, otherwise it is undefined. delegateDid = identity.metadata.connectedDid ? identity.did.uri : undefined; if (!(registration !== undefined)) return [3 /*break*/, 32]; _h.label = 20; case 20: _h.trys.push([20, 31, , 32]); _h.label = 21; case 21: _h.trys.push([21, 28, 29, 30]); serviceEndpointNodes_1 = __values(serviceEndpointNodes), serviceEndpointNodes_1_1 = serviceEndpointNodes_1.next(); _h.label = 22; case 22: if (!!serviceEndpointNodes_1_1.done) return [3 /*break*/, 27]; dwnEndpoint = serviceEndpointNodes_1_1.value; return [4 /*yield*/, userAgent.rpc.getServerInfo(dwnEndpoint)]; case 23: serverInfo = _h.sent(); if (serverInfo.registrationRequirements.length === 0) { // no registration required return [3 /*break*/, 26]; } // register the agent DID return [4 /*yield*/, agent_1.DwnRegistrar.registerTenant(dwnEndpoint, agent.agentDid.uri)]; case 24: // register the agent DID _h.sent(); // register the connected Identity DID return [4 /*yield*/, agent_1.DwnRegistrar.registerTenant(dwnEndpoint, connectedDid)]; case 25: // register the connected Identity DID _h.sent(); _h.label = 26; case 26: serviceEndpointNodes_1_1 = serviceEndpointNodes_1.next(); return [3 /*break*/, 22]; case 27: return [3 /*break*/, 30]; case 28: e_1_1 = _h.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 30]; case 29: try { if (serviceEndpointNodes_1_1 && !serviceEndpointNodes_1_1.done && (_g = serviceEndpointNodes_1.return)) _g.call(serviceEndpointNodes_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 30: // If no failures occurred, call the onSuccess callback registration.onSuccess(); return [3 /*break*/, 32]; case 31: error_2 = _h.sent(); // for any failure, call the onFailure callback with the error registration.onFailure(error_2); return [3 /*break*/, 32]; case 32: if (!(sync !== 'off')) return [3 /*break*/, 36]; if (!registerSync) return [3 /*break*/, 35]; return [4 /*yield*/, userAgent.sync.registerIdentity({ did: connectedDid, options: { delegateDid: delegateDid, protocols: connectedProtocols } })]; case 33: _h.sent(); if (!(walletConnectOptions !== undefined)) return [3 /*break*/, 35]; // If we are using WalletConnect, we should do a one-shot sync to pull down any messages that are associated with the connectedDid return [4 /*yield*/, userAgent.sync.sync('pull')]; case 34: // If we are using WalletConnect, we should do a one-shot sync to pull down any messages that are associated with the connectedDid _h.sent(); _h.label = 35; case 35: // Enable sync using the specified interval or default. sync !== null && sync !== void 0 ? sync : (sync = '2m'); userAgent.sync.startSync({ interval: sync }) .catch(function (error) { console.error("Sync failed: ".concat(error)); }); _h.label = 36; case 36: web5 = new Web5({ agent: agent, connectedDid: connectedDid, delegateDid: delegateDid }); return [2 /*return*/, { web5: web5, did: connectedDid, delegateDid: delegateDid, recoveryPhrase: recoveryPhrase }]; } }); }); }; /** * Cleans up the DID, Keys and Identity. Primarily used by a failed WalletConnect import. * Does not throw on error, but logs to console. */ Web5.cleanUpIdentity = function (_a) { var identity = _a.identity, userAgent = _a.userAgent; return __awaiter(this, void 0, void 0, function () { var error_3, error_4; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2, , 3]); // Delete the DID and the Associated Keys return [4 /*yield*/, userAgent.did.delete({ didUri: identity.did.uri, tenant: identity.metadata.tenant, deleteKey: true, })]; case 1: // Delete the DID and the Associated Keys _b.sent(); return [3 /*break*/, 3]; case 2: error_3 = _b.sent(); console.error("Failed to delete DID ".concat(identity.did.uri, ": ").concat(error_3.message)); return [3 /*break*/, 3]; case 3: _b.trys.push([3, 5, , 6]); // Delete the Identity return [4 /*yield*/, userAgent.identity.delete({ didUri: identity.did.uri })]; case 4: // Delete the Identity _b.sent(); return [3 /*break*/, 6]; case 5: error_4 = _b.sent(); console.error("Failed to delete Identity ".concat(identity.metadata.name, ": ").concat(error_4.message)); return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); }; /** * A static method to process connected grants for a delegate DID. * * This will store the grants as the DWN owner to be used later when impersonating the connected DID. */ Web5.processConnectedGrants = function (_a) { var grants = _a.grants, agent = _a.agent, delegateDid = _a.delegateDid; return __awaiter(this, void 0, void 0, function () { var connectedProtocols, grants_1, grants_1_1, grantMessage, grant, status_1, protocol, e_2_1; var e_2, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: connectedProtocols = new Set(); _c.label = 1; case 1: _c.trys.push([1, 7, 8, 9]); grants_1 = __values(grants), grants_1_1 = grants_1.next(); _c.label = 2; case 2: if (!!grants_1_1.done) return [3 /*break*/, 6]; grantMessage = grants_1_1.value; return [4 /*yield*/, permission_grant_js_1.PermissionGrant.parse({ connectedDid: delegateDid, agent: agent, message: grantMessage })]; case 3: grant = _c.sent(); return [4 /*yield*/, grant.store(true)]; case 4: status_1 = (_c.sent()).status; if (status_1.code !== 202) { throw new Error("AgentDwnApi: Failed to process connected grant: ".concat(status_1.detail)); } protocol = grant.scope.protocol; if (protocol) { connectedProtocols.add(protocol); } _c.label = 5; case 5: grants_1_1 = grants_1.next(); return [3 /*break*/, 2]; case 6: return [3 /*break*/, 9]; case 7: e_2_1 = _c.sent(); e_2 = { error: e_2_1 }; return [3 /*break*/, 9]; case 8: try { if (grants_1_1 && !grants_1_1.done && (_b = grants_1.return)) _b.call(grants_1); } finally { if (e_2) throw e_2.error; } return [7 /*endfinally*/]; case 9: // currently we return a de-duped set of protocols represented by these grants, this is used to register protocols for sync // we expect that any connected protocols will include MessagesQuery and MessagesRead grants that will allow it to sync return [2 /*return*/, __spreadArray([], __read(connectedProtocols), false)]; } }); }); }; return Web5; }()); exports.Web5 = Web5; //# sourceMappingURL=web5.js.map