diff --git a/dist/cli/cli.js b/dist/cli/cli.js index 6e3e3be481..82b8d2656d 100644 --- a/dist/cli/cli.js +++ b/dist/cli/cli.js @@ -1 +1,726 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.cli=t():e.cli=t()}(this,(function(){return function(e){var t={};function n(o){if(t[o])return t[o].exports;var a=t[o]={i:o,l:!1,exports:{}};return e[o].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=e,n.c=t,n.d=function(e,t,o){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(o,a,function(t){return e[t]}.bind(null,a));return o},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(4)),r=o(n(3)),s=n(1),i=o(n(5)),d=o(n(7)),l=o(n(8)),c=o(n(9)),u=o(n(10));function p(e){console.error(r.default.red(e.message))}function g(e){return"~"!==e[0]||"/"!==e[1]&&1!==e.length||(e=e.replace("~",a.default.homedir())),e}var f;t.actionRunner=function(e){return(...t)=>e(...t).catch(p)},t.resolveTilde=g,function(e){e[e.SUCCESS=0]="SUCCESS",e[e.INFO=1]="INFO",e[e.WARNING=2]="WARNING",e[e.none=3]="none"}(f||(f={})),t.PKMessageType=f,t.pkLogger=function(e,t){switch(t){case f.SUCCESS:console.log(r.default.green(e));break;case f.INFO:console.log(r.default.blue(e));break;case f.WARNING:console.log(r.default.yellow(e));break;default:console.log(e)}},t.determineNodePath=function(e){var t;const n=null!==(t=e.nodePath)&&void 0!==t?t:process.env.KEYNODE_PATH;if(!n)throw Error("no keynode path given, you can set it as an environment variable with \"export KEYNODE_PATH=''\"");return g(n)};const y=new s.program.Command;y.version(n(11).version,"--version","output the current version").addCommand(u.default()).addCommand(c.default()).addCommand(l.default()).addCommand(d.default()).addCommand(i.default()),e.exports=function(e){y.parse(e)}},function(e,t){e.exports=require("commander")},function(e,t){e.exports=require("../lib/polykey.js")},function(e,t){e.exports=require("chalk")},function(e,t){e.exports=require("os")},function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(6)),r=o(n(1)),s=n(2),i=n(0);t.default=function(){return new r.default.Command("agent").description("control the polykey agent").addCommand(new r.default.Command("start").description("start the agent").option("-d, --daemon","start the agent as a daemon process").action(i.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent();if("online"==await t.getAgentStatus())i.pkLogger("agent is already running",i.PKMessageType.INFO);else{const t=e.daemon,n=await s.PolykeyAgent.startAgent(t);i.pkLogger("agent has started with pid of "+n,i.PKMessageType.SUCCESS)}process.exit()}))).addCommand(new r.default.Command("restart").description("restart the agent").option("-d, --daemon","start the agent as a daemon process").action(i.actionRunner(async e=>{s.PolykeyAgent.connectToAgent().stopAgent();const t=e.daemon,n=await s.PolykeyAgent.startAgent(t);i.pkLogger("agent has restarted with pid of "+n,i.PKMessageType.SUCCESS),process.exit()}))).addCommand(new r.default.Command("status").description("retrieve the status of the agent").action(i.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent(),n=await t.getAgentStatus();i.pkLogger(`agent status is: '${n}'`,i.PKMessageType.INFO),process.exit()}))).addCommand(new r.default.Command("stop").description("stop the agent").option("-f, --force","forcibly stop the agent").action(i.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent();if("stopped"==await t.getAgentStatus())i.pkLogger("agent is already stopped",i.PKMessageType.INFO);else{const n=!!e.force;if(t.stopAgent(),n&&a.default.unlinkSync(s.PolykeyAgent.SocketPath),"online"==await t.getAgentStatus())throw Error("agent failed to stop");i.pkLogger("agent has successfully stopped",i.PKMessageType.SUCCESS)}process.exit()}))).addCommand(new r.default.Command("list").alias("ls").description("list all the nodes controlled by the node").option("-u, --unlocked-only, only list the nodes that are unlocked").action(i.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent(),n=!!e.unlockedOnly,o=await t.listNodes(n);if(0==o.length)i.pkLogger("no nodes were listed",i.PKMessageType.INFO);else for(const e of o)i.pkLogger(e,i.PKMessageType.INFO);process.exit()}))).addCommand(new r.default.Command("create").description("create a new polykey node").option("-k, --node-path ","provide the polykey path. defaults to ~/.polykey").requiredOption("-n, --full-name ","provide your full name for key pair generation").requiredOption("-e, --email ","provide a valid email address for key pair generation").requiredOption("-p, --private-passphrase ","provide the passphrase to the private key").option("-b, --number-of-bits ","number of bits to use for key pair generation").option("-v, --verbose","increase verbosity by one level").action(i.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent(),n=i.determineNodePath(e),o=e.fullName,a=e.email,r=e.privatePassphrase,d=parseInt(e.numberOfBits);if(!await t.newNode(n,o,a,r,d))throw Error("something went wrong with node creation");i.pkLogger(`node was successfully generated at: '${n}'`,i.PKMessageType.SUCCESS),process.exit()}))).addCommand(new r.default.Command("load").description("load an existing polykey node").option("-k, --node-path ","provide the polykey path. defaults to ~/.polykey").requiredOption("-p, --private-passphrase ","provide the passphrase to the private key").action(i.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent(),n=i.determineNodePath(e),o=e.privatePassphrase;if(!await t.registerNode(n,o))throw Error("something went wrong when loading node");i.pkLogger(`node was successfully loaded at: '${n}'`,i.PKMessageType.SUCCESS),process.exit()})))}},function(e,t){e.exports=require("fs")},function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(1)),r=n(2),s=n(0);t.default=function(){return new a.default.Command("crypto").description("crypto operations").addCommand(new a.default.Command("verify").description("verification operations").option("--node-path ","node path").option("-k, --verifying-key ","path to public key that will be used to verify files, defaults to primary key").option("-s, --detach-sig ","path to detached signature for file, defaults to [filename].sig").requiredOption("-f, --signed-file ","file to be signed").action(s.actionRunner(async e=>{var t;const n=r.PolykeyAgent.connectToAgent(),o=await n.getAgentStatus();if("online"!=o)throw Error("agent status is: "+o);const a=s.determineNodePath(e),i=(e.verifyingKey,e.signedFile),d=null!==(t=e.detachSig)&&void 0!==t?t:i+".sig";await n.verifyFile(a,i,d)?s.pkLogger(`file '${i}' was successfully verified`,s.PKMessageType.SUCCESS):s.pkLogger(`file '${i}' was not verified`,s.PKMessageType.WARNING)}))).addCommand(new a.default.Command("sign").description("signing operations [files]").option("--node-path ","node path").option("-k, --signing-key ","path to private key that will be used to sign files").option("-p, --key-passphrase ","passphrase to unlock the provided signing key").arguments("file(s) to be signed").action(async e=>{const t=r.PolykeyAgent.connectToAgent(),n=await t.getAgentStatus();if("online"!=n)throw Error("agent status is: "+n);const o=s.determineNodePath(e),a=e.signingKey,i=e.keyPassphrase;if((a||i)&&(!a||!i))throw Error("signing key and passphrase must be specified together");const d=e.args.values();if(0==d.length)throw Error("no files provided");for(const e of d)try{const n=await t.signFile(o,e,a,i);s.pkLogger(`file '${e}' successfully signed at '${n}'`,s.PKMessageType.SUCCESS)}catch(t){throw new Error(`failed to sign '${e}': ${t}`)}}))}},function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(3)),r=o(n(1)),s=n(0),i=n(2);t.default=function(){return new r.default.Command("vaults").description("manipulate vaults").addCommand(new r.default.Command("list").description("list all available vaults").alias("ls").option("--node-path ","node path").option("-v, --verbose","increase verbosity level by one").action(s.actionRunner(async e=>{const t=i.PolykeyAgent.connectToAgent(),n=await t.getAgentStatus();if("online"!=n)throw Error("agent status is: "+n);const o=s.determineNodePath(e),a=await t.listVaults(o);void 0===a||0==a.length?s.pkLogger("no vaults found",s.PKMessageType.INFO):a.forEach(e=>{s.pkLogger(e,s.PKMessageType.INFO)})}))).addCommand(new r.default.Command("new").description("create new vault(s)").option("--node-path ","node path").arguments("vault name(s)").action(s.actionRunner(async e=>{const t=i.PolykeyAgent.connectToAgent(),n=s.determineNodePath(e),o=e.args.values();for(const e of o)await t.newVault(n,e),s.pkLogger(`vault created at '${n}/${e}'`,s.PKMessageType.SUCCESS)}))).addCommand(new r.default.Command("remove").description("destroy an existing vault").option("-n, --vault-name ","name of vault").option("-a, --all","remove all vaults").option("-v, --verbose","increase verbosity by one level").action(s.actionRunner(async e=>{var t,n;const o=i.PolykeyAgent.connectToAgent(),r=s.determineNodePath(e),d=null!==(t=e.verbose)&&void 0!==t&&t;if(null!==(n=e.all)&&void 0!==n&&n){const e=await o.listVaults(r);if(void 0===e||0==e.length)s.pkLogger("no vaults found",s.PKMessageType.INFO);else{for(const t of e)await o.destroyVault(r,t),d&&s.pkLogger("destroyed "+t,s.PKMessageType.SUCCESS);s.pkLogger("all vaults destroyed successfully",s.PKMessageType.SUCCESS)}return}const l=e.vaultName;if(!l)throw new Error(a.default.red("error: did not receive vault name"));const c=await o.destroyVault(r,l);s.pkLogger(`vault '${l}' destroyed ${c?"un-":""}successfully`,s.PKMessageType.SUCCESS)})))}},function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(1)),r=n(0),s=n(2);t.default=function(){return new a.default.Command("secrets").description("manipulate secrets for a given vault").addCommand(new a.default.Command("list").description("list all available secrets for a given vault").alias("ls").requiredOption("-n, --vault-name ","the vault name").option("--node-path ","node path").option("--verbose","increase verbosity level by one").action(r.actionRunner(async e=>{var t;const n=s.PolykeyAgent.connectToAgent(),o=r.determineNodePath(e),a=null!==(t=e.verbose)&&void 0!==t&&t,i=e.vaultName,d=await n.listSecrets(o,i);0==d.length?r.pkLogger(`no secrets found for vault '${i}'`,r.PKMessageType.INFO):(a&&r.pkLogger(`secrets contained within the ${i} vault:`,r.PKMessageType.INFO),d.forEach(e=>{r.pkLogger(e,r.PKMessageType.INFO)}))}))).addCommand(new a.default.Command("create").description("create a secret within a given vault").requiredOption("-n, --vault-name ","the vault name").requiredOption("-s, --secret-name ","the new secret name").requiredOption("-p, --secret-path ","path to the secret to be added").option("--node-path ","node path").option("--verbose","increase verbosity level by one").action(r.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent(),n=r.determineNodePath(e),o=(e.verbose,e.vaultName),a=e.secretName,i=e.secretPath;try{const e=await t.createSecret(n,o,a,i);r.pkLogger(`secret '${a}' was ${e?"":"un-"}sucessfully added to vault '${o}'`,r.PKMessageType.SUCCESS)}catch(e){throw new Error("Error when adding secret: "+e.message)}}))).addCommand(new a.default.Command("remove").description("remove a secret from a given vault").requiredOption("-n, --vault-name ","the vault name").requiredOption("-s, --secret-name ","the new secret name").option("--verbose","increase verbosity level by one").action(r.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent(),n=r.determineNodePath(e),o=(e.verbose,e.vaultName),a=e.secretName;try{const e=await t.destroySecret(n,o,a);r.pkLogger(`secret '${a}' was ${e?"":"un-"}sucessfully removed from vault '${o}'`,r.PKMessageType.SUCCESS)}catch(e){throw new Error("Error when removing secret: "+e.message)}}))).addCommand(new a.default.Command("get").description("retrieve a secret from a given vault").requiredOption("-n, --vault-name ","the vault name").requiredOption("-s, --secret-name ","the new secret name").option("--verbose","increase verbosity level by one").action(r.actionRunner(async e=>{const t=s.PolykeyAgent.connectToAgent(),n=r.determineNodePath(e),o=(e.verbose,e.vaultName),a=e.secretName;try{const e=await t.getSecret(n,o,a);r.pkLogger(`secret '${a}' from vault '${o}':`,r.PKMessageType.SUCCESS),r.pkLogger(e.toString(),r.PKMessageType.none)}catch(e){throw new Error("Error when retrieving secret: "+e.message)}})))}},function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(1)),r=n(2),s=n(0);t.default=function(){return new a.default.Command("keymanager").alias("km").description("manipulate the keymanager").addCommand(new a.default.Command("derive").description("manipulate the keymanager").option("--node-path ","node path").requiredOption("-n, --key-name ","the name of the new key").requiredOption("-p, --key-passphrase ","the passphrase for the new key").action(s.actionRunner(async e=>{const t=r.PolykeyAgent.connectToAgent(),n=s.determineNodePath(e),o=e.keyName,a=e.keyPassphrase;await t.deriveKey(n,o,a),s.pkLogger(`'${o}' was added to the Key Manager`,s.PKMessageType.SUCCESS)})))}},function(e,t){e.exports=require("../../package.json")}])})); \ No newline at end of file +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["cli"] = factory(); + else + root["cli"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os_1 = __importDefault(__webpack_require__(4)); +const chalk_1 = __importDefault(__webpack_require__(3)); +const commander_1 = __webpack_require__(1); +const Agent_1 = __importDefault(__webpack_require__(5)); +const Crypto_1 = __importDefault(__webpack_require__(7)); +const Vaults_1 = __importDefault(__webpack_require__(8)); +const Secrets_1 = __importDefault(__webpack_require__(9)); +const KeyManager_1 = __importDefault(__webpack_require__(10)); +/*******************************************/ +// Error handler +function actionErrorHanlder(error) { + console.error(chalk_1.default.red(error.message)); +} +function actionRunner(fn) { + return (...args) => fn(...args).catch(actionErrorHanlder); +} +exports.actionRunner = actionRunner; +function resolveTilde(filePath) { + if (filePath[0] === '~' && (filePath[1] === '/' || filePath.length === 1)) { + filePath = filePath.replace('~', os_1.default.homedir()); + } + return filePath; +} +exports.resolveTilde = resolveTilde; +/*******************************************/ +// Logger +var PKMessageType; +(function (PKMessageType) { + PKMessageType[PKMessageType["SUCCESS"] = 0] = "SUCCESS"; + PKMessageType[PKMessageType["INFO"] = 1] = "INFO"; + PKMessageType[PKMessageType["WARNING"] = 2] = "WARNING"; + PKMessageType[PKMessageType["none"] = 3] = "none"; +})(PKMessageType || (PKMessageType = {})); +exports.PKMessageType = PKMessageType; +function pkLogger(message, type) { + switch (type) { + case PKMessageType.SUCCESS: + console.log(chalk_1.default.green(message)); + break; + case PKMessageType.INFO: + console.log(chalk_1.default.blue(message)); + break; + case PKMessageType.WARNING: + console.log(chalk_1.default.yellow(message)); + break; + default: + console.log(message); + break; + } +} +exports.pkLogger = pkLogger; +function determineNodePath(options) { + var _a; + const nodePath = (_a = options.nodePath) !== null && _a !== void 0 ? _a : process.env.KEYNODE_PATH; + if (!nodePath) { + throw Error('no keynode path given, you can set it as an environment variable with "export KEYNODE_PATH=\'\'"'); + } + return resolveTilde(nodePath); +} +exports.determineNodePath = determineNodePath; +/*******************************************/ +const polykey = new commander_1.program.Command(); +polykey + .version(__webpack_require__(11).version, '--version', 'output the current version') + .addCommand(KeyManager_1.default()) + .addCommand(Secrets_1.default()) + .addCommand(Vaults_1.default()) + .addCommand(Crypto_1.default()) + .addCommand(Agent_1.default()); +module.exports = function (argv) { + polykey.parse(argv); +}; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports) { + +module.exports = require("commander"); + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + +module.exports = require("../lib/polykey.js"); + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + +module.exports = require("chalk"); + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + +module.exports = require("os"); + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs_1 = __importDefault(__webpack_require__(6)); +const commander_1 = __importDefault(__webpack_require__(1)); +const Polykey_1 = __webpack_require__(2); +const _1 = __webpack_require__(0); +function makeStartAgentCommand() { + return new commander_1.default.Command('start') + .description('start the agent') + .option('-d, --daemon', 'start the agent as a daemon process') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + // Tell agent to stop + const status = await client.getAgentStatus(); + if (status == 'online') { + _1.pkLogger('agent is already running', _1.PKMessageType.INFO); + } + else { + const daemon = options.daemon; + const pid = await Polykey_1.PolykeyAgent.startAgent(daemon); + _1.pkLogger(`agent has started with pid of ${pid}`, _1.PKMessageType.SUCCESS); + } + process.exit(); + })); +} +function makeRestartAgentCommand() { + return new commander_1.default.Command('restart') + .description('restart the agent') + .option('-d, --daemon', 'start the agent as a daemon process') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + // Tell agent to stop + client.stopAgent(); + const daemon = options.daemon; + const pid = await Polykey_1.PolykeyAgent.startAgent(daemon); + _1.pkLogger(`agent has restarted with pid of ${pid}`, _1.PKMessageType.SUCCESS); + process.exit(); + })); +} +function makeAgentStatusCommand() { + return new commander_1.default.Command('status').description('retrieve the status of the agent').action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + _1.pkLogger(`agent status is: '${status}'`, _1.PKMessageType.INFO); + process.exit(); + })); +} +function makeStopAgentCommand() { + return new commander_1.default.Command('stop') + .description('stop the agent') + .option('-f, --force', 'forcibly stop the agent') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + if (status == 'stopped') { + _1.pkLogger('agent is already stopped', _1.PKMessageType.INFO); + } + else { + const force = options.force ? true : false; + // Tell agent to stop + client.stopAgent(); + if (force) { + fs_1.default.unlinkSync(Polykey_1.PolykeyAgent.SocketPath); + } + const status = await client.getAgentStatus(); + if (status != 'online') { + _1.pkLogger('agent has successfully stopped', _1.PKMessageType.SUCCESS); + } + else { + throw Error('agent failed to stop'); + } + } + process.exit(); + })); +} +function makeListNodesCommand() { + return new commander_1.default.Command('list') + .alias('ls') + .description('list all the nodes controlled by the node') + .option('-u, --unlocked-only, only list the nodes that are unlocked') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const unlockedOnly = options.unlockedOnly ? true : false; + const nodes = await client.listNodes(unlockedOnly); + if (nodes.length == 0) { + _1.pkLogger('no nodes were listed', _1.PKMessageType.INFO); + } + else { + for (const node of nodes) { + _1.pkLogger(node, _1.PKMessageType.INFO); + } + } + process.exit(); + })); +} +function makeNewNodeCommand() { + return new commander_1.default.Command('create') + .description('create a new polykey node') + .option('-k, --node-path ', 'provide the polykey path. defaults to ~/.polykey') + .requiredOption('-n, --full-name ', 'provide your full name for key pair generation') + .requiredOption('-e, --email ', 'provide a valid email address for key pair generation') + .requiredOption('-p, --private-passphrase ', 'provide the passphrase to the private key') + .option('-b, --number-of-bits ', 'number of bits to use for key pair generation') + .option('-v, --verbose', 'increase verbosity by one level') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const fullName = options.fullName; + const email = options.email; + const privatePassphrase = options.privatePassphrase; + const numberOfBits = parseInt(options.numberOfBits); + const successful = await client.newNode(nodePath, fullName, email, privatePassphrase, numberOfBits); + if (successful) { + _1.pkLogger(`node was successfully generated at: '${nodePath}'`, _1.PKMessageType.SUCCESS); + } + else { + throw Error('something went wrong with node creation'); + } + process.exit(); + })); +} +function makeLoadNodeCommand() { + return new commander_1.default.Command('load') + .description('load an existing polykey node') + .option('-k, --node-path ', 'provide the polykey path. defaults to ~/.polykey') + .requiredOption('-p, --private-passphrase ', 'provide the passphrase to the private key') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const privatePassphrase = options.privatePassphrase; + const successful = await client.registerNode(nodePath, privatePassphrase); + if (successful) { + _1.pkLogger(`node was successfully loaded at: '${nodePath}'`, _1.PKMessageType.SUCCESS); + } + else { + throw Error('something went wrong when loading node'); + } + process.exit(); + })); +} +function makeAgentCommand() { + return new commander_1.default.Command('agent') + .description('control the polykey agent') + .addCommand(makeStartAgentCommand()) + .addCommand(makeRestartAgentCommand()) + .addCommand(makeAgentStatusCommand()) + .addCommand(makeStopAgentCommand()) + .addCommand(makeListNodesCommand()) + .addCommand(makeNewNodeCommand()) + .addCommand(makeLoadNodeCommand()); +} +exports.default = makeAgentCommand; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports) { + +module.exports = require("fs"); + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const commander_1 = __importDefault(__webpack_require__(1)); +const Polykey_1 = __webpack_require__(2); +const _1 = __webpack_require__(0); +function makeSignCommand() { + return new commander_1.default.Command('sign') + .description('signing operations [files]') + .option('--node-path ', 'node path') + .option('-k, --signing-key ', 'path to private key that will be used to sign files') + .option('-p, --key-passphrase ', 'passphrase to unlock the provided signing key') + .arguments('file(s) to be signed') + .action(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + if (status != 'online') { + throw Error(`agent status is: ${status}`); + } + const nodePath = _1.determineNodePath(options); + const signingKeyPath = options.signingKey; + const keyPassphrase = options.keyPassphrase; + if ((signingKeyPath || keyPassphrase) && !(signingKeyPath && keyPassphrase)) { + throw Error('signing key and passphrase must be specified together'); + } + const filePathList = options.args.values(); + if (filePathList.length == 0) { + throw Error('no files provided'); + } + for (const filePath of filePathList) { + try { + const signaturePath = await client.signFile(nodePath, filePath, signingKeyPath, keyPassphrase); + _1.pkLogger(`file '${filePath}' successfully signed at '${signaturePath}'`, _1.PKMessageType.SUCCESS); + } + catch (err) { + throw Error(`failed to sign '${filePath}': ${err}`); + } + } + }); +} +function makeVerifyCommand() { + return new commander_1.default.Command('verify') + .description('verification operations') + .option('--node-path ', 'node path') + .option('-k, --verifying-key ', 'path to public key that will be used to verify files, defaults to primary key') + .option('-s, --detach-sig ', 'path to detached signature for file, defaults to [filename].sig') + .requiredOption('-f, --signed-file ', 'file to be signed') + .action(_1.actionRunner(async (options) => { + var _a; + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + if (status != 'online') { + throw Error(`agent status is: ${status}`); + } + const nodePath = _1.determineNodePath(options); + const verifyingKeyPath = options.verifyingKey; + const filePath = options.signedFile; + const signaturePath = (_a = options.detachSig) !== null && _a !== void 0 ? _a : filePath + '.sig'; + const verified = await client.verifyFile(nodePath, filePath, signaturePath); + if (verified) { + _1.pkLogger(`file '${filePath}' was successfully verified`, _1.PKMessageType.SUCCESS); + } + else { + _1.pkLogger(`file '${filePath}' was not verified`, _1.PKMessageType.WARNING); + } + })); +} +function makeCryptoCommand() { + return new commander_1.default.Command('crypto') + .description('crypto operations') + .addCommand(makeVerifyCommand()) + .addCommand(makeSignCommand()); +} +exports.default = makeCryptoCommand; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const chalk_1 = __importDefault(__webpack_require__(3)); +const commander_1 = __importDefault(__webpack_require__(1)); +const _1 = __webpack_require__(0); +const Polykey_1 = __webpack_require__(2); +function makeListVaultsCommand() { + return new commander_1.default.Command('list') + .description('list all available vaults') + .alias('ls') + .option('--node-path ', 'node path') + .option('-v, --verbose', 'increase verbosity level by one') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + if (status != 'online') { + throw Error(`agent status is: ${status}`); + } + const nodePath = _1.determineNodePath(options); + const vaultNames = await client.listVaults(nodePath); + if (vaultNames === undefined || vaultNames.length == 0) { + _1.pkLogger('no vaults found', _1.PKMessageType.INFO); + } + else { + vaultNames.forEach((vaultName) => { + _1.pkLogger(vaultName, _1.PKMessageType.INFO); + }); + } + })); +} +function makeAddVaultCommand() { + return new commander_1.default.Command('new') + .description('create new vault(s)') + .option('--node-path ', 'node path') + .arguments('vault name(s)') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const vaultNames = options.args.values(); + for (const vaultName of vaultNames) { + await client.newVault(nodePath, vaultName); + _1.pkLogger(`vault created at '${nodePath}/${vaultName}'`, _1.PKMessageType.SUCCESS); + } + })); +} +function makeRemoveVaultCommand() { + return new commander_1.default.Command('remove') + .description('destroy an existing vault') + .option('-n, --vault-name ', 'name of vault') + .option('-a, --all', 'remove all vaults') + .option('-v, --verbose', 'increase verbosity by one level') + .action(_1.actionRunner(async (options) => { + var _a, _b; + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const verbose = (_a = options.verbose) !== null && _a !== void 0 ? _a : false; + const deleteAll = (_b = options.all) !== null && _b !== void 0 ? _b : false; + if (deleteAll) { + const vaultNames = await client.listVaults(nodePath); + if (vaultNames === undefined || vaultNames.length == 0) { + _1.pkLogger('no vaults found', _1.PKMessageType.INFO); + } + else { + for (const vaultName of vaultNames) { + await client.destroyVault(nodePath, vaultName); + if (verbose) { + _1.pkLogger(`destroyed ${vaultName}`, _1.PKMessageType.SUCCESS); + } + } + _1.pkLogger('all vaults destroyed successfully', _1.PKMessageType.SUCCESS); + } + return; + } + const vaultName = options.vaultName; + if (!vaultName) { + throw Error(chalk_1.default.red('error: did not receive vault name')); + } + const successful = await client.destroyVault(nodePath, vaultName); + _1.pkLogger(`vault '${vaultName}' destroyed ${successful ? 'un-' : ''}successfully`, _1.PKMessageType.SUCCESS); + })); +} +function makeVaultsCommand() { + return new commander_1.default.Command('vaults') + .description('manipulate vaults') + .addCommand(makeListVaultsCommand()) + .addCommand(makeAddVaultCommand()) + .addCommand(makeRemoveVaultCommand()); +} +exports.default = makeVaultsCommand; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const commander_1 = __importDefault(__webpack_require__(1)); +const _1 = __webpack_require__(0); +const Polykey_1 = __webpack_require__(2); +function makeListSecretsCommand() { + return new commander_1.default.Command('list') + .description('list all available secrets for a given vault') + .alias('ls') + .requiredOption('-n, --vault-name ', 'the vault name') + .option('--node-path ', 'node path') + .option('--verbose', 'increase verbosity level by one') + .action(_1.actionRunner(async (options) => { + var _a; + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const isVerbose = (_a = options.verbose) !== null && _a !== void 0 ? _a : false; + const vaultName = options.vaultName; + // Get list of secrets from pk + const secretNames = await client.listSecrets(nodePath, vaultName); + // List secrets + if (secretNames.length == 0) { + _1.pkLogger(`no secrets found for vault '${vaultName}'`, _1.PKMessageType.INFO); + } + else { + if (isVerbose) { + _1.pkLogger(`secrets contained within the ${vaultName} vault:`, _1.PKMessageType.INFO); + } + secretNames.forEach((secretName) => { + _1.pkLogger(secretName, _1.PKMessageType.INFO); + }); + } + })); +} +function makeAddSecretCommand() { + return new commander_1.default.Command('create') + .description('create a secret within a given vault') + .requiredOption('-n, --vault-name ', 'the vault name') + .requiredOption('-s, --secret-name ', 'the new secret name') + .requiredOption('-p, --secret-path ', 'path to the secret to be added') + .option('--node-path ', 'node path') + .option('--verbose', 'increase verbosity level by one') + .action(_1.actionRunner(async (options) => { + var _a; + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const isVerbose = (_a = options.verbose) !== null && _a !== void 0 ? _a : false; + const vaultName = options.vaultName; + const secretName = options.secretName; + const secretPath = options.secretPath; + try { + // Add the secret + const successful = await client.createSecret(nodePath, vaultName, secretName, secretPath); + _1.pkLogger(`secret '${secretName}' was ${successful ? '' : 'un-'}sucessfully added to vault '${vaultName}'`, _1.PKMessageType.SUCCESS); + } + catch (err) { + throw Error(`Error when adding secret: ${err.message}`); + } + })); +} +function makeRemoveSecretCommand() { + return new commander_1.default.Command('remove') + .description('remove a secret from a given vault') + .requiredOption('-n, --vault-name ', 'the vault name') + .requiredOption('-s, --secret-name ', 'the new secret name') + .option('--verbose', 'increase verbosity level by one') + .action(_1.actionRunner(async (options) => { + var _a; + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const isVerbose = (_a = options.verbose) !== null && _a !== void 0 ? _a : false; + const vaultName = options.vaultName; + const secretName = options.secretName; + try { + // Remove secret + const successful = await client.destroySecret(nodePath, vaultName, secretName); + _1.pkLogger(`secret '${secretName}' was ${successful ? '' : 'un-'}sucessfully removed from vault '${vaultName}'`, _1.PKMessageType.SUCCESS); + } + catch (err) { + throw Error(`Error when removing secret: ${err.message}`); + } + })); +} +function makeGetSecretCommand() { + return new commander_1.default.Command('get') + .description('retrieve a secret from a given vault') + .requiredOption('-n, --vault-name ', 'the vault name') + .requiredOption('-s, --secret-name ', 'the new secret name') + .option('--verbose', 'increase verbosity level by one') + .action(_1.actionRunner(async (options) => { + var _a; + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const isVerbose = (_a = options.verbose) !== null && _a !== void 0 ? _a : false; + const vaultName = options.vaultName; + const secretName = options.secretName; + try { + // Remove secret + const secret = await client.getSecret(nodePath, vaultName, secretName); + _1.pkLogger(`secret '${secretName}' from vault '${vaultName}':`, _1.PKMessageType.SUCCESS); + _1.pkLogger(secret.toString(), _1.PKMessageType.none); + } + catch (err) { + throw Error(`Error when retrieving secret: ${err.message}`); + } + })); +} +function makeSecretsCommand() { + return new commander_1.default.Command('secrets') + .description('manipulate secrets for a given vault') + .addCommand(makeListSecretsCommand()) + .addCommand(makeAddSecretCommand()) + .addCommand(makeRemoveSecretCommand()) + .addCommand(makeGetSecretCommand()); +} +exports.default = makeSecretsCommand; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const commander_1 = __importDefault(__webpack_require__(1)); +const Polykey_1 = __webpack_require__(2); +const _1 = __webpack_require__(0); +function makeDeriveKeyCommand() { + return new commander_1.default.Command('derive') + .description('manipulate the keymanager') + .option('--node-path ', 'node path') + .requiredOption('-n, --key-name ', 'the name of the new key') + .requiredOption('-p, --key-passphrase ', 'the passphrase for the new key') + .action(_1.actionRunner(async (options) => { + const client = Polykey_1.PolykeyAgent.connectToAgent(); + const nodePath = _1.determineNodePath(options); + const keyName = options.keyName; + const keyPassphrase = options.keyPassphrase; + await client.deriveKey(nodePath, keyName, keyPassphrase); + _1.pkLogger(`'${keyName}' was added to the Key Manager`, _1.PKMessageType.SUCCESS); + })); +} +function makeKeyManagerCommand() { + return new commander_1.default.Command('keymanager') + .alias('km') + .description('manipulate the keymanager') + .addCommand(makeDeriveKeyCommand()); +} +exports.default = makeKeyManagerCommand; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports) { + +module.exports = require("../../package.json"); + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/dist/lib/browser-client.d.ts b/dist/lib/browser-client.d.ts index 3728da8f3d..e99eb94925 100644 --- a/dist/lib/browser-client.d.ts +++ b/dist/lib/browser-client.d.ts @@ -1,8 +1,8 @@ /// -import { PassThrough } from 'readable-stream'; +import { Duplex } from 'readable-stream'; declare class PolykeyClient { private getStream; - constructor(getStream: () => PassThrough); + constructor(getStream: () => Duplex); sendRequestToAgent(request: Uint8Array): Promise; private handleAgentCommunication; registerNode(path: string, passphrase: string): Promise; @@ -15,7 +15,7 @@ declare class PolykeyClient { newVault(nodePath: string, vaultName: string): Promise; destroyVault(nodePath: string, vaultName: string): Promise; listSecrets(nodePath: string, vaultName: string): Promise; - createSecret(nodePath: string, vaultName: string, secretName: string, secretPath: string): Promise; + createSecret(nodePath: string, vaultName: string, secretName: string, secret: string | Buffer): Promise; destroySecret(nodePath: string, vaultName: string, secretName: string): Promise; getSecret(nodePath: string, vaultName: string, secretName: string): Promise; getAgentStatus(): Promise; diff --git a/dist/lib/browser-client.js b/dist/lib/browser-client.js index 682edff737..8b67af9022 100644 --- a/dist/lib/browser-client.js +++ b/dist/lib/browser-client.js @@ -1,9 +1,5108 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["browser-client"]=t():e["browser-client"]=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var s=t[r]={i:r,l:!1,exports:{}};return e[r].call(s.exports,s,s.exports,n),s.l=!0,s.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)n.d(r,s,function(t){return e[t]}.bind(null,s));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});const r=n(6),{AgentMessage:s,CreateSecretRequestMessage:o,CreateSecretResponseMessage:i,DeriveKeyRequestMessage:a,DeriveKeyResponseMessage:u,DestroySecretRequestMessage:c,DestroySecretResponseMessage:f,DestroyVaultRequestMessage:l,DestroyVaultResponseMessage:h,ErrorMessage:p,GetSecretRequestMessage:g,GetSecretResponseMessage:d,ListNodesRequestMessage:y,ListNodesResponseMessage:w,ListSecretsRequestMessage:v,ListSecretsResponseMessage:b,ListVaultsRequestMessage:m,ListVaultsResponseMessage:R,NewNodeRequestMessage:E,NewNodeResponseMessage:O,NewVaultRequestMessage:P,NewVaultResponseMessage:N,RegisterNodeRequestMessage:T,RegisterNodeResponseMessage:S,SignFileRequestMessage:M,SignFileResponseMessage:k,Type:A,VerifyFileRequestMessage:_,VerifyFileResponseMessage:j}=r.agent;t.default=class{constructor(e){this.getStream=e}async sendRequestToAgent(e){const t=this.getStream(),n=await new Promise((n,r)=>{try{const s=[];t.on("data",e=>{s.push(e)}),t.on("error",e=>{r(e)}),t.on("end",()=>{n(s)}),t.write(e)}catch(e){r(e)}});return t.end(),n}async handleAgentCommunication(e,t,n){const r=s.encode({type:e,isResponse:!1,nodePath:t,subMessage:n}).finish(),o=await this.sendRequestToAgent(r),i=[];for(const e of o){const{subMessage:t,type:n}=s.decode(e);if(n==A.ERROR){const{error:e}=p.decode(t);throw new Error(e)}i.push(s.decode(e))}return i}async registerNode(e,t){const n=T.encode({passphrase:t}).finish(),r=await this.handleAgentCommunication(A.REGISTER_NODE,e,n);if(0==r.length)throw Error("agent did not respond");const{successful:s}=S.decode(r[0].subMessage);return s}async newNode(e,t,n,r,s){const o=E.encode({name:t,email:n,passphrase:r,nbits:s}).finish(),i=await this.handleAgentCommunication(A.NEW_NODE,e,o);if(0==i.length)throw Error("agent did not respond");const{successful:a}=O.decode(i[0].subMessage);return a}async listNodes(e=!0){const t=y.encode({unlockedOnly:e}).finish(),n=await this.handleAgentCommunication(A.LIST_NODES,void 0,t);if(0==n.length)throw Error("agent did not respond");const{nodes:r}=w.decode(n[0].subMessage);return r}async deriveKey(e,t,n){const r=a.encode({keyName:t,passphrase:n}).finish(),s=await this.handleAgentCommunication(A.DERIVE_KEY,e,r);if(0==s.length)throw Error("agent did not respond");const{successful:o}=u.decode(s[0].subMessage);return o}async signFile(e,t,n,r){const s=M.encode({filePath:t,privateKeyPath:n,passphrase:r}).finish(),o=await this.handleAgentCommunication(A.SIGN_FILE,e,s);if(0==o.length)throw Error("agent did not respond");const{signaturePath:i}=k.decode(o[0].subMessage);return i}async verifyFile(e,t,n){const r=_.encode({filePath:t,signaturePath:n}).finish(),s=await this.handleAgentCommunication(A.VERIFY_FILE,e,r);if(0==s.length)throw Error("agent did not respond");const{verified:o}=j.decode(s[0].subMessage);return o}async listVaults(e){const t=await this.handleAgentCommunication(A.LIST_VAULTS,e);if(0==t.length)throw Error("agent did not respond");const{vaultNames:n}=R.decode(t[0].subMessage);return n}async newVault(e,t){const n=P.encode({vaultName:t}).finish(),r=await this.handleAgentCommunication(A.NEW_VAULT,e,n);if(0==r.length)throw Error("agent did not respond");const{successful:s}=N.decode(r[0].subMessage);return s}async destroyVault(e,t){const n=l.encode({vaultName:t}).finish(),r=await this.handleAgentCommunication(A.DESTROY_VAULT,e,n);if(0==r.length)throw Error("agent did not respond");const{successful:s}=h.decode(r[0].subMessage);return s}async listSecrets(e,t){const n=v.encode({vaultName:t}).finish(),r=await this.handleAgentCommunication(A.LIST_SECRETS,e,n);if(0==r.length)throw Error("agent did not respond");const{secretNames:s}=b.decode(r[0].subMessage);return s}async createSecret(e,t,n,r){const s=o.encode({vaultName:t,secretName:n,secretPath:r}).finish(),a=await this.handleAgentCommunication(A.CREATE_SECRET,e,s);if(0==a.length)throw Error("agent did not respond");const{successful:u}=i.decode(a[0].subMessage);return u}async destroySecret(e,t,n){const r=c.encode({vaultName:t,secretName:n}).finish(),s=await this.handleAgentCommunication(A.DESTROY_SECRET,e,r);if(0==s.length)throw Error("agent did not respond");const{successful:o}=f.decode(s[0].subMessage);return o}async getSecret(t,n,r){const s=g.encode({vaultName:n,secretName:r}).finish(),o=await this.handleAgentCommunication(A.GET_SECRET,t,s);if(0==o.length)throw Error("agent did not respond");const{secret:i}=d.decode(o[0].subMessage);return e.from(i)}async getAgentStatus(){try{const e=await this.handleAgentCommunication(A.STATUS);if(0==e.length)throw Error("agent did not respond");return e[0].subMessage.toString()}catch(e){return"stopped"}}async stopAgent(){try{return await this.handleAgentCommunication(A.STOP_AGENT),!0}catch(e){return"online"!=await this.getAgentStatus()}}}}).call(this,n(1).Buffer)},function(e,t,n){"use strict";(function(e){ -/*! +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["browser-client"] = factory(); + else + root["browser-client"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { +Object.defineProperty(exports, "__esModule", { value: true }); +const Agent_1 = __webpack_require__(6); +const { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage, } = Agent_1.agent; +class PolykeyClient { + constructor(getStream) { + this.getStream = getStream; + } + async sendRequestToAgent(request) { + const stream = this.getStream(); + const responseList = await new Promise((resolve, reject) => { + try { + const responseList = []; + stream.on('data', (data) => { + if (data instanceof Uint8Array) { + responseList.push(data); + } + else { + responseList.push(...data); + } + }); + stream.on('error', (err) => { + reject(err); + }); + stream.on('end', () => { + resolve(responseList); + }); + if (!stream.writableEnded) { + stream.write(request); + } + } + catch (err) { + reject(err); + } + }); + return responseList; + } + async handleAgentCommunication(type, nodePath, request) { + // Encode message and sent + const agentMessage = AgentMessage.encode({ + type: type, + isResponse: false, + nodePath: nodePath, + subMessage: request, + }).finish(); + const responseList = await this.sendRequestToAgent(agentMessage); + const agentMessageList = []; + for (const response of responseList.values()) { + const { subMessage, type } = AgentMessage.decode(response); + if (type == Type.ERROR) { + const { error } = ErrorMessage.decode(subMessage); + const reason = new Error(`Agent Error: ${error}`); + throw reason; + } + else { + agentMessageList.push(AgentMessage.decode(response)); + } + } + return agentMessageList; + } + async registerNode(path, passphrase) { + var _a; + const registerNodeRequest = RegisterNodeRequestMessage.encode({ passphrase }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.REGISTER_NODE, path, registerNodeRequest); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.REGISTER_NODE)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = RegisterNodeResponseMessage.decode(subMessage); + return successful; + } + async newNode(path, name, email, passphrase, nbits) { + var _a; + const newNodeRequest = NewNodeRequestMessage.encode({ name, email, passphrase, nbits }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.NEW_NODE, path, newNodeRequest); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.NEW_NODE)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = NewNodeResponseMessage.decode(subMessage); + return successful; + } + async listNodes(unlockedOnly = true) { + var _a; + const newNodeRequest = ListNodesRequestMessage.encode({ unlockedOnly }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.LIST_NODES, undefined, newNodeRequest); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_NODES)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { nodes } = ListNodesResponseMessage.decode(subMessage); + return nodes; + } + ///////////////////// + // Crypto commands // + ///////////////////// + async deriveKey(nodePath, keyName, passphrase) { + var _a; + const request = DeriveKeyRequestMessage.encode({ keyName, passphrase }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.DERIVE_KEY, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DERIVE_KEY)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = DeriveKeyResponseMessage.decode(subMessage); + return successful; + } + ///////////////////// + // Crypto commands // + ///////////////////// + async signFile(nodePath, filePath, privateKeyPath, passphrase) { + var _a; + const request = SignFileRequestMessage.encode({ filePath, privateKeyPath, passphrase }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.SIGN_FILE, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.SIGN_FILE)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { signaturePath } = SignFileResponseMessage.decode(subMessage); + return signaturePath; + } + async verifyFile(nodePath, filePath, signaturePath) { + var _a; + const request = VerifyFileRequestMessage.encode({ filePath, signaturePath }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.VERIFY_FILE, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.VERIFY_FILE)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { verified } = VerifyFileResponseMessage.decode(subMessage); + return verified; + } + ////////////////////// + // Vault Operations // + ////////////////////// + async listVaults(nodePath) { + var _a; + const encodedResponse = await this.handleAgentCommunication(Type.LIST_VAULTS, nodePath); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_VAULTS)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { vaultNames } = ListVaultsResponseMessage.decode(subMessage); + return vaultNames; + } + async newVault(nodePath, vaultName) { + var _a; + const request = NewVaultRequestMessage.encode({ vaultName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.NEW_VAULT, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.NEW_VAULT)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = NewVaultResponseMessage.decode(subMessage); + return successful; + } + async destroyVault(nodePath, vaultName) { + var _a; + const request = DestroyVaultRequestMessage.encode({ vaultName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_VAULT, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DESTROY_VAULT)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = DestroyVaultResponseMessage.decode(subMessage); + return successful; + } + /////////////////////// + // Secret Operations // + /////////////////////// + async listSecrets(nodePath, vaultName) { + var _a; + const request = ListSecretsRequestMessage.encode({ vaultName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.LIST_SECRETS, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_SECRETS)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { secretNames } = ListSecretsResponseMessage.decode(subMessage); + return secretNames; + } + async createSecret(nodePath, vaultName, secretName, secret) { + var _a; + let request; + if (typeof secret == 'string') { + request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretPath: secret }).finish(); + } + else { + request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretContent: secret }).finish(); + } + const encodedResponse = await this.handleAgentCommunication(Type.CREATE_SECRET, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.CREATE_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = CreateSecretResponseMessage.decode(subMessage); + return successful; + } + async destroySecret(nodePath, vaultName, secretName) { + var _a; + const request = DestroySecretRequestMessage.encode({ vaultName, secretName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_SECRET, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DESTROY_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = DestroySecretResponseMessage.decode(subMessage); + return successful; + } + async getSecret(nodePath, vaultName, secretName) { + var _a; + const request = GetSecretRequestMessage.encode({ vaultName, secretName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.GET_SECRET, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.GET_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { secret } = GetSecretResponseMessage.decode(subMessage); + return Buffer.from(secret); + } + /////////////////// + // Agent control // + /////////////////// + async getAgentStatus() { + var _a; + try { + const encodedResponse = await this.handleAgentCommunication(Type.STATUS); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.STATUS)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const status = Buffer.from(subMessage).toString(); + return status; + } + catch (err) { + console.log(err); + return 'stopped'; + } + } + async stopAgent() { + try { + // Tell it to start shutting and wait for response + await this.handleAgentCommunication(Type.STOP_AGENT); + return true; + } + catch (err) { + return (await this.getAgentStatus()) != 'online'; + } + } +} +exports.default = PolykeyClient; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer)) + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ -var r=n(3),s=n(4),o=n(5);function i(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function g(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return V(e).length;default:if(r)return q(e).length;t=(""+t).toLowerCase(),r=!0}}function d(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return S(this,t,n);case"latin1":case"binary":return M(this,t,n);case"base64":return N(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function y(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function w(e,t,n,r,s){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=u.from(t,r)),u.isBuffer(t))return 0===t.length?-1:v(e,t,n,r,s);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):v(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function v(e,t,n,r,s){var o,i=1,a=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;i=2,a/=2,u/=2,n/=2}function c(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(s){var f=-1;for(o=n;oa&&(n=a-u),o=n;o>=0;o--){for(var l=!0,h=0;hs&&(r=s):r=s;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var i=0;i>8,s=n%256,o.push(s),o.push(r);return o}(t,e.length-n),e,n,r)}function N(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function T(e,t,n){n=Math.min(e.length,n);for(var r=[],s=t;s239?4:c>223?3:c>191?2:1;if(s+l<=n)switch(l){case 1:c<128&&(f=c);break;case 2:128==(192&(o=e[s+1]))&&(u=(31&c)<<6|63&o)>127&&(f=u);break;case 3:o=e[s+1],i=e[s+2],128==(192&o)&&128==(192&i)&&(u=(15&c)<<12|(63&o)<<6|63&i)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=e[s+1],i=e[s+2],a=e[s+3],128==(192&o)&&128==(192&i)&&128==(192&a)&&(u=(15&c)<<18|(63&o)<<12|(63&i)<<6|63&a)>65535&&u<1114112&&(f=u)}null===f?(f=65533,l=1):f>65535&&(f-=65536,r.push(f>>>10&1023|55296),f=56320|1023&f),r.push(f),s+=l}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},u.prototype.compare=function(e,t,n,r,s){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(s>>>=0)-(r>>>=0),i=(n>>>=0)-(t>>>=0),a=Math.min(o,i),c=this.slice(r,s),f=e.slice(t,n),l=0;ls)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return b(this,e,t,n);case"utf8":case"utf-8":return m(this,e,t,n);case"ascii":return R(this,e,t,n);case"latin1":case"binary":return E(this,e,t,n);case"base64":return O(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function S(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;sr)&&(n=r);for(var s="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,n,r,s,o){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||te.length)throw new RangeError("Index out of range")}function B(e,t,n,r){t<0&&(t=65535+t+1);for(var s=0,o=Math.min(e.length-n,2);s>>8*(r?s:1-s)}function U(e,t,n,r){t<0&&(t=4294967295+t+1);for(var s=0,o=Math.min(e.length-n,4);s>>8*(r?s:3-s)&255}function L(e,t,n,r,s,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function I(e,t,n,r,o){return o||L(e,0,n,4),s.write(e,t,n,r,23,4),n+4}function D(e,t,n,r,o){return o||L(e,0,n,8),s.write(e,t,n,r,52,8),n+8}u.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(s*=256);)r+=this[e+--t]*s;return r},u.prototype.readUInt8=function(e,t){return t||_(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||_(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||_(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||_(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||_(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||_(e,t,this.length);for(var r=this[e],s=1,o=0;++o=(s*=128)&&(r-=Math.pow(2,8*t)),r},u.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||_(e,t,this.length);for(var r=t,s=1,o=this[e+--r];r>0&&(s*=256);)o+=this[e+--r]*s;return o>=(s*=128)&&(o-=Math.pow(2,8*t)),o},u.prototype.readInt8=function(e,t){return t||_(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||_(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function(e,t){t||_(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function(e,t){return t||_(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||_(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||_(e,4,this.length),s.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||_(e,4,this.length),s.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||_(e,8,this.length),s.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||_(e,8,this.length),s.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||j(this,e,t,n,Math.pow(2,8*n)-1,0);var s=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+s]=e/o&255;return t+n},u.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):B(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):B(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):U(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):U(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var s=Math.pow(2,8*n-1);j(this,e,t,n,s-1,-s)}var o=0,i=1,a=0;for(this[t]=255&e;++o>0)-a&255;return t+n},u.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var s=Math.pow(2,8*n-1);j(this,e,t,n,s-1,-s)}var o=n-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i>>0)-a&255;return t+n},u.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):B(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):B(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):U(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):U(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,n){return I(this,e,t,!0,n)},u.prototype.writeFloatBE=function(e,t,n){return I(this,e,t,!1,n)},u.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},u.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},u.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--s)e[s+t]=this[s+n];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(s=0;s>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(i+1===r){(t-=3)>-1&&o.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&o.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function V(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Y,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function x(e,t,n,r){for(var s=0;s=t.length||s>=e.length);++s)t[s+n]=e[s];return s}}).call(this,n(2))},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t){e.exports=require("base64-js")},function(e,t){e.exports=require("ieee754")},function(e,t){e.exports=require("isarray")},function(e,t,n){"use strict";var r,s,o,i=n(7),a=i.Reader,u=i.Writer,c=i.util,f=i.roots.default||(i.roots.default={});f.agent=((o={}).Type=(r={},(s=Object.create(r))[r[0]="ERROR"]=0,s[r[1]="STOP_AGENT"]=1,s[r[2]="STATUS"]=2,s[r[3]="REGISTER_NODE"]=3,s[r[4]="NEW_NODE"]=4,s[r[5]="LIST_NODES"]=5,s[r[6]="DERIVE_KEY"]=6,s[r[7]="SIGN_FILE"]=7,s[r[8]="VERIFY_FILE"]=8,s[r[9]="LIST_VAULTS"]=9,s[r[10]="NEW_VAULT"]=10,s[r[11]="DESTROY_VAULT"]=11,s[r[12]="LIST_SECRETS"]=12,s[r[13]="CREATE_SECRET"]=13,s[r[14]="DESTROY_SECRET"]=14,s[r[15]="GET_SECRET"]=15,s),o.AgentMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.type=e.int32();break;case 2:r.isResponse=e.bool();break;case 3:r.nodePath=e.string();break;case 4:r.subMessage=e.bytes();break;default:e.skipType(7&s)}}return r},e}(),o.ErrorMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.error=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.RegisterNodeRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.passphrase=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.RegisterNodeResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.successful=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o.NewNodeRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.name=e.string();break;case 2:r.email=e.string();break;case 3:r.passphrase=e.string();break;case 4:r.nbits=e.int32();break;default:e.skipType(7&s)}}return r},e}(),o.NewNodeResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.successful=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o.ListNodesRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.unlockedOnly=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o.ListNodesResponseMessage=function(){function e(e){if(this.nodes=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.nodes&&r.nodes.length||(r.nodes=[]),r.nodes.push(e.string());break;default:e.skipType(7&s)}}return r},e}(),o.SignFileRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.filePath=e.string();break;case 2:r.privateKeyPath=e.string();break;case 3:r.passphrase=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.SignFileResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.signaturePath=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.VerifyFileRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.filePath=e.string();break;case 2:r.signaturePath=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.VerifyFileResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.verified=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o.ListVaultsRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.vaultNames&&r.vaultNames.length||(r.vaultNames=[]),r.vaultNames.push(e.string());break;default:e.skipType(7&s)}}return r},e}(),o.NewVaultRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.vaultName=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.NewVaultResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.successful=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o.DestroyVaultRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.vaultName=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.DestroyVaultResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.successful=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o.ListSecretsRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.vaultName=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.ListSecretsResponseMessage=function(){function e(e){if(this.secretNames=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.secretNames&&r.secretNames.length||(r.secretNames=[]),r.secretNames.push(e.string());break;default:e.skipType(7&s)}}return r},e}(),o.CreateSecretRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.vaultName=e.string();break;case 2:r.secretName=e.string();break;case 3:r.secretPath=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.CreateSecretResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.successful=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o.DestroySecretRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.vaultName=e.string();break;case 2:r.secretName=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.DestroySecretResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.successful=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o.GetSecretRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.vaultName=e.string();break;case 2:r.secretName=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.GetSecretResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.secret=e.bytes();break;default:e.skipType(7&s)}}return r},e}(),o.DeriveKeyRequestMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.vaultName=e.string();break;case 2:r.keyName=e.string();break;case 3:r.passphrase=e.string();break;default:e.skipType(7&s)}}return r},e}(),o.DeriveKeyResponseMessage=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.successful=e.bool();break;default:e.skipType(7&s)}}return r},e}(),o),e.exports=f},function(e,t){e.exports=require("protobufjs/minimal")}])})); +/* eslint-disable no-proto */ + + + +var base64 = __webpack_require__(3) +var ieee754 = __webpack_require__(4) +var isArray = __webpack_require__(5) + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(2))) + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + +module.exports = require("base64-js"); + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + +module.exports = require("ieee754"); + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + +module.exports = require("isarray"); + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ + + +var $protobuf = __webpack_require__(7); + +// Common aliases +var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; + +// Exported root namespace +var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); + +$root.agent = (function() { + + /** + * Namespace agent. + * @exports agent + * @namespace + */ + var agent = {}; + + /** + * Type enum. + * @name agent.Type + * @enum {number} + * @property {number} ERROR=0 ERROR value + * @property {number} STOP_AGENT=1 STOP_AGENT value + * @property {number} STATUS=2 STATUS value + * @property {number} REGISTER_NODE=3 REGISTER_NODE value + * @property {number} NEW_NODE=4 NEW_NODE value + * @property {number} LIST_NODES=5 LIST_NODES value + * @property {number} DERIVE_KEY=6 DERIVE_KEY value + * @property {number} SIGN_FILE=7 SIGN_FILE value + * @property {number} VERIFY_FILE=8 VERIFY_FILE value + * @property {number} LIST_VAULTS=9 LIST_VAULTS value + * @property {number} NEW_VAULT=10 NEW_VAULT value + * @property {number} DESTROY_VAULT=11 DESTROY_VAULT value + * @property {number} LIST_SECRETS=12 LIST_SECRETS value + * @property {number} CREATE_SECRET=13 CREATE_SECRET value + * @property {number} DESTROY_SECRET=14 DESTROY_SECRET value + * @property {number} GET_SECRET=15 GET_SECRET value + */ + agent.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ERROR"] = 0; + values[valuesById[1] = "STOP_AGENT"] = 1; + values[valuesById[2] = "STATUS"] = 2; + values[valuesById[3] = "REGISTER_NODE"] = 3; + values[valuesById[4] = "NEW_NODE"] = 4; + values[valuesById[5] = "LIST_NODES"] = 5; + values[valuesById[6] = "DERIVE_KEY"] = 6; + values[valuesById[7] = "SIGN_FILE"] = 7; + values[valuesById[8] = "VERIFY_FILE"] = 8; + values[valuesById[9] = "LIST_VAULTS"] = 9; + values[valuesById[10] = "NEW_VAULT"] = 10; + values[valuesById[11] = "DESTROY_VAULT"] = 11; + values[valuesById[12] = "LIST_SECRETS"] = 12; + values[valuesById[13] = "CREATE_SECRET"] = 13; + values[valuesById[14] = "DESTROY_SECRET"] = 14; + values[valuesById[15] = "GET_SECRET"] = 15; + return values; + })(); + + agent.AgentMessage = (function() { + + /** + * Properties of an AgentMessage. + * @memberof agent + * @interface IAgentMessage + * @property {agent.Type|null} [type] AgentMessage type + * @property {boolean|null} [isResponse] AgentMessage isResponse + * @property {string|null} [nodePath] AgentMessage nodePath + * @property {Uint8Array|null} [subMessage] AgentMessage subMessage + */ + + /** + * Constructs a new AgentMessage. + * @memberof agent + * @classdesc Represents an AgentMessage. + * @implements IAgentMessage + * @constructor + * @param {agent.IAgentMessage=} [p] Properties to set + */ + function AgentMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * AgentMessage type. + * @member {agent.Type} type + * @memberof agent.AgentMessage + * @instance + */ + AgentMessage.prototype.type = 0; + + /** + * AgentMessage isResponse. + * @member {boolean} isResponse + * @memberof agent.AgentMessage + * @instance + */ + AgentMessage.prototype.isResponse = false; + + /** + * AgentMessage nodePath. + * @member {string} nodePath + * @memberof agent.AgentMessage + * @instance + */ + AgentMessage.prototype.nodePath = ""; + + /** + * AgentMessage subMessage. + * @member {Uint8Array} subMessage + * @memberof agent.AgentMessage + * @instance + */ + AgentMessage.prototype.subMessage = $util.newBuffer([]); + + /** + * Creates a new AgentMessage instance using the specified properties. + * @function create + * @memberof agent.AgentMessage + * @static + * @param {agent.IAgentMessage=} [properties] Properties to set + * @returns {agent.AgentMessage} AgentMessage instance + */ + AgentMessage.create = function create(properties) { + return new AgentMessage(properties); + }; + + /** + * Encodes the specified AgentMessage message. Does not implicitly {@link agent.AgentMessage.verify|verify} messages. + * @function encode + * @memberof agent.AgentMessage + * @static + * @param {agent.IAgentMessage} m AgentMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AgentMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.type != null && Object.hasOwnProperty.call(m, "type")) + w.uint32(8).int32(m.type); + if (m.isResponse != null && Object.hasOwnProperty.call(m, "isResponse")) + w.uint32(16).bool(m.isResponse); + if (m.nodePath != null && Object.hasOwnProperty.call(m, "nodePath")) + w.uint32(26).string(m.nodePath); + if (m.subMessage != null && Object.hasOwnProperty.call(m, "subMessage")) + w.uint32(34).bytes(m.subMessage); + return w; + }; + + /** + * Decodes an AgentMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.AgentMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.AgentMessage} AgentMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AgentMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.AgentMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.type = r.int32(); + break; + case 2: + m.isResponse = r.bool(); + break; + case 3: + m.nodePath = r.string(); + break; + case 4: + m.subMessage = r.bytes(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return AgentMessage; + })(); + + agent.ErrorMessage = (function() { + + /** + * Properties of an ErrorMessage. + * @memberof agent + * @interface IErrorMessage + * @property {string|null} [error] ErrorMessage error + */ + + /** + * Constructs a new ErrorMessage. + * @memberof agent + * @classdesc Represents an ErrorMessage. + * @implements IErrorMessage + * @constructor + * @param {agent.IErrorMessage=} [p] Properties to set + */ + function ErrorMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * ErrorMessage error. + * @member {string} error + * @memberof agent.ErrorMessage + * @instance + */ + ErrorMessage.prototype.error = ""; + + /** + * Creates a new ErrorMessage instance using the specified properties. + * @function create + * @memberof agent.ErrorMessage + * @static + * @param {agent.IErrorMessage=} [properties] Properties to set + * @returns {agent.ErrorMessage} ErrorMessage instance + */ + ErrorMessage.create = function create(properties) { + return new ErrorMessage(properties); + }; + + /** + * Encodes the specified ErrorMessage message. Does not implicitly {@link agent.ErrorMessage.verify|verify} messages. + * @function encode + * @memberof agent.ErrorMessage + * @static + * @param {agent.IErrorMessage} m ErrorMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ErrorMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.error != null && Object.hasOwnProperty.call(m, "error")) + w.uint32(10).string(m.error); + return w; + }; + + /** + * Decodes an ErrorMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.ErrorMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.ErrorMessage} ErrorMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ErrorMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ErrorMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.error = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return ErrorMessage; + })(); + + agent.RegisterNodeRequestMessage = (function() { + + /** + * Properties of a RegisterNodeRequestMessage. + * @memberof agent + * @interface IRegisterNodeRequestMessage + * @property {string|null} [passphrase] RegisterNodeRequestMessage passphrase + */ + + /** + * Constructs a new RegisterNodeRequestMessage. + * @memberof agent + * @classdesc Represents a RegisterNodeRequestMessage. + * @implements IRegisterNodeRequestMessage + * @constructor + * @param {agent.IRegisterNodeRequestMessage=} [p] Properties to set + */ + function RegisterNodeRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * RegisterNodeRequestMessage passphrase. + * @member {string} passphrase + * @memberof agent.RegisterNodeRequestMessage + * @instance + */ + RegisterNodeRequestMessage.prototype.passphrase = ""; + + /** + * Creates a new RegisterNodeRequestMessage instance using the specified properties. + * @function create + * @memberof agent.RegisterNodeRequestMessage + * @static + * @param {agent.IRegisterNodeRequestMessage=} [properties] Properties to set + * @returns {agent.RegisterNodeRequestMessage} RegisterNodeRequestMessage instance + */ + RegisterNodeRequestMessage.create = function create(properties) { + return new RegisterNodeRequestMessage(properties); + }; + + /** + * Encodes the specified RegisterNodeRequestMessage message. Does not implicitly {@link agent.RegisterNodeRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.RegisterNodeRequestMessage + * @static + * @param {agent.IRegisterNodeRequestMessage} m RegisterNodeRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RegisterNodeRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.passphrase != null && Object.hasOwnProperty.call(m, "passphrase")) + w.uint32(10).string(m.passphrase); + return w; + }; + + /** + * Decodes a RegisterNodeRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.RegisterNodeRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.RegisterNodeRequestMessage} RegisterNodeRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RegisterNodeRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.RegisterNodeRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.passphrase = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return RegisterNodeRequestMessage; + })(); + + agent.RegisterNodeResponseMessage = (function() { + + /** + * Properties of a RegisterNodeResponseMessage. + * @memberof agent + * @interface IRegisterNodeResponseMessage + * @property {boolean|null} [successful] RegisterNodeResponseMessage successful + */ + + /** + * Constructs a new RegisterNodeResponseMessage. + * @memberof agent + * @classdesc Represents a RegisterNodeResponseMessage. + * @implements IRegisterNodeResponseMessage + * @constructor + * @param {agent.IRegisterNodeResponseMessage=} [p] Properties to set + */ + function RegisterNodeResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * RegisterNodeResponseMessage successful. + * @member {boolean} successful + * @memberof agent.RegisterNodeResponseMessage + * @instance + */ + RegisterNodeResponseMessage.prototype.successful = false; + + /** + * Creates a new RegisterNodeResponseMessage instance using the specified properties. + * @function create + * @memberof agent.RegisterNodeResponseMessage + * @static + * @param {agent.IRegisterNodeResponseMessage=} [properties] Properties to set + * @returns {agent.RegisterNodeResponseMessage} RegisterNodeResponseMessage instance + */ + RegisterNodeResponseMessage.create = function create(properties) { + return new RegisterNodeResponseMessage(properties); + }; + + /** + * Encodes the specified RegisterNodeResponseMessage message. Does not implicitly {@link agent.RegisterNodeResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.RegisterNodeResponseMessage + * @static + * @param {agent.IRegisterNodeResponseMessage} m RegisterNodeResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RegisterNodeResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.successful != null && Object.hasOwnProperty.call(m, "successful")) + w.uint32(8).bool(m.successful); + return w; + }; + + /** + * Decodes a RegisterNodeResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.RegisterNodeResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.RegisterNodeResponseMessage} RegisterNodeResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RegisterNodeResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.RegisterNodeResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.successful = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return RegisterNodeResponseMessage; + })(); + + agent.NewNodeRequestMessage = (function() { + + /** + * Properties of a NewNodeRequestMessage. + * @memberof agent + * @interface INewNodeRequestMessage + * @property {string|null} [name] NewNodeRequestMessage name + * @property {string|null} [email] NewNodeRequestMessage email + * @property {string|null} [passphrase] NewNodeRequestMessage passphrase + * @property {number|null} [nbits] NewNodeRequestMessage nbits + */ + + /** + * Constructs a new NewNodeRequestMessage. + * @memberof agent + * @classdesc Represents a NewNodeRequestMessage. + * @implements INewNodeRequestMessage + * @constructor + * @param {agent.INewNodeRequestMessage=} [p] Properties to set + */ + function NewNodeRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * NewNodeRequestMessage name. + * @member {string} name + * @memberof agent.NewNodeRequestMessage + * @instance + */ + NewNodeRequestMessage.prototype.name = ""; + + /** + * NewNodeRequestMessage email. + * @member {string} email + * @memberof agent.NewNodeRequestMessage + * @instance + */ + NewNodeRequestMessage.prototype.email = ""; + + /** + * NewNodeRequestMessage passphrase. + * @member {string} passphrase + * @memberof agent.NewNodeRequestMessage + * @instance + */ + NewNodeRequestMessage.prototype.passphrase = ""; + + /** + * NewNodeRequestMessage nbits. + * @member {number} nbits + * @memberof agent.NewNodeRequestMessage + * @instance + */ + NewNodeRequestMessage.prototype.nbits = 0; + + /** + * Creates a new NewNodeRequestMessage instance using the specified properties. + * @function create + * @memberof agent.NewNodeRequestMessage + * @static + * @param {agent.INewNodeRequestMessage=} [properties] Properties to set + * @returns {agent.NewNodeRequestMessage} NewNodeRequestMessage instance + */ + NewNodeRequestMessage.create = function create(properties) { + return new NewNodeRequestMessage(properties); + }; + + /** + * Encodes the specified NewNodeRequestMessage message. Does not implicitly {@link agent.NewNodeRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.NewNodeRequestMessage + * @static + * @param {agent.INewNodeRequestMessage} m NewNodeRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NewNodeRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.name != null && Object.hasOwnProperty.call(m, "name")) + w.uint32(10).string(m.name); + if (m.email != null && Object.hasOwnProperty.call(m, "email")) + w.uint32(18).string(m.email); + if (m.passphrase != null && Object.hasOwnProperty.call(m, "passphrase")) + w.uint32(26).string(m.passphrase); + if (m.nbits != null && Object.hasOwnProperty.call(m, "nbits")) + w.uint32(32).int32(m.nbits); + return w; + }; + + /** + * Decodes a NewNodeRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.NewNodeRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.NewNodeRequestMessage} NewNodeRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NewNodeRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewNodeRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.name = r.string(); + break; + case 2: + m.email = r.string(); + break; + case 3: + m.passphrase = r.string(); + break; + case 4: + m.nbits = r.int32(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return NewNodeRequestMessage; + })(); + + agent.NewNodeResponseMessage = (function() { + + /** + * Properties of a NewNodeResponseMessage. + * @memberof agent + * @interface INewNodeResponseMessage + * @property {boolean|null} [successful] NewNodeResponseMessage successful + */ + + /** + * Constructs a new NewNodeResponseMessage. + * @memberof agent + * @classdesc Represents a NewNodeResponseMessage. + * @implements INewNodeResponseMessage + * @constructor + * @param {agent.INewNodeResponseMessage=} [p] Properties to set + */ + function NewNodeResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * NewNodeResponseMessage successful. + * @member {boolean} successful + * @memberof agent.NewNodeResponseMessage + * @instance + */ + NewNodeResponseMessage.prototype.successful = false; + + /** + * Creates a new NewNodeResponseMessage instance using the specified properties. + * @function create + * @memberof agent.NewNodeResponseMessage + * @static + * @param {agent.INewNodeResponseMessage=} [properties] Properties to set + * @returns {agent.NewNodeResponseMessage} NewNodeResponseMessage instance + */ + NewNodeResponseMessage.create = function create(properties) { + return new NewNodeResponseMessage(properties); + }; + + /** + * Encodes the specified NewNodeResponseMessage message. Does not implicitly {@link agent.NewNodeResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.NewNodeResponseMessage + * @static + * @param {agent.INewNodeResponseMessage} m NewNodeResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NewNodeResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.successful != null && Object.hasOwnProperty.call(m, "successful")) + w.uint32(8).bool(m.successful); + return w; + }; + + /** + * Decodes a NewNodeResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.NewNodeResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.NewNodeResponseMessage} NewNodeResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NewNodeResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewNodeResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.successful = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return NewNodeResponseMessage; + })(); + + agent.ListNodesRequestMessage = (function() { + + /** + * Properties of a ListNodesRequestMessage. + * @memberof agent + * @interface IListNodesRequestMessage + * @property {boolean|null} [unlockedOnly] ListNodesRequestMessage unlockedOnly + */ + + /** + * Constructs a new ListNodesRequestMessage. + * @memberof agent + * @classdesc Represents a ListNodesRequestMessage. + * @implements IListNodesRequestMessage + * @constructor + * @param {agent.IListNodesRequestMessage=} [p] Properties to set + */ + function ListNodesRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * ListNodesRequestMessage unlockedOnly. + * @member {boolean} unlockedOnly + * @memberof agent.ListNodesRequestMessage + * @instance + */ + ListNodesRequestMessage.prototype.unlockedOnly = false; + + /** + * Creates a new ListNodesRequestMessage instance using the specified properties. + * @function create + * @memberof agent.ListNodesRequestMessage + * @static + * @param {agent.IListNodesRequestMessage=} [properties] Properties to set + * @returns {agent.ListNodesRequestMessage} ListNodesRequestMessage instance + */ + ListNodesRequestMessage.create = function create(properties) { + return new ListNodesRequestMessage(properties); + }; + + /** + * Encodes the specified ListNodesRequestMessage message. Does not implicitly {@link agent.ListNodesRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.ListNodesRequestMessage + * @static + * @param {agent.IListNodesRequestMessage} m ListNodesRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListNodesRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.unlockedOnly != null && Object.hasOwnProperty.call(m, "unlockedOnly")) + w.uint32(8).bool(m.unlockedOnly); + return w; + }; + + /** + * Decodes a ListNodesRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.ListNodesRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.ListNodesRequestMessage} ListNodesRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListNodesRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListNodesRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.unlockedOnly = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return ListNodesRequestMessage; + })(); + + agent.ListNodesResponseMessage = (function() { + + /** + * Properties of a ListNodesResponseMessage. + * @memberof agent + * @interface IListNodesResponseMessage + * @property {Array.|null} [nodes] ListNodesResponseMessage nodes + */ + + /** + * Constructs a new ListNodesResponseMessage. + * @memberof agent + * @classdesc Represents a ListNodesResponseMessage. + * @implements IListNodesResponseMessage + * @constructor + * @param {agent.IListNodesResponseMessage=} [p] Properties to set + */ + function ListNodesResponseMessage(p) { + this.nodes = []; + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * ListNodesResponseMessage nodes. + * @member {Array.} nodes + * @memberof agent.ListNodesResponseMessage + * @instance + */ + ListNodesResponseMessage.prototype.nodes = $util.emptyArray; + + /** + * Creates a new ListNodesResponseMessage instance using the specified properties. + * @function create + * @memberof agent.ListNodesResponseMessage + * @static + * @param {agent.IListNodesResponseMessage=} [properties] Properties to set + * @returns {agent.ListNodesResponseMessage} ListNodesResponseMessage instance + */ + ListNodesResponseMessage.create = function create(properties) { + return new ListNodesResponseMessage(properties); + }; + + /** + * Encodes the specified ListNodesResponseMessage message. Does not implicitly {@link agent.ListNodesResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.ListNodesResponseMessage + * @static + * @param {agent.IListNodesResponseMessage} m ListNodesResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListNodesResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.nodes != null && m.nodes.length) { + for (var i = 0; i < m.nodes.length; ++i) + w.uint32(10).string(m.nodes[i]); + } + return w; + }; + + /** + * Decodes a ListNodesResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.ListNodesResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.ListNodesResponseMessage} ListNodesResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListNodesResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListNodesResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + if (!(m.nodes && m.nodes.length)) + m.nodes = []; + m.nodes.push(r.string()); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return ListNodesResponseMessage; + })(); + + agent.SignFileRequestMessage = (function() { + + /** + * Properties of a SignFileRequestMessage. + * @memberof agent + * @interface ISignFileRequestMessage + * @property {string|null} [filePath] SignFileRequestMessage filePath + * @property {string|null} [privateKeyPath] SignFileRequestMessage privateKeyPath + * @property {string|null} [passphrase] SignFileRequestMessage passphrase + */ + + /** + * Constructs a new SignFileRequestMessage. + * @memberof agent + * @classdesc Represents a SignFileRequestMessage. + * @implements ISignFileRequestMessage + * @constructor + * @param {agent.ISignFileRequestMessage=} [p] Properties to set + */ + function SignFileRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * SignFileRequestMessage filePath. + * @member {string} filePath + * @memberof agent.SignFileRequestMessage + * @instance + */ + SignFileRequestMessage.prototype.filePath = ""; + + /** + * SignFileRequestMessage privateKeyPath. + * @member {string} privateKeyPath + * @memberof agent.SignFileRequestMessage + * @instance + */ + SignFileRequestMessage.prototype.privateKeyPath = ""; + + /** + * SignFileRequestMessage passphrase. + * @member {string} passphrase + * @memberof agent.SignFileRequestMessage + * @instance + */ + SignFileRequestMessage.prototype.passphrase = ""; + + /** + * Creates a new SignFileRequestMessage instance using the specified properties. + * @function create + * @memberof agent.SignFileRequestMessage + * @static + * @param {agent.ISignFileRequestMessage=} [properties] Properties to set + * @returns {agent.SignFileRequestMessage} SignFileRequestMessage instance + */ + SignFileRequestMessage.create = function create(properties) { + return new SignFileRequestMessage(properties); + }; + + /** + * Encodes the specified SignFileRequestMessage message. Does not implicitly {@link agent.SignFileRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.SignFileRequestMessage + * @static + * @param {agent.ISignFileRequestMessage} m SignFileRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SignFileRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.filePath != null && Object.hasOwnProperty.call(m, "filePath")) + w.uint32(10).string(m.filePath); + if (m.privateKeyPath != null && Object.hasOwnProperty.call(m, "privateKeyPath")) + w.uint32(18).string(m.privateKeyPath); + if (m.passphrase != null && Object.hasOwnProperty.call(m, "passphrase")) + w.uint32(26).string(m.passphrase); + return w; + }; + + /** + * Decodes a SignFileRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.SignFileRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.SignFileRequestMessage} SignFileRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SignFileRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.SignFileRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.filePath = r.string(); + break; + case 2: + m.privateKeyPath = r.string(); + break; + case 3: + m.passphrase = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return SignFileRequestMessage; + })(); + + agent.SignFileResponseMessage = (function() { + + /** + * Properties of a SignFileResponseMessage. + * @memberof agent + * @interface ISignFileResponseMessage + * @property {string|null} [signaturePath] SignFileResponseMessage signaturePath + */ + + /** + * Constructs a new SignFileResponseMessage. + * @memberof agent + * @classdesc Represents a SignFileResponseMessage. + * @implements ISignFileResponseMessage + * @constructor + * @param {agent.ISignFileResponseMessage=} [p] Properties to set + */ + function SignFileResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * SignFileResponseMessage signaturePath. + * @member {string} signaturePath + * @memberof agent.SignFileResponseMessage + * @instance + */ + SignFileResponseMessage.prototype.signaturePath = ""; + + /** + * Creates a new SignFileResponseMessage instance using the specified properties. + * @function create + * @memberof agent.SignFileResponseMessage + * @static + * @param {agent.ISignFileResponseMessage=} [properties] Properties to set + * @returns {agent.SignFileResponseMessage} SignFileResponseMessage instance + */ + SignFileResponseMessage.create = function create(properties) { + return new SignFileResponseMessage(properties); + }; + + /** + * Encodes the specified SignFileResponseMessage message. Does not implicitly {@link agent.SignFileResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.SignFileResponseMessage + * @static + * @param {agent.ISignFileResponseMessage} m SignFileResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SignFileResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.signaturePath != null && Object.hasOwnProperty.call(m, "signaturePath")) + w.uint32(10).string(m.signaturePath); + return w; + }; + + /** + * Decodes a SignFileResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.SignFileResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.SignFileResponseMessage} SignFileResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SignFileResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.SignFileResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.signaturePath = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return SignFileResponseMessage; + })(); + + agent.VerifyFileRequestMessage = (function() { + + /** + * Properties of a VerifyFileRequestMessage. + * @memberof agent + * @interface IVerifyFileRequestMessage + * @property {string|null} [filePath] VerifyFileRequestMessage filePath + * @property {string|null} [signaturePath] VerifyFileRequestMessage signaturePath + */ + + /** + * Constructs a new VerifyFileRequestMessage. + * @memberof agent + * @classdesc Represents a VerifyFileRequestMessage. + * @implements IVerifyFileRequestMessage + * @constructor + * @param {agent.IVerifyFileRequestMessage=} [p] Properties to set + */ + function VerifyFileRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * VerifyFileRequestMessage filePath. + * @member {string} filePath + * @memberof agent.VerifyFileRequestMessage + * @instance + */ + VerifyFileRequestMessage.prototype.filePath = ""; + + /** + * VerifyFileRequestMessage signaturePath. + * @member {string} signaturePath + * @memberof agent.VerifyFileRequestMessage + * @instance + */ + VerifyFileRequestMessage.prototype.signaturePath = ""; + + /** + * Creates a new VerifyFileRequestMessage instance using the specified properties. + * @function create + * @memberof agent.VerifyFileRequestMessage + * @static + * @param {agent.IVerifyFileRequestMessage=} [properties] Properties to set + * @returns {agent.VerifyFileRequestMessage} VerifyFileRequestMessage instance + */ + VerifyFileRequestMessage.create = function create(properties) { + return new VerifyFileRequestMessage(properties); + }; + + /** + * Encodes the specified VerifyFileRequestMessage message. Does not implicitly {@link agent.VerifyFileRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.VerifyFileRequestMessage + * @static + * @param {agent.IVerifyFileRequestMessage} m VerifyFileRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VerifyFileRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.filePath != null && Object.hasOwnProperty.call(m, "filePath")) + w.uint32(10).string(m.filePath); + if (m.signaturePath != null && Object.hasOwnProperty.call(m, "signaturePath")) + w.uint32(18).string(m.signaturePath); + return w; + }; + + /** + * Decodes a VerifyFileRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.VerifyFileRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.VerifyFileRequestMessage} VerifyFileRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VerifyFileRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.VerifyFileRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.filePath = r.string(); + break; + case 2: + m.signaturePath = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return VerifyFileRequestMessage; + })(); + + agent.VerifyFileResponseMessage = (function() { + + /** + * Properties of a VerifyFileResponseMessage. + * @memberof agent + * @interface IVerifyFileResponseMessage + * @property {boolean|null} [verified] VerifyFileResponseMessage verified + */ + + /** + * Constructs a new VerifyFileResponseMessage. + * @memberof agent + * @classdesc Represents a VerifyFileResponseMessage. + * @implements IVerifyFileResponseMessage + * @constructor + * @param {agent.IVerifyFileResponseMessage=} [p] Properties to set + */ + function VerifyFileResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * VerifyFileResponseMessage verified. + * @member {boolean} verified + * @memberof agent.VerifyFileResponseMessage + * @instance + */ + VerifyFileResponseMessage.prototype.verified = false; + + /** + * Creates a new VerifyFileResponseMessage instance using the specified properties. + * @function create + * @memberof agent.VerifyFileResponseMessage + * @static + * @param {agent.IVerifyFileResponseMessage=} [properties] Properties to set + * @returns {agent.VerifyFileResponseMessage} VerifyFileResponseMessage instance + */ + VerifyFileResponseMessage.create = function create(properties) { + return new VerifyFileResponseMessage(properties); + }; + + /** + * Encodes the specified VerifyFileResponseMessage message. Does not implicitly {@link agent.VerifyFileResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.VerifyFileResponseMessage + * @static + * @param {agent.IVerifyFileResponseMessage} m VerifyFileResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VerifyFileResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.verified != null && Object.hasOwnProperty.call(m, "verified")) + w.uint32(8).bool(m.verified); + return w; + }; + + /** + * Decodes a VerifyFileResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.VerifyFileResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.VerifyFileResponseMessage} VerifyFileResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VerifyFileResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.VerifyFileResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.verified = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return VerifyFileResponseMessage; + })(); + + agent.ListVaultsRequestMessage = (function() { + + /** + * Properties of a ListVaultsRequestMessage. + * @memberof agent + * @interface IListVaultsRequestMessage + */ + + /** + * Constructs a new ListVaultsRequestMessage. + * @memberof agent + * @classdesc Represents a ListVaultsRequestMessage. + * @implements IListVaultsRequestMessage + * @constructor + * @param {agent.IListVaultsRequestMessage=} [p] Properties to set + */ + function ListVaultsRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * Creates a new ListVaultsRequestMessage instance using the specified properties. + * @function create + * @memberof agent.ListVaultsRequestMessage + * @static + * @param {agent.IListVaultsRequestMessage=} [properties] Properties to set + * @returns {agent.ListVaultsRequestMessage} ListVaultsRequestMessage instance + */ + ListVaultsRequestMessage.create = function create(properties) { + return new ListVaultsRequestMessage(properties); + }; + + /** + * Encodes the specified ListVaultsRequestMessage message. Does not implicitly {@link agent.ListVaultsRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.ListVaultsRequestMessage + * @static + * @param {agent.IListVaultsRequestMessage} m ListVaultsRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListVaultsRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + return w; + }; + + /** + * Decodes a ListVaultsRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.ListVaultsRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.ListVaultsRequestMessage} ListVaultsRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListVaultsRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListVaultsRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return ListVaultsRequestMessage; + })(); + + agent.ListVaultsResponseMessage = (function() { + + /** + * Properties of a ListVaultsResponseMessage. + * @memberof agent + * @interface IListVaultsResponseMessage + * @property {Array.|null} [vaultNames] ListVaultsResponseMessage vaultNames + */ + + /** + * Constructs a new ListVaultsResponseMessage. + * @memberof agent + * @classdesc Represents a ListVaultsResponseMessage. + * @implements IListVaultsResponseMessage + * @constructor + * @param {agent.IListVaultsResponseMessage=} [p] Properties to set + */ + function ListVaultsResponseMessage(p) { + this.vaultNames = []; + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * ListVaultsResponseMessage vaultNames. + * @member {Array.} vaultNames + * @memberof agent.ListVaultsResponseMessage + * @instance + */ + ListVaultsResponseMessage.prototype.vaultNames = $util.emptyArray; + + /** + * Creates a new ListVaultsResponseMessage instance using the specified properties. + * @function create + * @memberof agent.ListVaultsResponseMessage + * @static + * @param {agent.IListVaultsResponseMessage=} [properties] Properties to set + * @returns {agent.ListVaultsResponseMessage} ListVaultsResponseMessage instance + */ + ListVaultsResponseMessage.create = function create(properties) { + return new ListVaultsResponseMessage(properties); + }; + + /** + * Encodes the specified ListVaultsResponseMessage message. Does not implicitly {@link agent.ListVaultsResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.ListVaultsResponseMessage + * @static + * @param {agent.IListVaultsResponseMessage} m ListVaultsResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListVaultsResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.vaultNames != null && m.vaultNames.length) { + for (var i = 0; i < m.vaultNames.length; ++i) + w.uint32(10).string(m.vaultNames[i]); + } + return w; + }; + + /** + * Decodes a ListVaultsResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.ListVaultsResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.ListVaultsResponseMessage} ListVaultsResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListVaultsResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListVaultsResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + if (!(m.vaultNames && m.vaultNames.length)) + m.vaultNames = []; + m.vaultNames.push(r.string()); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return ListVaultsResponseMessage; + })(); + + agent.NewVaultRequestMessage = (function() { + + /** + * Properties of a NewVaultRequestMessage. + * @memberof agent + * @interface INewVaultRequestMessage + * @property {string|null} [vaultName] NewVaultRequestMessage vaultName + */ + + /** + * Constructs a new NewVaultRequestMessage. + * @memberof agent + * @classdesc Represents a NewVaultRequestMessage. + * @implements INewVaultRequestMessage + * @constructor + * @param {agent.INewVaultRequestMessage=} [p] Properties to set + */ + function NewVaultRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * NewVaultRequestMessage vaultName. + * @member {string} vaultName + * @memberof agent.NewVaultRequestMessage + * @instance + */ + NewVaultRequestMessage.prototype.vaultName = ""; + + /** + * Creates a new NewVaultRequestMessage instance using the specified properties. + * @function create + * @memberof agent.NewVaultRequestMessage + * @static + * @param {agent.INewVaultRequestMessage=} [properties] Properties to set + * @returns {agent.NewVaultRequestMessage} NewVaultRequestMessage instance + */ + NewVaultRequestMessage.create = function create(properties) { + return new NewVaultRequestMessage(properties); + }; + + /** + * Encodes the specified NewVaultRequestMessage message. Does not implicitly {@link agent.NewVaultRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.NewVaultRequestMessage + * @static + * @param {agent.INewVaultRequestMessage} m NewVaultRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NewVaultRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.vaultName != null && Object.hasOwnProperty.call(m, "vaultName")) + w.uint32(10).string(m.vaultName); + return w; + }; + + /** + * Decodes a NewVaultRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.NewVaultRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.NewVaultRequestMessage} NewVaultRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NewVaultRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewVaultRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.vaultName = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return NewVaultRequestMessage; + })(); + + agent.NewVaultResponseMessage = (function() { + + /** + * Properties of a NewVaultResponseMessage. + * @memberof agent + * @interface INewVaultResponseMessage + * @property {boolean|null} [successful] NewVaultResponseMessage successful + */ + + /** + * Constructs a new NewVaultResponseMessage. + * @memberof agent + * @classdesc Represents a NewVaultResponseMessage. + * @implements INewVaultResponseMessage + * @constructor + * @param {agent.INewVaultResponseMessage=} [p] Properties to set + */ + function NewVaultResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * NewVaultResponseMessage successful. + * @member {boolean} successful + * @memberof agent.NewVaultResponseMessage + * @instance + */ + NewVaultResponseMessage.prototype.successful = false; + + /** + * Creates a new NewVaultResponseMessage instance using the specified properties. + * @function create + * @memberof agent.NewVaultResponseMessage + * @static + * @param {agent.INewVaultResponseMessage=} [properties] Properties to set + * @returns {agent.NewVaultResponseMessage} NewVaultResponseMessage instance + */ + NewVaultResponseMessage.create = function create(properties) { + return new NewVaultResponseMessage(properties); + }; + + /** + * Encodes the specified NewVaultResponseMessage message. Does not implicitly {@link agent.NewVaultResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.NewVaultResponseMessage + * @static + * @param {agent.INewVaultResponseMessage} m NewVaultResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NewVaultResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.successful != null && Object.hasOwnProperty.call(m, "successful")) + w.uint32(8).bool(m.successful); + return w; + }; + + /** + * Decodes a NewVaultResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.NewVaultResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.NewVaultResponseMessage} NewVaultResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NewVaultResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewVaultResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.successful = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return NewVaultResponseMessage; + })(); + + agent.DestroyVaultRequestMessage = (function() { + + /** + * Properties of a DestroyVaultRequestMessage. + * @memberof agent + * @interface IDestroyVaultRequestMessage + * @property {string|null} [vaultName] DestroyVaultRequestMessage vaultName + */ + + /** + * Constructs a new DestroyVaultRequestMessage. + * @memberof agent + * @classdesc Represents a DestroyVaultRequestMessage. + * @implements IDestroyVaultRequestMessage + * @constructor + * @param {agent.IDestroyVaultRequestMessage=} [p] Properties to set + */ + function DestroyVaultRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * DestroyVaultRequestMessage vaultName. + * @member {string} vaultName + * @memberof agent.DestroyVaultRequestMessage + * @instance + */ + DestroyVaultRequestMessage.prototype.vaultName = ""; + + /** + * Creates a new DestroyVaultRequestMessage instance using the specified properties. + * @function create + * @memberof agent.DestroyVaultRequestMessage + * @static + * @param {agent.IDestroyVaultRequestMessage=} [properties] Properties to set + * @returns {agent.DestroyVaultRequestMessage} DestroyVaultRequestMessage instance + */ + DestroyVaultRequestMessage.create = function create(properties) { + return new DestroyVaultRequestMessage(properties); + }; + + /** + * Encodes the specified DestroyVaultRequestMessage message. Does not implicitly {@link agent.DestroyVaultRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.DestroyVaultRequestMessage + * @static + * @param {agent.IDestroyVaultRequestMessage} m DestroyVaultRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DestroyVaultRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.vaultName != null && Object.hasOwnProperty.call(m, "vaultName")) + w.uint32(10).string(m.vaultName); + return w; + }; + + /** + * Decodes a DestroyVaultRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.DestroyVaultRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.DestroyVaultRequestMessage} DestroyVaultRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DestroyVaultRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroyVaultRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.vaultName = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return DestroyVaultRequestMessage; + })(); + + agent.DestroyVaultResponseMessage = (function() { + + /** + * Properties of a DestroyVaultResponseMessage. + * @memberof agent + * @interface IDestroyVaultResponseMessage + * @property {boolean|null} [successful] DestroyVaultResponseMessage successful + */ + + /** + * Constructs a new DestroyVaultResponseMessage. + * @memberof agent + * @classdesc Represents a DestroyVaultResponseMessage. + * @implements IDestroyVaultResponseMessage + * @constructor + * @param {agent.IDestroyVaultResponseMessage=} [p] Properties to set + */ + function DestroyVaultResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * DestroyVaultResponseMessage successful. + * @member {boolean} successful + * @memberof agent.DestroyVaultResponseMessage + * @instance + */ + DestroyVaultResponseMessage.prototype.successful = false; + + /** + * Creates a new DestroyVaultResponseMessage instance using the specified properties. + * @function create + * @memberof agent.DestroyVaultResponseMessage + * @static + * @param {agent.IDestroyVaultResponseMessage=} [properties] Properties to set + * @returns {agent.DestroyVaultResponseMessage} DestroyVaultResponseMessage instance + */ + DestroyVaultResponseMessage.create = function create(properties) { + return new DestroyVaultResponseMessage(properties); + }; + + /** + * Encodes the specified DestroyVaultResponseMessage message. Does not implicitly {@link agent.DestroyVaultResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.DestroyVaultResponseMessage + * @static + * @param {agent.IDestroyVaultResponseMessage} m DestroyVaultResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DestroyVaultResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.successful != null && Object.hasOwnProperty.call(m, "successful")) + w.uint32(8).bool(m.successful); + return w; + }; + + /** + * Decodes a DestroyVaultResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.DestroyVaultResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.DestroyVaultResponseMessage} DestroyVaultResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DestroyVaultResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroyVaultResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.successful = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return DestroyVaultResponseMessage; + })(); + + agent.ListSecretsRequestMessage = (function() { + + /** + * Properties of a ListSecretsRequestMessage. + * @memberof agent + * @interface IListSecretsRequestMessage + * @property {string|null} [vaultName] ListSecretsRequestMessage vaultName + */ + + /** + * Constructs a new ListSecretsRequestMessage. + * @memberof agent + * @classdesc Represents a ListSecretsRequestMessage. + * @implements IListSecretsRequestMessage + * @constructor + * @param {agent.IListSecretsRequestMessage=} [p] Properties to set + */ + function ListSecretsRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * ListSecretsRequestMessage vaultName. + * @member {string} vaultName + * @memberof agent.ListSecretsRequestMessage + * @instance + */ + ListSecretsRequestMessage.prototype.vaultName = ""; + + /** + * Creates a new ListSecretsRequestMessage instance using the specified properties. + * @function create + * @memberof agent.ListSecretsRequestMessage + * @static + * @param {agent.IListSecretsRequestMessage=} [properties] Properties to set + * @returns {agent.ListSecretsRequestMessage} ListSecretsRequestMessage instance + */ + ListSecretsRequestMessage.create = function create(properties) { + return new ListSecretsRequestMessage(properties); + }; + + /** + * Encodes the specified ListSecretsRequestMessage message. Does not implicitly {@link agent.ListSecretsRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.ListSecretsRequestMessage + * @static + * @param {agent.IListSecretsRequestMessage} m ListSecretsRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSecretsRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.vaultName != null && Object.hasOwnProperty.call(m, "vaultName")) + w.uint32(10).string(m.vaultName); + return w; + }; + + /** + * Decodes a ListSecretsRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.ListSecretsRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.ListSecretsRequestMessage} ListSecretsRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSecretsRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListSecretsRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.vaultName = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return ListSecretsRequestMessage; + })(); + + agent.ListSecretsResponseMessage = (function() { + + /** + * Properties of a ListSecretsResponseMessage. + * @memberof agent + * @interface IListSecretsResponseMessage + * @property {Array.|null} [secretNames] ListSecretsResponseMessage secretNames + */ + + /** + * Constructs a new ListSecretsResponseMessage. + * @memberof agent + * @classdesc Represents a ListSecretsResponseMessage. + * @implements IListSecretsResponseMessage + * @constructor + * @param {agent.IListSecretsResponseMessage=} [p] Properties to set + */ + function ListSecretsResponseMessage(p) { + this.secretNames = []; + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * ListSecretsResponseMessage secretNames. + * @member {Array.} secretNames + * @memberof agent.ListSecretsResponseMessage + * @instance + */ + ListSecretsResponseMessage.prototype.secretNames = $util.emptyArray; + + /** + * Creates a new ListSecretsResponseMessage instance using the specified properties. + * @function create + * @memberof agent.ListSecretsResponseMessage + * @static + * @param {agent.IListSecretsResponseMessage=} [properties] Properties to set + * @returns {agent.ListSecretsResponseMessage} ListSecretsResponseMessage instance + */ + ListSecretsResponseMessage.create = function create(properties) { + return new ListSecretsResponseMessage(properties); + }; + + /** + * Encodes the specified ListSecretsResponseMessage message. Does not implicitly {@link agent.ListSecretsResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.ListSecretsResponseMessage + * @static + * @param {agent.IListSecretsResponseMessage} m ListSecretsResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSecretsResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.secretNames != null && m.secretNames.length) { + for (var i = 0; i < m.secretNames.length; ++i) + w.uint32(10).string(m.secretNames[i]); + } + return w; + }; + + /** + * Decodes a ListSecretsResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.ListSecretsResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.ListSecretsResponseMessage} ListSecretsResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSecretsResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListSecretsResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + if (!(m.secretNames && m.secretNames.length)) + m.secretNames = []; + m.secretNames.push(r.string()); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return ListSecretsResponseMessage; + })(); + + agent.CreateSecretRequestMessage = (function() { + + /** + * Properties of a CreateSecretRequestMessage. + * @memberof agent + * @interface ICreateSecretRequestMessage + * @property {string|null} [vaultName] CreateSecretRequestMessage vaultName + * @property {string|null} [secretName] CreateSecretRequestMessage secretName + * @property {string|null} [secretPath] CreateSecretRequestMessage secretPath + * @property {Uint8Array|null} [secretContent] CreateSecretRequestMessage secretContent + */ + + /** + * Constructs a new CreateSecretRequestMessage. + * @memberof agent + * @classdesc Represents a CreateSecretRequestMessage. + * @implements ICreateSecretRequestMessage + * @constructor + * @param {agent.ICreateSecretRequestMessage=} [p] Properties to set + */ + function CreateSecretRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * CreateSecretRequestMessage vaultName. + * @member {string} vaultName + * @memberof agent.CreateSecretRequestMessage + * @instance + */ + CreateSecretRequestMessage.prototype.vaultName = ""; + + /** + * CreateSecretRequestMessage secretName. + * @member {string} secretName + * @memberof agent.CreateSecretRequestMessage + * @instance + */ + CreateSecretRequestMessage.prototype.secretName = ""; + + /** + * CreateSecretRequestMessage secretPath. + * @member {string} secretPath + * @memberof agent.CreateSecretRequestMessage + * @instance + */ + CreateSecretRequestMessage.prototype.secretPath = ""; + + /** + * CreateSecretRequestMessage secretContent. + * @member {Uint8Array} secretContent + * @memberof agent.CreateSecretRequestMessage + * @instance + */ + CreateSecretRequestMessage.prototype.secretContent = $util.newBuffer([]); + + /** + * Creates a new CreateSecretRequestMessage instance using the specified properties. + * @function create + * @memberof agent.CreateSecretRequestMessage + * @static + * @param {agent.ICreateSecretRequestMessage=} [properties] Properties to set + * @returns {agent.CreateSecretRequestMessage} CreateSecretRequestMessage instance + */ + CreateSecretRequestMessage.create = function create(properties) { + return new CreateSecretRequestMessage(properties); + }; + + /** + * Encodes the specified CreateSecretRequestMessage message. Does not implicitly {@link agent.CreateSecretRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.CreateSecretRequestMessage + * @static + * @param {agent.ICreateSecretRequestMessage} m CreateSecretRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateSecretRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.vaultName != null && Object.hasOwnProperty.call(m, "vaultName")) + w.uint32(10).string(m.vaultName); + if (m.secretName != null && Object.hasOwnProperty.call(m, "secretName")) + w.uint32(18).string(m.secretName); + if (m.secretPath != null && Object.hasOwnProperty.call(m, "secretPath")) + w.uint32(26).string(m.secretPath); + if (m.secretContent != null && Object.hasOwnProperty.call(m, "secretContent")) + w.uint32(34).bytes(m.secretContent); + return w; + }; + + /** + * Decodes a CreateSecretRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.CreateSecretRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.CreateSecretRequestMessage} CreateSecretRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateSecretRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.CreateSecretRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.vaultName = r.string(); + break; + case 2: + m.secretName = r.string(); + break; + case 3: + m.secretPath = r.string(); + break; + case 4: + m.secretContent = r.bytes(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return CreateSecretRequestMessage; + })(); + + agent.CreateSecretResponseMessage = (function() { + + /** + * Properties of a CreateSecretResponseMessage. + * @memberof agent + * @interface ICreateSecretResponseMessage + * @property {boolean|null} [successful] CreateSecretResponseMessage successful + */ + + /** + * Constructs a new CreateSecretResponseMessage. + * @memberof agent + * @classdesc Represents a CreateSecretResponseMessage. + * @implements ICreateSecretResponseMessage + * @constructor + * @param {agent.ICreateSecretResponseMessage=} [p] Properties to set + */ + function CreateSecretResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * CreateSecretResponseMessage successful. + * @member {boolean} successful + * @memberof agent.CreateSecretResponseMessage + * @instance + */ + CreateSecretResponseMessage.prototype.successful = false; + + /** + * Creates a new CreateSecretResponseMessage instance using the specified properties. + * @function create + * @memberof agent.CreateSecretResponseMessage + * @static + * @param {agent.ICreateSecretResponseMessage=} [properties] Properties to set + * @returns {agent.CreateSecretResponseMessage} CreateSecretResponseMessage instance + */ + CreateSecretResponseMessage.create = function create(properties) { + return new CreateSecretResponseMessage(properties); + }; + + /** + * Encodes the specified CreateSecretResponseMessage message. Does not implicitly {@link agent.CreateSecretResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.CreateSecretResponseMessage + * @static + * @param {agent.ICreateSecretResponseMessage} m CreateSecretResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateSecretResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.successful != null && Object.hasOwnProperty.call(m, "successful")) + w.uint32(8).bool(m.successful); + return w; + }; + + /** + * Decodes a CreateSecretResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.CreateSecretResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.CreateSecretResponseMessage} CreateSecretResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateSecretResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.CreateSecretResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.successful = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return CreateSecretResponseMessage; + })(); + + agent.DestroySecretRequestMessage = (function() { + + /** + * Properties of a DestroySecretRequestMessage. + * @memberof agent + * @interface IDestroySecretRequestMessage + * @property {string|null} [vaultName] DestroySecretRequestMessage vaultName + * @property {string|null} [secretName] DestroySecretRequestMessage secretName + */ + + /** + * Constructs a new DestroySecretRequestMessage. + * @memberof agent + * @classdesc Represents a DestroySecretRequestMessage. + * @implements IDestroySecretRequestMessage + * @constructor + * @param {agent.IDestroySecretRequestMessage=} [p] Properties to set + */ + function DestroySecretRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * DestroySecretRequestMessage vaultName. + * @member {string} vaultName + * @memberof agent.DestroySecretRequestMessage + * @instance + */ + DestroySecretRequestMessage.prototype.vaultName = ""; + + /** + * DestroySecretRequestMessage secretName. + * @member {string} secretName + * @memberof agent.DestroySecretRequestMessage + * @instance + */ + DestroySecretRequestMessage.prototype.secretName = ""; + + /** + * Creates a new DestroySecretRequestMessage instance using the specified properties. + * @function create + * @memberof agent.DestroySecretRequestMessage + * @static + * @param {agent.IDestroySecretRequestMessage=} [properties] Properties to set + * @returns {agent.DestroySecretRequestMessage} DestroySecretRequestMessage instance + */ + DestroySecretRequestMessage.create = function create(properties) { + return new DestroySecretRequestMessage(properties); + }; + + /** + * Encodes the specified DestroySecretRequestMessage message. Does not implicitly {@link agent.DestroySecretRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.DestroySecretRequestMessage + * @static + * @param {agent.IDestroySecretRequestMessage} m DestroySecretRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DestroySecretRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.vaultName != null && Object.hasOwnProperty.call(m, "vaultName")) + w.uint32(10).string(m.vaultName); + if (m.secretName != null && Object.hasOwnProperty.call(m, "secretName")) + w.uint32(18).string(m.secretName); + return w; + }; + + /** + * Decodes a DestroySecretRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.DestroySecretRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.DestroySecretRequestMessage} DestroySecretRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DestroySecretRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroySecretRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.vaultName = r.string(); + break; + case 2: + m.secretName = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return DestroySecretRequestMessage; + })(); + + agent.DestroySecretResponseMessage = (function() { + + /** + * Properties of a DestroySecretResponseMessage. + * @memberof agent + * @interface IDestroySecretResponseMessage + * @property {boolean|null} [successful] DestroySecretResponseMessage successful + */ + + /** + * Constructs a new DestroySecretResponseMessage. + * @memberof agent + * @classdesc Represents a DestroySecretResponseMessage. + * @implements IDestroySecretResponseMessage + * @constructor + * @param {agent.IDestroySecretResponseMessage=} [p] Properties to set + */ + function DestroySecretResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * DestroySecretResponseMessage successful. + * @member {boolean} successful + * @memberof agent.DestroySecretResponseMessage + * @instance + */ + DestroySecretResponseMessage.prototype.successful = false; + + /** + * Creates a new DestroySecretResponseMessage instance using the specified properties. + * @function create + * @memberof agent.DestroySecretResponseMessage + * @static + * @param {agent.IDestroySecretResponseMessage=} [properties] Properties to set + * @returns {agent.DestroySecretResponseMessage} DestroySecretResponseMessage instance + */ + DestroySecretResponseMessage.create = function create(properties) { + return new DestroySecretResponseMessage(properties); + }; + + /** + * Encodes the specified DestroySecretResponseMessage message. Does not implicitly {@link agent.DestroySecretResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.DestroySecretResponseMessage + * @static + * @param {agent.IDestroySecretResponseMessage} m DestroySecretResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DestroySecretResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.successful != null && Object.hasOwnProperty.call(m, "successful")) + w.uint32(8).bool(m.successful); + return w; + }; + + /** + * Decodes a DestroySecretResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.DestroySecretResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.DestroySecretResponseMessage} DestroySecretResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DestroySecretResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroySecretResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.successful = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return DestroySecretResponseMessage; + })(); + + agent.GetSecretRequestMessage = (function() { + + /** + * Properties of a GetSecretRequestMessage. + * @memberof agent + * @interface IGetSecretRequestMessage + * @property {string|null} [vaultName] GetSecretRequestMessage vaultName + * @property {string|null} [secretName] GetSecretRequestMessage secretName + */ + + /** + * Constructs a new GetSecretRequestMessage. + * @memberof agent + * @classdesc Represents a GetSecretRequestMessage. + * @implements IGetSecretRequestMessage + * @constructor + * @param {agent.IGetSecretRequestMessage=} [p] Properties to set + */ + function GetSecretRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * GetSecretRequestMessage vaultName. + * @member {string} vaultName + * @memberof agent.GetSecretRequestMessage + * @instance + */ + GetSecretRequestMessage.prototype.vaultName = ""; + + /** + * GetSecretRequestMessage secretName. + * @member {string} secretName + * @memberof agent.GetSecretRequestMessage + * @instance + */ + GetSecretRequestMessage.prototype.secretName = ""; + + /** + * Creates a new GetSecretRequestMessage instance using the specified properties. + * @function create + * @memberof agent.GetSecretRequestMessage + * @static + * @param {agent.IGetSecretRequestMessage=} [properties] Properties to set + * @returns {agent.GetSecretRequestMessage} GetSecretRequestMessage instance + */ + GetSecretRequestMessage.create = function create(properties) { + return new GetSecretRequestMessage(properties); + }; + + /** + * Encodes the specified GetSecretRequestMessage message. Does not implicitly {@link agent.GetSecretRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.GetSecretRequestMessage + * @static + * @param {agent.IGetSecretRequestMessage} m GetSecretRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetSecretRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.vaultName != null && Object.hasOwnProperty.call(m, "vaultName")) + w.uint32(10).string(m.vaultName); + if (m.secretName != null && Object.hasOwnProperty.call(m, "secretName")) + w.uint32(18).string(m.secretName); + return w; + }; + + /** + * Decodes a GetSecretRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.GetSecretRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.GetSecretRequestMessage} GetSecretRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetSecretRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.GetSecretRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.vaultName = r.string(); + break; + case 2: + m.secretName = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return GetSecretRequestMessage; + })(); + + agent.GetSecretResponseMessage = (function() { + + /** + * Properties of a GetSecretResponseMessage. + * @memberof agent + * @interface IGetSecretResponseMessage + * @property {Uint8Array|null} [secret] GetSecretResponseMessage secret + */ + + /** + * Constructs a new GetSecretResponseMessage. + * @memberof agent + * @classdesc Represents a GetSecretResponseMessage. + * @implements IGetSecretResponseMessage + * @constructor + * @param {agent.IGetSecretResponseMessage=} [p] Properties to set + */ + function GetSecretResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * GetSecretResponseMessage secret. + * @member {Uint8Array} secret + * @memberof agent.GetSecretResponseMessage + * @instance + */ + GetSecretResponseMessage.prototype.secret = $util.newBuffer([]); + + /** + * Creates a new GetSecretResponseMessage instance using the specified properties. + * @function create + * @memberof agent.GetSecretResponseMessage + * @static + * @param {agent.IGetSecretResponseMessage=} [properties] Properties to set + * @returns {agent.GetSecretResponseMessage} GetSecretResponseMessage instance + */ + GetSecretResponseMessage.create = function create(properties) { + return new GetSecretResponseMessage(properties); + }; + + /** + * Encodes the specified GetSecretResponseMessage message. Does not implicitly {@link agent.GetSecretResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.GetSecretResponseMessage + * @static + * @param {agent.IGetSecretResponseMessage} m GetSecretResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetSecretResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.secret != null && Object.hasOwnProperty.call(m, "secret")) + w.uint32(10).bytes(m.secret); + return w; + }; + + /** + * Decodes a GetSecretResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.GetSecretResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.GetSecretResponseMessage} GetSecretResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetSecretResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.GetSecretResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.secret = r.bytes(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return GetSecretResponseMessage; + })(); + + agent.DeriveKeyRequestMessage = (function() { + + /** + * Properties of a DeriveKeyRequestMessage. + * @memberof agent + * @interface IDeriveKeyRequestMessage + * @property {string|null} [vaultName] DeriveKeyRequestMessage vaultName + * @property {string|null} [keyName] DeriveKeyRequestMessage keyName + * @property {string|null} [passphrase] DeriveKeyRequestMessage passphrase + */ + + /** + * Constructs a new DeriveKeyRequestMessage. + * @memberof agent + * @classdesc Represents a DeriveKeyRequestMessage. + * @implements IDeriveKeyRequestMessage + * @constructor + * @param {agent.IDeriveKeyRequestMessage=} [p] Properties to set + */ + function DeriveKeyRequestMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * DeriveKeyRequestMessage vaultName. + * @member {string} vaultName + * @memberof agent.DeriveKeyRequestMessage + * @instance + */ + DeriveKeyRequestMessage.prototype.vaultName = ""; + + /** + * DeriveKeyRequestMessage keyName. + * @member {string} keyName + * @memberof agent.DeriveKeyRequestMessage + * @instance + */ + DeriveKeyRequestMessage.prototype.keyName = ""; + + /** + * DeriveKeyRequestMessage passphrase. + * @member {string} passphrase + * @memberof agent.DeriveKeyRequestMessage + * @instance + */ + DeriveKeyRequestMessage.prototype.passphrase = ""; + + /** + * Creates a new DeriveKeyRequestMessage instance using the specified properties. + * @function create + * @memberof agent.DeriveKeyRequestMessage + * @static + * @param {agent.IDeriveKeyRequestMessage=} [properties] Properties to set + * @returns {agent.DeriveKeyRequestMessage} DeriveKeyRequestMessage instance + */ + DeriveKeyRequestMessage.create = function create(properties) { + return new DeriveKeyRequestMessage(properties); + }; + + /** + * Encodes the specified DeriveKeyRequestMessage message. Does not implicitly {@link agent.DeriveKeyRequestMessage.verify|verify} messages. + * @function encode + * @memberof agent.DeriveKeyRequestMessage + * @static + * @param {agent.IDeriveKeyRequestMessage} m DeriveKeyRequestMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeriveKeyRequestMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.vaultName != null && Object.hasOwnProperty.call(m, "vaultName")) + w.uint32(10).string(m.vaultName); + if (m.keyName != null && Object.hasOwnProperty.call(m, "keyName")) + w.uint32(18).string(m.keyName); + if (m.passphrase != null && Object.hasOwnProperty.call(m, "passphrase")) + w.uint32(26).string(m.passphrase); + return w; + }; + + /** + * Decodes a DeriveKeyRequestMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.DeriveKeyRequestMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.DeriveKeyRequestMessage} DeriveKeyRequestMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeriveKeyRequestMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DeriveKeyRequestMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.vaultName = r.string(); + break; + case 2: + m.keyName = r.string(); + break; + case 3: + m.passphrase = r.string(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return DeriveKeyRequestMessage; + })(); + + agent.DeriveKeyResponseMessage = (function() { + + /** + * Properties of a DeriveKeyResponseMessage. + * @memberof agent + * @interface IDeriveKeyResponseMessage + * @property {boolean|null} [successful] DeriveKeyResponseMessage successful + */ + + /** + * Constructs a new DeriveKeyResponseMessage. + * @memberof agent + * @classdesc Represents a DeriveKeyResponseMessage. + * @implements IDeriveKeyResponseMessage + * @constructor + * @param {agent.IDeriveKeyResponseMessage=} [p] Properties to set + */ + function DeriveKeyResponseMessage(p) { + if (p) + for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) + if (p[ks[i]] != null) + this[ks[i]] = p[ks[i]]; + } + + /** + * DeriveKeyResponseMessage successful. + * @member {boolean} successful + * @memberof agent.DeriveKeyResponseMessage + * @instance + */ + DeriveKeyResponseMessage.prototype.successful = false; + + /** + * Creates a new DeriveKeyResponseMessage instance using the specified properties. + * @function create + * @memberof agent.DeriveKeyResponseMessage + * @static + * @param {agent.IDeriveKeyResponseMessage=} [properties] Properties to set + * @returns {agent.DeriveKeyResponseMessage} DeriveKeyResponseMessage instance + */ + DeriveKeyResponseMessage.create = function create(properties) { + return new DeriveKeyResponseMessage(properties); + }; + + /** + * Encodes the specified DeriveKeyResponseMessage message. Does not implicitly {@link agent.DeriveKeyResponseMessage.verify|verify} messages. + * @function encode + * @memberof agent.DeriveKeyResponseMessage + * @static + * @param {agent.IDeriveKeyResponseMessage} m DeriveKeyResponseMessage message or plain object to encode + * @param {$protobuf.Writer} [w] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeriveKeyResponseMessage.encode = function encode(m, w) { + if (!w) + w = $Writer.create(); + if (m.successful != null && Object.hasOwnProperty.call(m, "successful")) + w.uint32(8).bool(m.successful); + return w; + }; + + /** + * Decodes a DeriveKeyResponseMessage message from the specified reader or buffer. + * @function decode + * @memberof agent.DeriveKeyResponseMessage + * @static + * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from + * @param {number} [l] Message length if known beforehand + * @returns {agent.DeriveKeyResponseMessage} DeriveKeyResponseMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeriveKeyResponseMessage.decode = function decode(r, l) { + if (!(r instanceof $Reader)) + r = $Reader.create(r); + var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DeriveKeyResponseMessage(); + while (r.pos < c) { + var t = r.uint32(); + switch (t >>> 3) { + case 1: + m.successful = r.bool(); + break; + default: + r.skipType(t & 7); + break; + } + } + return m; + }; + + return DeriveKeyResponseMessage; + })(); + + return agent; +})(); + +module.exports = $root; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + +module.exports = require("protobufjs/minimal"); + +/***/ }) +/******/ ]); +}); //# sourceMappingURL=browser-client.js.map \ No newline at end of file diff --git a/dist/lib/browser-client.js.map b/dist/lib/browser-client.js.map index 1be8602709..fdc0124a64 100644 --- a/dist/lib/browser-client.js.map +++ b/dist/lib/browser-client.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://browser-client/webpack/universalModuleDefinition","webpack://browser-client/webpack/bootstrap","webpack://browser-client/./src/lib/agent/PolykeyClient.ts","webpack://browser-client/./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack://browser-client/(webpack)/buildin/global.js","webpack://browser-client/external \"base64-js\"","webpack://browser-client/external \"ieee754\"","webpack://browser-client/external \"isarray\"","webpack://browser-client/./proto/js/Agent.js","webpack://browser-client/external \"protobufjs/minimal\""],"names":["root","factory","exports","module","define","amd","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Agent_1","AgentMessage","CreateSecretRequestMessage","CreateSecretResponseMessage","DeriveKeyRequestMessage","DeriveKeyResponseMessage","DestroySecretRequestMessage","DestroySecretResponseMessage","DestroyVaultRequestMessage","DestroyVaultResponseMessage","ErrorMessage","GetSecretRequestMessage","GetSecretResponseMessage","ListNodesRequestMessage","ListNodesResponseMessage","ListSecretsRequestMessage","ListSecretsResponseMessage","ListVaultsRequestMessage","ListVaultsResponseMessage","NewNodeRequestMessage","NewNodeResponseMessage","NewVaultRequestMessage","NewVaultResponseMessage","RegisterNodeRequestMessage","RegisterNodeResponseMessage","SignFileRequestMessage","SignFileResponseMessage","Type","VerifyFileRequestMessage","VerifyFileResponseMessage","agent","default","getStream","request","stream","responseList","Promise","resolve","reject","on","data","push","err","write","end","type","nodePath","agentMessage","encode","isResponse","subMessage","finish","sendRequestToAgent","agentMessageList","response","decode","ERROR","error","Error","path","passphrase","registerNodeRequest","encodedResponse","handleAgentCommunication","REGISTER_NODE","length","successful","email","nbits","newNodeRequest","NEW_NODE","unlockedOnly","LIST_NODES","undefined","nodes","keyName","DERIVE_KEY","filePath","privateKeyPath","SIGN_FILE","signaturePath","VERIFY_FILE","verified","LIST_VAULTS","vaultNames","vaultName","NEW_VAULT","DESTROY_VAULT","LIST_SECRETS","secretNames","secretName","secretPath","CREATE_SECRET","DESTROY_SECRET","GET_SECRET","secret","Buffer","from","STATUS","toString","STOP_AGENT","getAgentStatus","base64","ieee754","isArray","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","Uint8Array","__proto__","arg","encodingOrOffset","allocUnsafe","TypeError","ArrayBuffer","array","byteOffset","byteLength","fromArrayLike","fromArrayBuffer","string","encoding","isEncoding","actual","slice","fromString","obj","isBuffer","len","checked","copy","buffer","val","fromObject","assertSize","size","isView","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","start","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","b","bidirectionalIndexOf","dir","isNaN","arrayIndexOf","indexOf","lastIndexOf","arr","indexSize","arrLength","valLength","String","read","buf","readUInt16BE","foundIndex","found","j","hexWrite","offset","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","str","byteArray","charCodeAt","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","Math","min","res","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","fromCharCode","apply","decodeCodePointsArray","SlowBuffer","alloc","INSPECT_MAX_BYTES","global","foo","subarray","e","typedArraySupport","poolSize","_augment","species","configurable","fill","allocUnsafeSlow","_isBuffer","compare","a","x","y","concat","list","pos","swap16","swap32","swap64","arguments","equals","inspect","max","match","join","target","thisStart","thisEnd","thisCopy","targetCopy","includes","isFinite","toJSON","Array","_arr","ret","out","toHex","bytes","checkOffset","ext","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","pow","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","floor","writeUInt16LE","writeUInt16BE","writeUInt32LE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","set","code","INVALID_BASE64_RE","Infinity","leadSurrogate","toByteArray","trim","replace","stringtrim","base64clean","src","dst","g","Function","window","require","valuesById","values","$protobuf","$Reader","Reader","$Writer","Writer","$util","util","$root","roots","ks","keys","newBuffer","properties","w","uint32","int32","bool","skipType","emptyArray"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAQ,kBAAoBD,IAE5BD,EAAK,kBAAoBC,IAR3B,CASGK,MAAM,WACT,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY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,IAAI1U,EAAyB0U,IAYxC1U,EAAyB2C,OAAS,SAAgB5E,EAAG4W,GAKjD,OAJKA,IACDA,EAAIV,EAAQhV,UACI,MAAhBlB,EAAE8F,YAAsBxF,OAAOmB,eAAe1B,KAAKC,EAAG,eACtD4W,EAAEC,OAAO,GAAGE,KAAK/W,EAAE8F,YAChB8Q,GAcX3U,EAAyBkD,OAAS,SAAgBzE,EAAGb,GAC3Ca,aAAasV,IACftV,EAAIsV,EAAQ9U,OAAOR,IAEvB,IADA,IAAIT,OAAUoG,IAANxG,EAAkBa,EAAEoJ,IAAMpJ,EAAEsP,IAAMnQ,EAAGG,EAAI,IAAIsW,EAAM5S,MAAMzB,yBAC1DvB,EAAEsP,IAAM/P,GAAG,CACd,IAAIa,EAAIJ,EAAEmW,SACV,OAAQ/V,IAAM,GACd,KAAK,EACDd,EAAE8F,WAAapF,EAAEqW,OACjB,MACJ,QACIrW,EAAEsW,SAAa,EAAJlW,IAInB,OAAOd,GAGJiC,EA1FsB,GA6F1ByB,GAGXrE,EAAOD,QAAUkX,G,cCh0FjBjX,EAAOD,QAAUwW,QAAQ","file":"browser-client.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"browser-client\"] = factory();\n\telse\n\t\troot[\"browser-client\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Agent_1 = require(\"../../../proto/js/Agent\");\nconst { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage } = Agent_1.agent;\nclass PolykeyClient {\n constructor(getStream) {\n this.getStream = getStream;\n }\n async sendRequestToAgent(request) {\n const stream = this.getStream();\n const responseList = await new Promise((resolve, reject) => {\n try {\n const responseList = [];\n stream.on('data', (data) => {\n responseList.push(data);\n });\n stream.on('error', (err) => {\n reject(err);\n });\n stream.on('end', () => {\n resolve(responseList);\n });\n stream.write(request);\n }\n catch (err) {\n reject(err);\n }\n });\n stream.end();\n return responseList;\n }\n async handleAgentCommunication(type, nodePath, request) {\n // Encode message and sent\n const agentMessage = AgentMessage.encode({ type: type, isResponse: false, nodePath: nodePath, subMessage: request }).finish();\n const responseList = await this.sendRequestToAgent(agentMessage);\n const agentMessageList = [];\n for (const response of responseList) {\n const { subMessage, type } = AgentMessage.decode(response);\n if (type == Type.ERROR) {\n const { error } = ErrorMessage.decode(subMessage);\n const reason = new Error(error);\n throw reason;\n }\n else {\n agentMessageList.push(AgentMessage.decode(response));\n }\n }\n return agentMessageList;\n }\n async registerNode(path, passphrase) {\n const registerNodeRequest = RegisterNodeRequestMessage.encode({ passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.REGISTER_NODE, path, registerNodeRequest);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = RegisterNodeResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async newNode(path, name, email, passphrase, nbits) {\n const newNodeRequest = NewNodeRequestMessage.encode({ name, email, passphrase, nbits }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.NEW_NODE, path, newNodeRequest);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = NewNodeResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async listNodes(unlockedOnly = true) {\n const newNodeRequest = ListNodesRequestMessage.encode({ unlockedOnly }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_NODES, undefined, newNodeRequest);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { nodes } = ListNodesResponseMessage.decode(encodedResponse[0].subMessage);\n return nodes;\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async deriveKey(nodePath, keyName, passphrase) {\n const request = DeriveKeyRequestMessage.encode({ keyName, passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DERIVE_KEY, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = DeriveKeyResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async signFile(nodePath, filePath, privateKeyPath, passphrase) {\n const request = SignFileRequestMessage.encode({ filePath, privateKeyPath, passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.SIGN_FILE, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { signaturePath } = SignFileResponseMessage.decode(encodedResponse[0].subMessage);\n return signaturePath;\n }\n async verifyFile(nodePath, filePath, signaturePath) {\n const request = VerifyFileRequestMessage.encode({ filePath, signaturePath }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.VERIFY_FILE, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { verified } = VerifyFileResponseMessage.decode(encodedResponse[0].subMessage);\n return verified;\n }\n //////////////////////\n // Vault Operations //\n //////////////////////\n async listVaults(nodePath) {\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_VAULTS, nodePath);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { vaultNames } = ListVaultsResponseMessage.decode(encodedResponse[0].subMessage);\n return vaultNames;\n }\n async newVault(nodePath, vaultName) {\n const request = NewVaultRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.NEW_VAULT, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = NewVaultResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async destroyVault(nodePath, vaultName) {\n const request = DestroyVaultRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_VAULT, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = DestroyVaultResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n ///////////////////////\n // Secret Operations //\n ///////////////////////\n async listSecrets(nodePath, vaultName) {\n const request = ListSecretsRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_SECRETS, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { secretNames } = ListSecretsResponseMessage.decode(encodedResponse[0].subMessage);\n return secretNames;\n }\n async createSecret(nodePath, vaultName, secretName, secretPath) {\n const request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretPath }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.CREATE_SECRET, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = CreateSecretResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async destroySecret(nodePath, vaultName, secretName) {\n const request = DestroySecretRequestMessage.encode({ vaultName, secretName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_SECRET, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = DestroySecretResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async getSecret(nodePath, vaultName, secretName) {\n const request = GetSecretRequestMessage.encode({ vaultName, secretName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.GET_SECRET, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { secret } = GetSecretResponseMessage.decode(encodedResponse[0].subMessage);\n return Buffer.from(secret);\n }\n ///////////////////\n // Agent control //\n ///////////////////\n async getAgentStatus() {\n try {\n const encodedResponse = await this.handleAgentCommunication(Type.STATUS);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const status = encodedResponse[0].subMessage.toString();\n return status;\n }\n catch (err) {\n return 'stopped';\n }\n }\n async stopAgent() {\n try {\n // Tell it to start shutting and wait for response\n await this.handleAgentCommunication(Type.STOP_AGENT);\n return true;\n }\n catch (err) {\n return (await this.getAgentStatus() != 'online');\n }\n }\n}\nexports.default = PolykeyClient;\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","module.exports = require(\"base64-js\");","module.exports = require(\"ieee754\");","module.exports = require(\"isarray\");","/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/\n\"use strict\";\n\nvar $protobuf = require(\"protobufjs/minimal\");\n\n// Common aliases\nvar $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nvar $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\n$root.agent = (function() {\n\n /**\n * Namespace agent.\n * @exports agent\n * @namespace\n */\n var agent = {};\n\n /**\n * Type enum.\n * @name agent.Type\n * @enum {number}\n * @property {number} ERROR=0 ERROR value\n * @property {number} STOP_AGENT=1 STOP_AGENT value\n * @property {number} STATUS=2 STATUS value\n * @property {number} REGISTER_NODE=3 REGISTER_NODE value\n * @property {number} NEW_NODE=4 NEW_NODE value\n * @property {number} LIST_NODES=5 LIST_NODES value\n * @property {number} DERIVE_KEY=6 DERIVE_KEY value\n * @property {number} SIGN_FILE=7 SIGN_FILE value\n * @property {number} VERIFY_FILE=8 VERIFY_FILE value\n * @property {number} LIST_VAULTS=9 LIST_VAULTS value\n * @property {number} NEW_VAULT=10 NEW_VAULT value\n * @property {number} DESTROY_VAULT=11 DESTROY_VAULT value\n * @property {number} LIST_SECRETS=12 LIST_SECRETS value\n * @property {number} CREATE_SECRET=13 CREATE_SECRET value\n * @property {number} DESTROY_SECRET=14 DESTROY_SECRET value\n * @property {number} GET_SECRET=15 GET_SECRET value\n */\n agent.Type = (function() {\n var valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"ERROR\"] = 0;\n values[valuesById[1] = \"STOP_AGENT\"] = 1;\n values[valuesById[2] = \"STATUS\"] = 2;\n values[valuesById[3] = \"REGISTER_NODE\"] = 3;\n values[valuesById[4] = \"NEW_NODE\"] = 4;\n values[valuesById[5] = \"LIST_NODES\"] = 5;\n values[valuesById[6] = \"DERIVE_KEY\"] = 6;\n values[valuesById[7] = \"SIGN_FILE\"] = 7;\n values[valuesById[8] = \"VERIFY_FILE\"] = 8;\n values[valuesById[9] = \"LIST_VAULTS\"] = 9;\n values[valuesById[10] = \"NEW_VAULT\"] = 10;\n values[valuesById[11] = \"DESTROY_VAULT\"] = 11;\n values[valuesById[12] = \"LIST_SECRETS\"] = 12;\n values[valuesById[13] = \"CREATE_SECRET\"] = 13;\n values[valuesById[14] = \"DESTROY_SECRET\"] = 14;\n values[valuesById[15] = \"GET_SECRET\"] = 15;\n return values;\n })();\n\n agent.AgentMessage = (function() {\n\n /**\n * Properties of an AgentMessage.\n * @memberof agent\n * @interface IAgentMessage\n * @property {agent.Type|null} [type] AgentMessage type\n * @property {boolean|null} [isResponse] AgentMessage isResponse\n * @property {string|null} [nodePath] AgentMessage nodePath\n * @property {Uint8Array|null} [subMessage] AgentMessage subMessage\n */\n\n /**\n * Constructs a new AgentMessage.\n * @memberof agent\n * @classdesc Represents an AgentMessage.\n * @implements IAgentMessage\n * @constructor\n * @param {agent.IAgentMessage=} [p] Properties to set\n */\n function AgentMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * AgentMessage type.\n * @member {agent.Type} type\n * @memberof agent.AgentMessage\n * @instance\n */\n AgentMessage.prototype.type = 0;\n\n /**\n * AgentMessage isResponse.\n * @member {boolean} isResponse\n * @memberof agent.AgentMessage\n * @instance\n */\n AgentMessage.prototype.isResponse = false;\n\n /**\n * AgentMessage nodePath.\n * @member {string} nodePath\n * @memberof agent.AgentMessage\n * @instance\n */\n AgentMessage.prototype.nodePath = \"\";\n\n /**\n * AgentMessage subMessage.\n * @member {Uint8Array} subMessage\n * @memberof agent.AgentMessage\n * @instance\n */\n AgentMessage.prototype.subMessage = $util.newBuffer([]);\n\n /**\n * Creates a new AgentMessage instance using the specified properties.\n * @function create\n * @memberof agent.AgentMessage\n * @static\n * @param {agent.IAgentMessage=} [properties] Properties to set\n * @returns {agent.AgentMessage} AgentMessage instance\n */\n AgentMessage.create = function create(properties) {\n return new AgentMessage(properties);\n };\n\n /**\n * Encodes the specified AgentMessage message. Does not implicitly {@link agent.AgentMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.AgentMessage\n * @static\n * @param {agent.IAgentMessage} m AgentMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n AgentMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.type != null && Object.hasOwnProperty.call(m, \"type\"))\n w.uint32(8).int32(m.type);\n if (m.isResponse != null && Object.hasOwnProperty.call(m, \"isResponse\"))\n w.uint32(16).bool(m.isResponse);\n if (m.nodePath != null && Object.hasOwnProperty.call(m, \"nodePath\"))\n w.uint32(26).string(m.nodePath);\n if (m.subMessage != null && Object.hasOwnProperty.call(m, \"subMessage\"))\n w.uint32(34).bytes(m.subMessage);\n return w;\n };\n\n /**\n * Decodes an AgentMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.AgentMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.AgentMessage} AgentMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n AgentMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.AgentMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.type = r.int32();\n break;\n case 2:\n m.isResponse = r.bool();\n break;\n case 3:\n m.nodePath = r.string();\n break;\n case 4:\n m.subMessage = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return AgentMessage;\n })();\n\n agent.ErrorMessage = (function() {\n\n /**\n * Properties of an ErrorMessage.\n * @memberof agent\n * @interface IErrorMessage\n * @property {string|null} [error] ErrorMessage error\n */\n\n /**\n * Constructs a new ErrorMessage.\n * @memberof agent\n * @classdesc Represents an ErrorMessage.\n * @implements IErrorMessage\n * @constructor\n * @param {agent.IErrorMessage=} [p] Properties to set\n */\n function ErrorMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ErrorMessage error.\n * @member {string} error\n * @memberof agent.ErrorMessage\n * @instance\n */\n ErrorMessage.prototype.error = \"\";\n\n /**\n * Creates a new ErrorMessage instance using the specified properties.\n * @function create\n * @memberof agent.ErrorMessage\n * @static\n * @param {agent.IErrorMessage=} [properties] Properties to set\n * @returns {agent.ErrorMessage} ErrorMessage instance\n */\n ErrorMessage.create = function create(properties) {\n return new ErrorMessage(properties);\n };\n\n /**\n * Encodes the specified ErrorMessage message. Does not implicitly {@link agent.ErrorMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ErrorMessage\n * @static\n * @param {agent.IErrorMessage} m ErrorMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ErrorMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.error != null && Object.hasOwnProperty.call(m, \"error\"))\n w.uint32(10).string(m.error);\n return w;\n };\n\n /**\n * Decodes an ErrorMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ErrorMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ErrorMessage} ErrorMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ErrorMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ErrorMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.error = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ErrorMessage;\n })();\n\n agent.RegisterNodeRequestMessage = (function() {\n\n /**\n * Properties of a RegisterNodeRequestMessage.\n * @memberof agent\n * @interface IRegisterNodeRequestMessage\n * @property {string|null} [passphrase] RegisterNodeRequestMessage passphrase\n */\n\n /**\n * Constructs a new RegisterNodeRequestMessage.\n * @memberof agent\n * @classdesc Represents a RegisterNodeRequestMessage.\n * @implements IRegisterNodeRequestMessage\n * @constructor\n * @param {agent.IRegisterNodeRequestMessage=} [p] Properties to set\n */\n function RegisterNodeRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * RegisterNodeRequestMessage passphrase.\n * @member {string} passphrase\n * @memberof agent.RegisterNodeRequestMessage\n * @instance\n */\n RegisterNodeRequestMessage.prototype.passphrase = \"\";\n\n /**\n * Creates a new RegisterNodeRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.RegisterNodeRequestMessage\n * @static\n * @param {agent.IRegisterNodeRequestMessage=} [properties] Properties to set\n * @returns {agent.RegisterNodeRequestMessage} RegisterNodeRequestMessage instance\n */\n RegisterNodeRequestMessage.create = function create(properties) {\n return new RegisterNodeRequestMessage(properties);\n };\n\n /**\n * Encodes the specified RegisterNodeRequestMessage message. Does not implicitly {@link agent.RegisterNodeRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.RegisterNodeRequestMessage\n * @static\n * @param {agent.IRegisterNodeRequestMessage} m RegisterNodeRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n RegisterNodeRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.passphrase != null && Object.hasOwnProperty.call(m, \"passphrase\"))\n w.uint32(10).string(m.passphrase);\n return w;\n };\n\n /**\n * Decodes a RegisterNodeRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.RegisterNodeRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.RegisterNodeRequestMessage} RegisterNodeRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n RegisterNodeRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.RegisterNodeRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.passphrase = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return RegisterNodeRequestMessage;\n })();\n\n agent.RegisterNodeResponseMessage = (function() {\n\n /**\n * Properties of a RegisterNodeResponseMessage.\n * @memberof agent\n * @interface IRegisterNodeResponseMessage\n * @property {boolean|null} [successful] RegisterNodeResponseMessage successful\n */\n\n /**\n * Constructs a new RegisterNodeResponseMessage.\n * @memberof agent\n * @classdesc Represents a RegisterNodeResponseMessage.\n * @implements IRegisterNodeResponseMessage\n * @constructor\n * @param {agent.IRegisterNodeResponseMessage=} [p] Properties to set\n */\n function RegisterNodeResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * RegisterNodeResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.RegisterNodeResponseMessage\n * @instance\n */\n RegisterNodeResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new RegisterNodeResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.RegisterNodeResponseMessage\n * @static\n * @param {agent.IRegisterNodeResponseMessage=} [properties] Properties to set\n * @returns {agent.RegisterNodeResponseMessage} RegisterNodeResponseMessage instance\n */\n RegisterNodeResponseMessage.create = function create(properties) {\n return new RegisterNodeResponseMessage(properties);\n };\n\n /**\n * Encodes the specified RegisterNodeResponseMessage message. Does not implicitly {@link agent.RegisterNodeResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.RegisterNodeResponseMessage\n * @static\n * @param {agent.IRegisterNodeResponseMessage} m RegisterNodeResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n RegisterNodeResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a RegisterNodeResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.RegisterNodeResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.RegisterNodeResponseMessage} RegisterNodeResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n RegisterNodeResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.RegisterNodeResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return RegisterNodeResponseMessage;\n })();\n\n agent.NewNodeRequestMessage = (function() {\n\n /**\n * Properties of a NewNodeRequestMessage.\n * @memberof agent\n * @interface INewNodeRequestMessage\n * @property {string|null} [name] NewNodeRequestMessage name\n * @property {string|null} [email] NewNodeRequestMessage email\n * @property {string|null} [passphrase] NewNodeRequestMessage passphrase\n * @property {number|null} [nbits] NewNodeRequestMessage nbits\n */\n\n /**\n * Constructs a new NewNodeRequestMessage.\n * @memberof agent\n * @classdesc Represents a NewNodeRequestMessage.\n * @implements INewNodeRequestMessage\n * @constructor\n * @param {agent.INewNodeRequestMessage=} [p] Properties to set\n */\n function NewNodeRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * NewNodeRequestMessage name.\n * @member {string} name\n * @memberof agent.NewNodeRequestMessage\n * @instance\n */\n NewNodeRequestMessage.prototype.name = \"\";\n\n /**\n * NewNodeRequestMessage email.\n * @member {string} email\n * @memberof agent.NewNodeRequestMessage\n * @instance\n */\n NewNodeRequestMessage.prototype.email = \"\";\n\n /**\n * NewNodeRequestMessage passphrase.\n * @member {string} passphrase\n * @memberof agent.NewNodeRequestMessage\n * @instance\n */\n NewNodeRequestMessage.prototype.passphrase = \"\";\n\n /**\n * NewNodeRequestMessage nbits.\n * @member {number} nbits\n * @memberof agent.NewNodeRequestMessage\n * @instance\n */\n NewNodeRequestMessage.prototype.nbits = 0;\n\n /**\n * Creates a new NewNodeRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.NewNodeRequestMessage\n * @static\n * @param {agent.INewNodeRequestMessage=} [properties] Properties to set\n * @returns {agent.NewNodeRequestMessage} NewNodeRequestMessage instance\n */\n NewNodeRequestMessage.create = function create(properties) {\n return new NewNodeRequestMessage(properties);\n };\n\n /**\n * Encodes the specified NewNodeRequestMessage message. Does not implicitly {@link agent.NewNodeRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.NewNodeRequestMessage\n * @static\n * @param {agent.INewNodeRequestMessage} m NewNodeRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n NewNodeRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.name != null && Object.hasOwnProperty.call(m, \"name\"))\n w.uint32(10).string(m.name);\n if (m.email != null && Object.hasOwnProperty.call(m, \"email\"))\n w.uint32(18).string(m.email);\n if (m.passphrase != null && Object.hasOwnProperty.call(m, \"passphrase\"))\n w.uint32(26).string(m.passphrase);\n if (m.nbits != null && Object.hasOwnProperty.call(m, \"nbits\"))\n w.uint32(32).int32(m.nbits);\n return w;\n };\n\n /**\n * Decodes a NewNodeRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.NewNodeRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.NewNodeRequestMessage} NewNodeRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n NewNodeRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewNodeRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.name = r.string();\n break;\n case 2:\n m.email = r.string();\n break;\n case 3:\n m.passphrase = r.string();\n break;\n case 4:\n m.nbits = r.int32();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return NewNodeRequestMessage;\n })();\n\n agent.NewNodeResponseMessage = (function() {\n\n /**\n * Properties of a NewNodeResponseMessage.\n * @memberof agent\n * @interface INewNodeResponseMessage\n * @property {boolean|null} [successful] NewNodeResponseMessage successful\n */\n\n /**\n * Constructs a new NewNodeResponseMessage.\n * @memberof agent\n * @classdesc Represents a NewNodeResponseMessage.\n * @implements INewNodeResponseMessage\n * @constructor\n * @param {agent.INewNodeResponseMessage=} [p] Properties to set\n */\n function NewNodeResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * NewNodeResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.NewNodeResponseMessage\n * @instance\n */\n NewNodeResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new NewNodeResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.NewNodeResponseMessage\n * @static\n * @param {agent.INewNodeResponseMessage=} [properties] Properties to set\n * @returns {agent.NewNodeResponseMessage} NewNodeResponseMessage instance\n */\n NewNodeResponseMessage.create = function create(properties) {\n return new NewNodeResponseMessage(properties);\n };\n\n /**\n * Encodes the specified NewNodeResponseMessage message. Does not implicitly {@link agent.NewNodeResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.NewNodeResponseMessage\n * @static\n * @param {agent.INewNodeResponseMessage} m NewNodeResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n NewNodeResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a NewNodeResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.NewNodeResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.NewNodeResponseMessage} NewNodeResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n NewNodeResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewNodeResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return NewNodeResponseMessage;\n })();\n\n agent.ListNodesRequestMessage = (function() {\n\n /**\n * Properties of a ListNodesRequestMessage.\n * @memberof agent\n * @interface IListNodesRequestMessage\n * @property {boolean|null} [unlockedOnly] ListNodesRequestMessage unlockedOnly\n */\n\n /**\n * Constructs a new ListNodesRequestMessage.\n * @memberof agent\n * @classdesc Represents a ListNodesRequestMessage.\n * @implements IListNodesRequestMessage\n * @constructor\n * @param {agent.IListNodesRequestMessage=} [p] Properties to set\n */\n function ListNodesRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListNodesRequestMessage unlockedOnly.\n * @member {boolean} unlockedOnly\n * @memberof agent.ListNodesRequestMessage\n * @instance\n */\n ListNodesRequestMessage.prototype.unlockedOnly = false;\n\n /**\n * Creates a new ListNodesRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListNodesRequestMessage\n * @static\n * @param {agent.IListNodesRequestMessage=} [properties] Properties to set\n * @returns {agent.ListNodesRequestMessage} ListNodesRequestMessage instance\n */\n ListNodesRequestMessage.create = function create(properties) {\n return new ListNodesRequestMessage(properties);\n };\n\n /**\n * Encodes the specified ListNodesRequestMessage message. Does not implicitly {@link agent.ListNodesRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListNodesRequestMessage\n * @static\n * @param {agent.IListNodesRequestMessage} m ListNodesRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListNodesRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.unlockedOnly != null && Object.hasOwnProperty.call(m, \"unlockedOnly\"))\n w.uint32(8).bool(m.unlockedOnly);\n return w;\n };\n\n /**\n * Decodes a ListNodesRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListNodesRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListNodesRequestMessage} ListNodesRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListNodesRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListNodesRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.unlockedOnly = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListNodesRequestMessage;\n })();\n\n agent.ListNodesResponseMessage = (function() {\n\n /**\n * Properties of a ListNodesResponseMessage.\n * @memberof agent\n * @interface IListNodesResponseMessage\n * @property {Array.|null} [nodes] ListNodesResponseMessage nodes\n */\n\n /**\n * Constructs a new ListNodesResponseMessage.\n * @memberof agent\n * @classdesc Represents a ListNodesResponseMessage.\n * @implements IListNodesResponseMessage\n * @constructor\n * @param {agent.IListNodesResponseMessage=} [p] Properties to set\n */\n function ListNodesResponseMessage(p) {\n this.nodes = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListNodesResponseMessage nodes.\n * @member {Array.} nodes\n * @memberof agent.ListNodesResponseMessage\n * @instance\n */\n ListNodesResponseMessage.prototype.nodes = $util.emptyArray;\n\n /**\n * Creates a new ListNodesResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListNodesResponseMessage\n * @static\n * @param {agent.IListNodesResponseMessage=} [properties] Properties to set\n * @returns {agent.ListNodesResponseMessage} ListNodesResponseMessage instance\n */\n ListNodesResponseMessage.create = function create(properties) {\n return new ListNodesResponseMessage(properties);\n };\n\n /**\n * Encodes the specified ListNodesResponseMessage message. Does not implicitly {@link agent.ListNodesResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListNodesResponseMessage\n * @static\n * @param {agent.IListNodesResponseMessage} m ListNodesResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListNodesResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.nodes != null && m.nodes.length) {\n for (var i = 0; i < m.nodes.length; ++i)\n w.uint32(10).string(m.nodes[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ListNodesResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListNodesResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListNodesResponseMessage} ListNodesResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListNodesResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListNodesResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.nodes && m.nodes.length))\n m.nodes = [];\n m.nodes.push(r.string());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListNodesResponseMessage;\n })();\n\n agent.SignFileRequestMessage = (function() {\n\n /**\n * Properties of a SignFileRequestMessage.\n * @memberof agent\n * @interface ISignFileRequestMessage\n * @property {string|null} [filePath] SignFileRequestMessage filePath\n * @property {string|null} [privateKeyPath] SignFileRequestMessage privateKeyPath\n * @property {string|null} [passphrase] SignFileRequestMessage passphrase\n */\n\n /**\n * Constructs a new SignFileRequestMessage.\n * @memberof agent\n * @classdesc Represents a SignFileRequestMessage.\n * @implements ISignFileRequestMessage\n * @constructor\n * @param {agent.ISignFileRequestMessage=} [p] Properties to set\n */\n function SignFileRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * SignFileRequestMessage filePath.\n * @member {string} filePath\n * @memberof agent.SignFileRequestMessage\n * @instance\n */\n SignFileRequestMessage.prototype.filePath = \"\";\n\n /**\n * SignFileRequestMessage privateKeyPath.\n * @member {string} privateKeyPath\n * @memberof agent.SignFileRequestMessage\n * @instance\n */\n SignFileRequestMessage.prototype.privateKeyPath = \"\";\n\n /**\n * SignFileRequestMessage passphrase.\n * @member {string} passphrase\n * @memberof agent.SignFileRequestMessage\n * @instance\n */\n SignFileRequestMessage.prototype.passphrase = \"\";\n\n /**\n * Creates a new SignFileRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.SignFileRequestMessage\n * @static\n * @param {agent.ISignFileRequestMessage=} [properties] Properties to set\n * @returns {agent.SignFileRequestMessage} SignFileRequestMessage instance\n */\n SignFileRequestMessage.create = function create(properties) {\n return new SignFileRequestMessage(properties);\n };\n\n /**\n * Encodes the specified SignFileRequestMessage message. Does not implicitly {@link agent.SignFileRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.SignFileRequestMessage\n * @static\n * @param {agent.ISignFileRequestMessage} m SignFileRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n SignFileRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.filePath != null && Object.hasOwnProperty.call(m, \"filePath\"))\n w.uint32(10).string(m.filePath);\n if (m.privateKeyPath != null && Object.hasOwnProperty.call(m, \"privateKeyPath\"))\n w.uint32(18).string(m.privateKeyPath);\n if (m.passphrase != null && Object.hasOwnProperty.call(m, \"passphrase\"))\n w.uint32(26).string(m.passphrase);\n return w;\n };\n\n /**\n * Decodes a SignFileRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.SignFileRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.SignFileRequestMessage} SignFileRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n SignFileRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.SignFileRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.filePath = r.string();\n break;\n case 2:\n m.privateKeyPath = r.string();\n break;\n case 3:\n m.passphrase = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return SignFileRequestMessage;\n })();\n\n agent.SignFileResponseMessage = (function() {\n\n /**\n * Properties of a SignFileResponseMessage.\n * @memberof agent\n * @interface ISignFileResponseMessage\n * @property {string|null} [signaturePath] SignFileResponseMessage signaturePath\n */\n\n /**\n * Constructs a new SignFileResponseMessage.\n * @memberof agent\n * @classdesc Represents a SignFileResponseMessage.\n * @implements ISignFileResponseMessage\n * @constructor\n * @param {agent.ISignFileResponseMessage=} [p] Properties to set\n */\n function SignFileResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * SignFileResponseMessage signaturePath.\n * @member {string} signaturePath\n * @memberof agent.SignFileResponseMessage\n * @instance\n */\n SignFileResponseMessage.prototype.signaturePath = \"\";\n\n /**\n * Creates a new SignFileResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.SignFileResponseMessage\n * @static\n * @param {agent.ISignFileResponseMessage=} [properties] Properties to set\n * @returns {agent.SignFileResponseMessage} SignFileResponseMessage instance\n */\n SignFileResponseMessage.create = function create(properties) {\n return new SignFileResponseMessage(properties);\n };\n\n /**\n * Encodes the specified SignFileResponseMessage message. Does not implicitly {@link agent.SignFileResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.SignFileResponseMessage\n * @static\n * @param {agent.ISignFileResponseMessage} m SignFileResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n SignFileResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.signaturePath != null && Object.hasOwnProperty.call(m, \"signaturePath\"))\n w.uint32(10).string(m.signaturePath);\n return w;\n };\n\n /**\n * Decodes a SignFileResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.SignFileResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.SignFileResponseMessage} SignFileResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n SignFileResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.SignFileResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.signaturePath = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return SignFileResponseMessage;\n })();\n\n agent.VerifyFileRequestMessage = (function() {\n\n /**\n * Properties of a VerifyFileRequestMessage.\n * @memberof agent\n * @interface IVerifyFileRequestMessage\n * @property {string|null} [filePath] VerifyFileRequestMessage filePath\n * @property {string|null} [signaturePath] VerifyFileRequestMessage signaturePath\n */\n\n /**\n * Constructs a new VerifyFileRequestMessage.\n * @memberof agent\n * @classdesc Represents a VerifyFileRequestMessage.\n * @implements IVerifyFileRequestMessage\n * @constructor\n * @param {agent.IVerifyFileRequestMessage=} [p] Properties to set\n */\n function VerifyFileRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * VerifyFileRequestMessage filePath.\n * @member {string} filePath\n * @memberof agent.VerifyFileRequestMessage\n * @instance\n */\n VerifyFileRequestMessage.prototype.filePath = \"\";\n\n /**\n * VerifyFileRequestMessage signaturePath.\n * @member {string} signaturePath\n * @memberof agent.VerifyFileRequestMessage\n * @instance\n */\n VerifyFileRequestMessage.prototype.signaturePath = \"\";\n\n /**\n * Creates a new VerifyFileRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.VerifyFileRequestMessage\n * @static\n * @param {agent.IVerifyFileRequestMessage=} [properties] Properties to set\n * @returns {agent.VerifyFileRequestMessage} VerifyFileRequestMessage instance\n */\n VerifyFileRequestMessage.create = function create(properties) {\n return new VerifyFileRequestMessage(properties);\n };\n\n /**\n * Encodes the specified VerifyFileRequestMessage message. Does not implicitly {@link agent.VerifyFileRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.VerifyFileRequestMessage\n * @static\n * @param {agent.IVerifyFileRequestMessage} m VerifyFileRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n VerifyFileRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.filePath != null && Object.hasOwnProperty.call(m, \"filePath\"))\n w.uint32(10).string(m.filePath);\n if (m.signaturePath != null && Object.hasOwnProperty.call(m, \"signaturePath\"))\n w.uint32(18).string(m.signaturePath);\n return w;\n };\n\n /**\n * Decodes a VerifyFileRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.VerifyFileRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.VerifyFileRequestMessage} VerifyFileRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n VerifyFileRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.VerifyFileRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.filePath = r.string();\n break;\n case 2:\n m.signaturePath = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return VerifyFileRequestMessage;\n })();\n\n agent.VerifyFileResponseMessage = (function() {\n\n /**\n * Properties of a VerifyFileResponseMessage.\n * @memberof agent\n * @interface IVerifyFileResponseMessage\n * @property {boolean|null} [verified] VerifyFileResponseMessage verified\n */\n\n /**\n * Constructs a new VerifyFileResponseMessage.\n * @memberof agent\n * @classdesc Represents a VerifyFileResponseMessage.\n * @implements IVerifyFileResponseMessage\n * @constructor\n * @param {agent.IVerifyFileResponseMessage=} [p] Properties to set\n */\n function VerifyFileResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * VerifyFileResponseMessage verified.\n * @member {boolean} verified\n * @memberof agent.VerifyFileResponseMessage\n * @instance\n */\n VerifyFileResponseMessage.prototype.verified = false;\n\n /**\n * Creates a new VerifyFileResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.VerifyFileResponseMessage\n * @static\n * @param {agent.IVerifyFileResponseMessage=} [properties] Properties to set\n * @returns {agent.VerifyFileResponseMessage} VerifyFileResponseMessage instance\n */\n VerifyFileResponseMessage.create = function create(properties) {\n return new VerifyFileResponseMessage(properties);\n };\n\n /**\n * Encodes the specified VerifyFileResponseMessage message. Does not implicitly {@link agent.VerifyFileResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.VerifyFileResponseMessage\n * @static\n * @param {agent.IVerifyFileResponseMessage} m VerifyFileResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n VerifyFileResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.verified != null && Object.hasOwnProperty.call(m, \"verified\"))\n w.uint32(8).bool(m.verified);\n return w;\n };\n\n /**\n * Decodes a VerifyFileResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.VerifyFileResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.VerifyFileResponseMessage} VerifyFileResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n VerifyFileResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.VerifyFileResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.verified = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return VerifyFileResponseMessage;\n })();\n\n agent.ListVaultsRequestMessage = (function() {\n\n /**\n * Properties of a ListVaultsRequestMessage.\n * @memberof agent\n * @interface IListVaultsRequestMessage\n */\n\n /**\n * Constructs a new ListVaultsRequestMessage.\n * @memberof agent\n * @classdesc Represents a ListVaultsRequestMessage.\n * @implements IListVaultsRequestMessage\n * @constructor\n * @param {agent.IListVaultsRequestMessage=} [p] Properties to set\n */\n function ListVaultsRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Creates a new ListVaultsRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListVaultsRequestMessage\n * @static\n * @param {agent.IListVaultsRequestMessage=} [properties] Properties to set\n * @returns {agent.ListVaultsRequestMessage} ListVaultsRequestMessage instance\n */\n ListVaultsRequestMessage.create = function create(properties) {\n return new ListVaultsRequestMessage(properties);\n };\n\n /**\n * Encodes the specified ListVaultsRequestMessage message. Does not implicitly {@link agent.ListVaultsRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListVaultsRequestMessage\n * @static\n * @param {agent.IListVaultsRequestMessage} m ListVaultsRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListVaultsRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n return w;\n };\n\n /**\n * Decodes a ListVaultsRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListVaultsRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListVaultsRequestMessage} ListVaultsRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListVaultsRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListVaultsRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListVaultsRequestMessage;\n })();\n\n agent.ListVaultsResponseMessage = (function() {\n\n /**\n * Properties of a ListVaultsResponseMessage.\n * @memberof agent\n * @interface IListVaultsResponseMessage\n * @property {Array.|null} [vaultNames] ListVaultsResponseMessage vaultNames\n */\n\n /**\n * Constructs a new ListVaultsResponseMessage.\n * @memberof agent\n * @classdesc Represents a ListVaultsResponseMessage.\n * @implements IListVaultsResponseMessage\n * @constructor\n * @param {agent.IListVaultsResponseMessage=} [p] Properties to set\n */\n function ListVaultsResponseMessage(p) {\n this.vaultNames = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListVaultsResponseMessage vaultNames.\n * @member {Array.} vaultNames\n * @memberof agent.ListVaultsResponseMessage\n * @instance\n */\n ListVaultsResponseMessage.prototype.vaultNames = $util.emptyArray;\n\n /**\n * Creates a new ListVaultsResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListVaultsResponseMessage\n * @static\n * @param {agent.IListVaultsResponseMessage=} [properties] Properties to set\n * @returns {agent.ListVaultsResponseMessage} ListVaultsResponseMessage instance\n */\n ListVaultsResponseMessage.create = function create(properties) {\n return new ListVaultsResponseMessage(properties);\n };\n\n /**\n * Encodes the specified ListVaultsResponseMessage message. Does not implicitly {@link agent.ListVaultsResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListVaultsResponseMessage\n * @static\n * @param {agent.IListVaultsResponseMessage} m ListVaultsResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListVaultsResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultNames != null && m.vaultNames.length) {\n for (var i = 0; i < m.vaultNames.length; ++i)\n w.uint32(10).string(m.vaultNames[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ListVaultsResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListVaultsResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListVaultsResponseMessage} ListVaultsResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListVaultsResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListVaultsResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.vaultNames && m.vaultNames.length))\n m.vaultNames = [];\n m.vaultNames.push(r.string());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListVaultsResponseMessage;\n })();\n\n agent.NewVaultRequestMessage = (function() {\n\n /**\n * Properties of a NewVaultRequestMessage.\n * @memberof agent\n * @interface INewVaultRequestMessage\n * @property {string|null} [vaultName] NewVaultRequestMessage vaultName\n */\n\n /**\n * Constructs a new NewVaultRequestMessage.\n * @memberof agent\n * @classdesc Represents a NewVaultRequestMessage.\n * @implements INewVaultRequestMessage\n * @constructor\n * @param {agent.INewVaultRequestMessage=} [p] Properties to set\n */\n function NewVaultRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * NewVaultRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.NewVaultRequestMessage\n * @instance\n */\n NewVaultRequestMessage.prototype.vaultName = \"\";\n\n /**\n * Creates a new NewVaultRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.NewVaultRequestMessage\n * @static\n * @param {agent.INewVaultRequestMessage=} [properties] Properties to set\n * @returns {agent.NewVaultRequestMessage} NewVaultRequestMessage instance\n */\n NewVaultRequestMessage.create = function create(properties) {\n return new NewVaultRequestMessage(properties);\n };\n\n /**\n * Encodes the specified NewVaultRequestMessage message. Does not implicitly {@link agent.NewVaultRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.NewVaultRequestMessage\n * @static\n * @param {agent.INewVaultRequestMessage} m NewVaultRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n NewVaultRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n return w;\n };\n\n /**\n * Decodes a NewVaultRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.NewVaultRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.NewVaultRequestMessage} NewVaultRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n NewVaultRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewVaultRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return NewVaultRequestMessage;\n })();\n\n agent.NewVaultResponseMessage = (function() {\n\n /**\n * Properties of a NewVaultResponseMessage.\n * @memberof agent\n * @interface INewVaultResponseMessage\n * @property {boolean|null} [successful] NewVaultResponseMessage successful\n */\n\n /**\n * Constructs a new NewVaultResponseMessage.\n * @memberof agent\n * @classdesc Represents a NewVaultResponseMessage.\n * @implements INewVaultResponseMessage\n * @constructor\n * @param {agent.INewVaultResponseMessage=} [p] Properties to set\n */\n function NewVaultResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * NewVaultResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.NewVaultResponseMessage\n * @instance\n */\n NewVaultResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new NewVaultResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.NewVaultResponseMessage\n * @static\n * @param {agent.INewVaultResponseMessage=} [properties] Properties to set\n * @returns {agent.NewVaultResponseMessage} NewVaultResponseMessage instance\n */\n NewVaultResponseMessage.create = function create(properties) {\n return new NewVaultResponseMessage(properties);\n };\n\n /**\n * Encodes the specified NewVaultResponseMessage message. Does not implicitly {@link agent.NewVaultResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.NewVaultResponseMessage\n * @static\n * @param {agent.INewVaultResponseMessage} m NewVaultResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n NewVaultResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a NewVaultResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.NewVaultResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.NewVaultResponseMessage} NewVaultResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n NewVaultResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewVaultResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return NewVaultResponseMessage;\n })();\n\n agent.DestroyVaultRequestMessage = (function() {\n\n /**\n * Properties of a DestroyVaultRequestMessage.\n * @memberof agent\n * @interface IDestroyVaultRequestMessage\n * @property {string|null} [vaultName] DestroyVaultRequestMessage vaultName\n */\n\n /**\n * Constructs a new DestroyVaultRequestMessage.\n * @memberof agent\n * @classdesc Represents a DestroyVaultRequestMessage.\n * @implements IDestroyVaultRequestMessage\n * @constructor\n * @param {agent.IDestroyVaultRequestMessage=} [p] Properties to set\n */\n function DestroyVaultRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DestroyVaultRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.DestroyVaultRequestMessage\n * @instance\n */\n DestroyVaultRequestMessage.prototype.vaultName = \"\";\n\n /**\n * Creates a new DestroyVaultRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.DestroyVaultRequestMessage\n * @static\n * @param {agent.IDestroyVaultRequestMessage=} [properties] Properties to set\n * @returns {agent.DestroyVaultRequestMessage} DestroyVaultRequestMessage instance\n */\n DestroyVaultRequestMessage.create = function create(properties) {\n return new DestroyVaultRequestMessage(properties);\n };\n\n /**\n * Encodes the specified DestroyVaultRequestMessage message. Does not implicitly {@link agent.DestroyVaultRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DestroyVaultRequestMessage\n * @static\n * @param {agent.IDestroyVaultRequestMessage} m DestroyVaultRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DestroyVaultRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n return w;\n };\n\n /**\n * Decodes a DestroyVaultRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DestroyVaultRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DestroyVaultRequestMessage} DestroyVaultRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DestroyVaultRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroyVaultRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DestroyVaultRequestMessage;\n })();\n\n agent.DestroyVaultResponseMessage = (function() {\n\n /**\n * Properties of a DestroyVaultResponseMessage.\n * @memberof agent\n * @interface IDestroyVaultResponseMessage\n * @property {boolean|null} [successful] DestroyVaultResponseMessage successful\n */\n\n /**\n * Constructs a new DestroyVaultResponseMessage.\n * @memberof agent\n * @classdesc Represents a DestroyVaultResponseMessage.\n * @implements IDestroyVaultResponseMessage\n * @constructor\n * @param {agent.IDestroyVaultResponseMessage=} [p] Properties to set\n */\n function DestroyVaultResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DestroyVaultResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.DestroyVaultResponseMessage\n * @instance\n */\n DestroyVaultResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new DestroyVaultResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.DestroyVaultResponseMessage\n * @static\n * @param {agent.IDestroyVaultResponseMessage=} [properties] Properties to set\n * @returns {agent.DestroyVaultResponseMessage} DestroyVaultResponseMessage instance\n */\n DestroyVaultResponseMessage.create = function create(properties) {\n return new DestroyVaultResponseMessage(properties);\n };\n\n /**\n * Encodes the specified DestroyVaultResponseMessage message. Does not implicitly {@link agent.DestroyVaultResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DestroyVaultResponseMessage\n * @static\n * @param {agent.IDestroyVaultResponseMessage} m DestroyVaultResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DestroyVaultResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a DestroyVaultResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DestroyVaultResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DestroyVaultResponseMessage} DestroyVaultResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DestroyVaultResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroyVaultResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DestroyVaultResponseMessage;\n })();\n\n agent.ListSecretsRequestMessage = (function() {\n\n /**\n * Properties of a ListSecretsRequestMessage.\n * @memberof agent\n * @interface IListSecretsRequestMessage\n * @property {string|null} [vaultName] ListSecretsRequestMessage vaultName\n */\n\n /**\n * Constructs a new ListSecretsRequestMessage.\n * @memberof agent\n * @classdesc Represents a ListSecretsRequestMessage.\n * @implements IListSecretsRequestMessage\n * @constructor\n * @param {agent.IListSecretsRequestMessage=} [p] Properties to set\n */\n function ListSecretsRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListSecretsRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.ListSecretsRequestMessage\n * @instance\n */\n ListSecretsRequestMessage.prototype.vaultName = \"\";\n\n /**\n * Creates a new ListSecretsRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListSecretsRequestMessage\n * @static\n * @param {agent.IListSecretsRequestMessage=} [properties] Properties to set\n * @returns {agent.ListSecretsRequestMessage} ListSecretsRequestMessage instance\n */\n ListSecretsRequestMessage.create = function create(properties) {\n return new ListSecretsRequestMessage(properties);\n };\n\n /**\n * Encodes the specified ListSecretsRequestMessage message. Does not implicitly {@link agent.ListSecretsRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListSecretsRequestMessage\n * @static\n * @param {agent.IListSecretsRequestMessage} m ListSecretsRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListSecretsRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n return w;\n };\n\n /**\n * Decodes a ListSecretsRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListSecretsRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListSecretsRequestMessage} ListSecretsRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListSecretsRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListSecretsRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListSecretsRequestMessage;\n })();\n\n agent.ListSecretsResponseMessage = (function() {\n\n /**\n * Properties of a ListSecretsResponseMessage.\n * @memberof agent\n * @interface IListSecretsResponseMessage\n * @property {Array.|null} [secretNames] ListSecretsResponseMessage secretNames\n */\n\n /**\n * Constructs a new ListSecretsResponseMessage.\n * @memberof agent\n * @classdesc Represents a ListSecretsResponseMessage.\n * @implements IListSecretsResponseMessage\n * @constructor\n * @param {agent.IListSecretsResponseMessage=} [p] Properties to set\n */\n function ListSecretsResponseMessage(p) {\n this.secretNames = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListSecretsResponseMessage secretNames.\n * @member {Array.} secretNames\n * @memberof agent.ListSecretsResponseMessage\n * @instance\n */\n ListSecretsResponseMessage.prototype.secretNames = $util.emptyArray;\n\n /**\n * Creates a new ListSecretsResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListSecretsResponseMessage\n * @static\n * @param {agent.IListSecretsResponseMessage=} [properties] Properties to set\n * @returns {agent.ListSecretsResponseMessage} ListSecretsResponseMessage instance\n */\n ListSecretsResponseMessage.create = function create(properties) {\n return new ListSecretsResponseMessage(properties);\n };\n\n /**\n * Encodes the specified ListSecretsResponseMessage message. Does not implicitly {@link agent.ListSecretsResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListSecretsResponseMessage\n * @static\n * @param {agent.IListSecretsResponseMessage} m ListSecretsResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListSecretsResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.secretNames != null && m.secretNames.length) {\n for (var i = 0; i < m.secretNames.length; ++i)\n w.uint32(10).string(m.secretNames[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ListSecretsResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListSecretsResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListSecretsResponseMessage} ListSecretsResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListSecretsResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListSecretsResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.secretNames && m.secretNames.length))\n m.secretNames = [];\n m.secretNames.push(r.string());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListSecretsResponseMessage;\n })();\n\n agent.CreateSecretRequestMessage = (function() {\n\n /**\n * Properties of a CreateSecretRequestMessage.\n * @memberof agent\n * @interface ICreateSecretRequestMessage\n * @property {string|null} [vaultName] CreateSecretRequestMessage vaultName\n * @property {string|null} [secretName] CreateSecretRequestMessage secretName\n * @property {string|null} [secretPath] CreateSecretRequestMessage secretPath\n */\n\n /**\n * Constructs a new CreateSecretRequestMessage.\n * @memberof agent\n * @classdesc Represents a CreateSecretRequestMessage.\n * @implements ICreateSecretRequestMessage\n * @constructor\n * @param {agent.ICreateSecretRequestMessage=} [p] Properties to set\n */\n function CreateSecretRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * CreateSecretRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.CreateSecretRequestMessage\n * @instance\n */\n CreateSecretRequestMessage.prototype.vaultName = \"\";\n\n /**\n * CreateSecretRequestMessage secretName.\n * @member {string} secretName\n * @memberof agent.CreateSecretRequestMessage\n * @instance\n */\n CreateSecretRequestMessage.prototype.secretName = \"\";\n\n /**\n * CreateSecretRequestMessage secretPath.\n * @member {string} secretPath\n * @memberof agent.CreateSecretRequestMessage\n * @instance\n */\n CreateSecretRequestMessage.prototype.secretPath = \"\";\n\n /**\n * Creates a new CreateSecretRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.CreateSecretRequestMessage\n * @static\n * @param {agent.ICreateSecretRequestMessage=} [properties] Properties to set\n * @returns {agent.CreateSecretRequestMessage} CreateSecretRequestMessage instance\n */\n CreateSecretRequestMessage.create = function create(properties) {\n return new CreateSecretRequestMessage(properties);\n };\n\n /**\n * Encodes the specified CreateSecretRequestMessage message. Does not implicitly {@link agent.CreateSecretRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.CreateSecretRequestMessage\n * @static\n * @param {agent.ICreateSecretRequestMessage} m CreateSecretRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n CreateSecretRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n if (m.secretName != null && Object.hasOwnProperty.call(m, \"secretName\"))\n w.uint32(18).string(m.secretName);\n if (m.secretPath != null && Object.hasOwnProperty.call(m, \"secretPath\"))\n w.uint32(26).string(m.secretPath);\n return w;\n };\n\n /**\n * Decodes a CreateSecretRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.CreateSecretRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.CreateSecretRequestMessage} CreateSecretRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n CreateSecretRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.CreateSecretRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n case 2:\n m.secretName = r.string();\n break;\n case 3:\n m.secretPath = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return CreateSecretRequestMessage;\n })();\n\n agent.CreateSecretResponseMessage = (function() {\n\n /**\n * Properties of a CreateSecretResponseMessage.\n * @memberof agent\n * @interface ICreateSecretResponseMessage\n * @property {boolean|null} [successful] CreateSecretResponseMessage successful\n */\n\n /**\n * Constructs a new CreateSecretResponseMessage.\n * @memberof agent\n * @classdesc Represents a CreateSecretResponseMessage.\n * @implements ICreateSecretResponseMessage\n * @constructor\n * @param {agent.ICreateSecretResponseMessage=} [p] Properties to set\n */\n function CreateSecretResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * CreateSecretResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.CreateSecretResponseMessage\n * @instance\n */\n CreateSecretResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new CreateSecretResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.CreateSecretResponseMessage\n * @static\n * @param {agent.ICreateSecretResponseMessage=} [properties] Properties to set\n * @returns {agent.CreateSecretResponseMessage} CreateSecretResponseMessage instance\n */\n CreateSecretResponseMessage.create = function create(properties) {\n return new CreateSecretResponseMessage(properties);\n };\n\n /**\n * Encodes the specified CreateSecretResponseMessage message. Does not implicitly {@link agent.CreateSecretResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.CreateSecretResponseMessage\n * @static\n * @param {agent.ICreateSecretResponseMessage} m CreateSecretResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n CreateSecretResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a CreateSecretResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.CreateSecretResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.CreateSecretResponseMessage} CreateSecretResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n CreateSecretResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.CreateSecretResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return CreateSecretResponseMessage;\n })();\n\n agent.DestroySecretRequestMessage = (function() {\n\n /**\n * Properties of a DestroySecretRequestMessage.\n * @memberof agent\n * @interface IDestroySecretRequestMessage\n * @property {string|null} [vaultName] DestroySecretRequestMessage vaultName\n * @property {string|null} [secretName] DestroySecretRequestMessage secretName\n */\n\n /**\n * Constructs a new DestroySecretRequestMessage.\n * @memberof agent\n * @classdesc Represents a DestroySecretRequestMessage.\n * @implements IDestroySecretRequestMessage\n * @constructor\n * @param {agent.IDestroySecretRequestMessage=} [p] Properties to set\n */\n function DestroySecretRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DestroySecretRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.DestroySecretRequestMessage\n * @instance\n */\n DestroySecretRequestMessage.prototype.vaultName = \"\";\n\n /**\n * DestroySecretRequestMessage secretName.\n * @member {string} secretName\n * @memberof agent.DestroySecretRequestMessage\n * @instance\n */\n DestroySecretRequestMessage.prototype.secretName = \"\";\n\n /**\n * Creates a new DestroySecretRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.DestroySecretRequestMessage\n * @static\n * @param {agent.IDestroySecretRequestMessage=} [properties] Properties to set\n * @returns {agent.DestroySecretRequestMessage} DestroySecretRequestMessage instance\n */\n DestroySecretRequestMessage.create = function create(properties) {\n return new DestroySecretRequestMessage(properties);\n };\n\n /**\n * Encodes the specified DestroySecretRequestMessage message. Does not implicitly {@link agent.DestroySecretRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DestroySecretRequestMessage\n * @static\n * @param {agent.IDestroySecretRequestMessage} m DestroySecretRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DestroySecretRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n if (m.secretName != null && Object.hasOwnProperty.call(m, \"secretName\"))\n w.uint32(18).string(m.secretName);\n return w;\n };\n\n /**\n * Decodes a DestroySecretRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DestroySecretRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DestroySecretRequestMessage} DestroySecretRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DestroySecretRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroySecretRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n case 2:\n m.secretName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DestroySecretRequestMessage;\n })();\n\n agent.DestroySecretResponseMessage = (function() {\n\n /**\n * Properties of a DestroySecretResponseMessage.\n * @memberof agent\n * @interface IDestroySecretResponseMessage\n * @property {boolean|null} [successful] DestroySecretResponseMessage successful\n */\n\n /**\n * Constructs a new DestroySecretResponseMessage.\n * @memberof agent\n * @classdesc Represents a DestroySecretResponseMessage.\n * @implements IDestroySecretResponseMessage\n * @constructor\n * @param {agent.IDestroySecretResponseMessage=} [p] Properties to set\n */\n function DestroySecretResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DestroySecretResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.DestroySecretResponseMessage\n * @instance\n */\n DestroySecretResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new DestroySecretResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.DestroySecretResponseMessage\n * @static\n * @param {agent.IDestroySecretResponseMessage=} [properties] Properties to set\n * @returns {agent.DestroySecretResponseMessage} DestroySecretResponseMessage instance\n */\n DestroySecretResponseMessage.create = function create(properties) {\n return new DestroySecretResponseMessage(properties);\n };\n\n /**\n * Encodes the specified DestroySecretResponseMessage message. Does not implicitly {@link agent.DestroySecretResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DestroySecretResponseMessage\n * @static\n * @param {agent.IDestroySecretResponseMessage} m DestroySecretResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DestroySecretResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a DestroySecretResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DestroySecretResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DestroySecretResponseMessage} DestroySecretResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DestroySecretResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroySecretResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DestroySecretResponseMessage;\n })();\n\n agent.GetSecretRequestMessage = (function() {\n\n /**\n * Properties of a GetSecretRequestMessage.\n * @memberof agent\n * @interface IGetSecretRequestMessage\n * @property {string|null} [vaultName] GetSecretRequestMessage vaultName\n * @property {string|null} [secretName] GetSecretRequestMessage secretName\n */\n\n /**\n * Constructs a new GetSecretRequestMessage.\n * @memberof agent\n * @classdesc Represents a GetSecretRequestMessage.\n * @implements IGetSecretRequestMessage\n * @constructor\n * @param {agent.IGetSecretRequestMessage=} [p] Properties to set\n */\n function GetSecretRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * GetSecretRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.GetSecretRequestMessage\n * @instance\n */\n GetSecretRequestMessage.prototype.vaultName = \"\";\n\n /**\n * GetSecretRequestMessage secretName.\n * @member {string} secretName\n * @memberof agent.GetSecretRequestMessage\n * @instance\n */\n GetSecretRequestMessage.prototype.secretName = \"\";\n\n /**\n * Creates a new GetSecretRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.GetSecretRequestMessage\n * @static\n * @param {agent.IGetSecretRequestMessage=} [properties] Properties to set\n * @returns {agent.GetSecretRequestMessage} GetSecretRequestMessage instance\n */\n GetSecretRequestMessage.create = function create(properties) {\n return new GetSecretRequestMessage(properties);\n };\n\n /**\n * Encodes the specified GetSecretRequestMessage message. Does not implicitly {@link agent.GetSecretRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.GetSecretRequestMessage\n * @static\n * @param {agent.IGetSecretRequestMessage} m GetSecretRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n GetSecretRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n if (m.secretName != null && Object.hasOwnProperty.call(m, \"secretName\"))\n w.uint32(18).string(m.secretName);\n return w;\n };\n\n /**\n * Decodes a GetSecretRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.GetSecretRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.GetSecretRequestMessage} GetSecretRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n GetSecretRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.GetSecretRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n case 2:\n m.secretName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return GetSecretRequestMessage;\n })();\n\n agent.GetSecretResponseMessage = (function() {\n\n /**\n * Properties of a GetSecretResponseMessage.\n * @memberof agent\n * @interface IGetSecretResponseMessage\n * @property {Uint8Array|null} [secret] GetSecretResponseMessage secret\n */\n\n /**\n * Constructs a new GetSecretResponseMessage.\n * @memberof agent\n * @classdesc Represents a GetSecretResponseMessage.\n * @implements IGetSecretResponseMessage\n * @constructor\n * @param {agent.IGetSecretResponseMessage=} [p] Properties to set\n */\n function GetSecretResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * GetSecretResponseMessage secret.\n * @member {Uint8Array} secret\n * @memberof agent.GetSecretResponseMessage\n * @instance\n */\n GetSecretResponseMessage.prototype.secret = $util.newBuffer([]);\n\n /**\n * Creates a new GetSecretResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.GetSecretResponseMessage\n * @static\n * @param {agent.IGetSecretResponseMessage=} [properties] Properties to set\n * @returns {agent.GetSecretResponseMessage} GetSecretResponseMessage instance\n */\n GetSecretResponseMessage.create = function create(properties) {\n return new GetSecretResponseMessage(properties);\n };\n\n /**\n * Encodes the specified GetSecretResponseMessage message. Does not implicitly {@link agent.GetSecretResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.GetSecretResponseMessage\n * @static\n * @param {agent.IGetSecretResponseMessage} m GetSecretResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n GetSecretResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.secret != null && Object.hasOwnProperty.call(m, \"secret\"))\n w.uint32(10).bytes(m.secret);\n return w;\n };\n\n /**\n * Decodes a GetSecretResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.GetSecretResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.GetSecretResponseMessage} GetSecretResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n GetSecretResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.GetSecretResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.secret = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return GetSecretResponseMessage;\n })();\n\n agent.DeriveKeyRequestMessage = (function() {\n\n /**\n * Properties of a DeriveKeyRequestMessage.\n * @memberof agent\n * @interface IDeriveKeyRequestMessage\n * @property {string|null} [vaultName] DeriveKeyRequestMessage vaultName\n * @property {string|null} [keyName] DeriveKeyRequestMessage keyName\n * @property {string|null} [passphrase] DeriveKeyRequestMessage passphrase\n */\n\n /**\n * Constructs a new DeriveKeyRequestMessage.\n * @memberof agent\n * @classdesc Represents a DeriveKeyRequestMessage.\n * @implements IDeriveKeyRequestMessage\n * @constructor\n * @param {agent.IDeriveKeyRequestMessage=} [p] Properties to set\n */\n function DeriveKeyRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DeriveKeyRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.DeriveKeyRequestMessage\n * @instance\n */\n DeriveKeyRequestMessage.prototype.vaultName = \"\";\n\n /**\n * DeriveKeyRequestMessage keyName.\n * @member {string} keyName\n * @memberof agent.DeriveKeyRequestMessage\n * @instance\n */\n DeriveKeyRequestMessage.prototype.keyName = \"\";\n\n /**\n * DeriveKeyRequestMessage passphrase.\n * @member {string} passphrase\n * @memberof agent.DeriveKeyRequestMessage\n * @instance\n */\n DeriveKeyRequestMessage.prototype.passphrase = \"\";\n\n /**\n * Creates a new DeriveKeyRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.DeriveKeyRequestMessage\n * @static\n * @param {agent.IDeriveKeyRequestMessage=} [properties] Properties to set\n * @returns {agent.DeriveKeyRequestMessage} DeriveKeyRequestMessage instance\n */\n DeriveKeyRequestMessage.create = function create(properties) {\n return new DeriveKeyRequestMessage(properties);\n };\n\n /**\n * Encodes the specified DeriveKeyRequestMessage message. Does not implicitly {@link agent.DeriveKeyRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DeriveKeyRequestMessage\n * @static\n * @param {agent.IDeriveKeyRequestMessage} m DeriveKeyRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DeriveKeyRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n if (m.keyName != null && Object.hasOwnProperty.call(m, \"keyName\"))\n w.uint32(18).string(m.keyName);\n if (m.passphrase != null && Object.hasOwnProperty.call(m, \"passphrase\"))\n w.uint32(26).string(m.passphrase);\n return w;\n };\n\n /**\n * Decodes a DeriveKeyRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DeriveKeyRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DeriveKeyRequestMessage} DeriveKeyRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DeriveKeyRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DeriveKeyRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n case 2:\n m.keyName = r.string();\n break;\n case 3:\n m.passphrase = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DeriveKeyRequestMessage;\n })();\n\n agent.DeriveKeyResponseMessage = (function() {\n\n /**\n * Properties of a DeriveKeyResponseMessage.\n * @memberof agent\n * @interface IDeriveKeyResponseMessage\n * @property {boolean|null} [successful] DeriveKeyResponseMessage successful\n */\n\n /**\n * Constructs a new DeriveKeyResponseMessage.\n * @memberof agent\n * @classdesc Represents a DeriveKeyResponseMessage.\n * @implements IDeriveKeyResponseMessage\n * @constructor\n * @param {agent.IDeriveKeyResponseMessage=} [p] Properties to set\n */\n function DeriveKeyResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DeriveKeyResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.DeriveKeyResponseMessage\n * @instance\n */\n DeriveKeyResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new DeriveKeyResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.DeriveKeyResponseMessage\n * @static\n * @param {agent.IDeriveKeyResponseMessage=} [properties] Properties to set\n * @returns {agent.DeriveKeyResponseMessage} DeriveKeyResponseMessage instance\n */\n DeriveKeyResponseMessage.create = function create(properties) {\n return new DeriveKeyResponseMessage(properties);\n };\n\n /**\n * Encodes the specified DeriveKeyResponseMessage message. Does not implicitly {@link agent.DeriveKeyResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DeriveKeyResponseMessage\n * @static\n * @param {agent.IDeriveKeyResponseMessage} m DeriveKeyResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DeriveKeyResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a DeriveKeyResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DeriveKeyResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DeriveKeyResponseMessage} DeriveKeyResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DeriveKeyResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DeriveKeyResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DeriveKeyResponseMessage;\n })();\n\n return agent;\n})();\n\nmodule.exports = $root;\n","module.exports = require(\"protobufjs/minimal\");"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://browser-client/webpack/universalModuleDefinition","webpack://browser-client/webpack/bootstrap","webpack://browser-client/./src/lib/agent/PolykeyClient.ts","webpack://browser-client/./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack://browser-client/(webpack)/buildin/global.js","webpack://browser-client/external \"base64-js\"","webpack://browser-client/external \"ieee754\"","webpack://browser-client/external \"isarray\"","webpack://browser-client/./proto/js/Agent.js","webpack://browser-client/external \"protobufjs/minimal\""],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBAAmB,EAAE;QACrI;QACA;;QAEA;QACA;QACA;QACA,2BAA2B,0BAA0B,EAAE;QACvD,iCAAiC,eAAe;QAChD;QACA;QACA;;QAEA;QACA,sDAAsD,+DAA+D;;QAErH;QACA;;;QAGA;QACA;;;;;;;;AClFA,8CAAa;AACb,8CAA8C,cAAc;AAC5D,gBAAgB,mBAAO,CAAC,CAAyB;AACjD,OAAO,qtBAAqtB;AAC5tB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,mBAAmB,mBAAmB;AACtC;AACA,uBAAuB,QAAQ;AAC/B,yDAAyD,MAAM;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uEAAuE,aAAa;AACpF;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,6DAA6D,iCAAiC;AAC9F;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,+DAA+D,eAAe;AAC9E;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wDAAwD,sBAAsB;AAC9E;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,uCAAuC;AAC9F;AACA;AACA;AACA;AACA;AACA,eAAe,gBAAgB;AAC/B;AACA;AACA;AACA;AACA,yDAAyD,0BAA0B;AACnF;AACA;AACA;AACA;AACA;AACA,eAAe,WAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,uDAAuD,YAAY;AACnE;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,2DAA2D,YAAY;AACvE;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,YAAY;AACtE;AACA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,4CAA4C;AACrG;AACA;AACA,yDAAyD,+CAA+C;AACxG;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,4DAA4D,wBAAwB;AACpF;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,wDAAwD,wBAAwB;AAChF;AACA;AACA;AACA;AACA;AACA,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC1PA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEY;;AAEZ,aAAa,mBAAO,CAAC,CAAW;AAChC,cAAc,mBAAO,CAAC,CAAS;AAC/B,cAAc,mBAAO,CAAC,CAAS;;AAE/B;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,qBAAqB,mDAAmD;AACxE;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,mBAAmB,UAAU;AAC7B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,YAAY;AAC7B;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,0BAA0B;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA,uCAAuC,SAAS;AAChD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,iBAAiB;AAChC;AACA;AACA;;AAEA;AACA;AACA,aAAa,iBAAiB;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gDAAgD,EAAE;AAClD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,eAAe;AACvC;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,GAAG;AACH;AACA,wBAAwB,QAAQ;AAChC;AACA,qBAAqB,eAAe;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,YAAY;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA,SAAS;AACT;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,qBAAqB,SAAS;AAC9B;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,qBAAqB,SAAS;AAC9B;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,qBAAqB,SAAS;AAC9B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,kBAAkB;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA,mBAAmB,cAAc;AACjC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,uDAAuD,OAAO;AAC9D;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA,uDAAuD,OAAO;AAC9D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,qBAAqB,QAAQ;AAC7B;AACA;AACA,GAAG;AACH;AACA,eAAe,SAAS;AACxB;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA,mBAAmB,SAAS;AAC5B;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA,eAAe,iBAAiB;AAChC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,iBAAiB,YAAY;AAC7B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,iBAAiB,gBAAgB;AACjC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,gBAAgB;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,iBAAiB,YAAY;AAC7B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;;;;;;AC5vDA;;AAEA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA,CAAC;AACD;AACA;AACA;;AAEA;AACA;AACA,4CAA4C;;AAE5C;;;;;;;ACnBA,sC;;;;;;ACAA,oC;;;;;;ACAA,oC;;;;;;;ACAA;AACa;;AAEb,gBAAgB,mBAAO,CAAC,CAAoB;;AAE5C;AACA;;AAEA;AACA,0EAA0E;;AAE1E;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB,kBAAkB,OAAO;AACzB;AACA;AACA,2BAA2B;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,gBAAgB;AACtC,sBAAsB,aAAa;AACnC,sBAAsB,YAAY;AAClC,sBAAsB,gBAAgB;AACtC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,qBAAqB;AACxC;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,WAAW;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,WAAW;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,qBAAqB;AACxC,qBAAqB,mBAAmB;AACxC;AACA;AACA;AACA;;AAEA;AACA,4EAA4E,uCAAuC;AACnH;AACA;AACA;AACA,mBAAmB,oBAAoB;AACvC,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,mBAAmB;AACxC,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,qBAAqB;AACxC;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,qBAAqB;AACxC,qBAAqB,mBAAmB;AACxC;AACA;AACA;AACA;;AAEA;AACA,4EAA4E,uCAAuC;AACnH;AACA;AACA;AACA,mBAAmB,oBAAoB;AACvC,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,mBAAmB;AACxC,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD,qBAAqB,iCAAiC;AACtD;AACA;AACA;AACA;;AAEA;AACA,0FAA0F,qDAAqD;AAC/I;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,iCAAiC;AACtD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD,qBAAqB,kCAAkC;AACvD;AACA;AACA;AACA;;AAEA;AACA,2FAA2F,sDAAsD;AACjJ;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,kCAAkC;AACvD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,8BAA8B;AACjD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,8BAA8B;AACjD,qBAAqB,4BAA4B;AACjD;AACA;AACA;AACA;;AAEA;AACA,qFAAqF,gDAAgD;AACrI;AACA;AACA;AACA,mBAAmB,6BAA6B;AAChD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,4BAA4B;AACjD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD,qBAAqB,6BAA6B;AAClD;AACA;AACA;AACA;;AAEA;AACA,sFAAsF,iDAAiD;AACvI;AACA;AACA;AACA,mBAAmB,8BAA8B;AACjD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,6BAA6B;AAClD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,qBAAqB,8BAA8B;AACnD;AACA;AACA;AACA;;AAEA;AACA,uFAAuF,kDAAkD;AACzI;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,8BAA8B;AACnD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,oBAAoB;AAC1C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD;AACA;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,eAAe;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD,qBAAqB,+BAA+B;AACpD;AACA;AACA;AACA;;AAEA;AACA,wFAAwF,mDAAmD;AAC3I;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA,+BAA+B,oBAAoB;AACnD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,+BAA+B;AACpD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD,qBAAqB,6BAA6B;AAClD;AACA;AACA;AACA;;AAEA;AACA,sFAAsF,iDAAiD;AACvI;AACA;AACA;AACA,mBAAmB,8BAA8B;AACjD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,6BAA6B;AAClD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,qBAAqB,8BAA8B;AACnD;AACA;AACA;AACA;;AAEA;AACA,uFAAuF,kDAAkD;AACzI;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,8BAA8B;AACnD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD,qBAAqB,+BAA+B;AACpD;AACA;AACA;AACA;;AAEA;AACA,wFAAwF,mDAAmD;AAC3I;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,+BAA+B;AACpD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD,qBAAqB,gCAAgC;AACrD;AACA;AACA;AACA;;AAEA;AACA,yFAAyF,oDAAoD;AAC7I;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,gCAAgC;AACrD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD,qBAAqB,+BAA+B;AACpD;AACA;AACA;AACA;;AAEA;AACA,wFAAwF,mDAAmD;AAC3I;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,+BAA+B;AACpD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,oBAAoB;AAC1C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD;AACA;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,eAAe;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD,qBAAqB,gCAAgC;AACrD;AACA;AACA;AACA;;AAEA;AACA,yFAAyF,oDAAoD;AAC7I;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA,+BAA+B,yBAAyB;AACxD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,gCAAgC;AACrD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD,qBAAqB,6BAA6B;AAClD;AACA;AACA;AACA;;AAEA;AACA,sFAAsF,iDAAiD;AACvI;AACA;AACA;AACA,mBAAmB,8BAA8B;AACjD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,6BAA6B;AAClD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,qBAAqB,8BAA8B;AACnD;AACA;AACA;AACA;;AAEA;AACA,uFAAuF,kDAAkD;AACzI;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,8BAA8B;AACnD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD,qBAAqB,iCAAiC;AACtD;AACA;AACA;AACA;;AAEA;AACA,0FAA0F,qDAAqD;AAC/I;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,iCAAiC;AACtD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD,qBAAqB,kCAAkC;AACvD;AACA;AACA;AACA;;AAEA;AACA,2FAA2F,sDAAsD;AACjJ;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,kCAAkC;AACvD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD,qBAAqB,gCAAgC;AACrD;AACA;AACA;AACA;;AAEA;AACA,yFAAyF,oDAAoD;AAC7I;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,gCAAgC;AACrD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,oBAAoB;AAC1C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD;AACA;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,eAAe;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD,qBAAqB,iCAAiC;AACtD;AACA;AACA;AACA;;AAEA;AACA,0FAA0F,qDAAqD;AAC/I;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA,+BAA+B,0BAA0B;AACzD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,iCAAiC;AACtD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC,sBAAsB,gBAAgB;AACtC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,WAAW;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD,qBAAqB,iCAAiC;AACtD;AACA;AACA;AACA;;AAEA;AACA,0FAA0F,qDAAqD;AAC/I;AACA;AACA;AACA,mBAAmB,kCAAkC;AACrD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,iCAAiC;AACtD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD,qBAAqB,kCAAkC;AACvD;AACA;AACA;AACA;;AAEA;AACA,2FAA2F,sDAAsD;AACjJ;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,kCAAkC;AACvD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD,qBAAqB,kCAAkC;AACvD;AACA;AACA;AACA;;AAEA;AACA,2FAA2F,sDAAsD;AACjJ;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,kCAAkC;AACvD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,qCAAqC;AACxD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,qCAAqC;AACxD,qBAAqB,mCAAmC;AACxD;AACA;AACA;AACA;;AAEA;AACA,4FAA4F,uDAAuD;AACnJ;AACA;AACA;AACA,mBAAmB,oCAAoC;AACvD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,mCAAmC;AACxD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,qBAAqB,8BAA8B;AACnD;AACA;AACA;AACA;;AAEA;AACA,uFAAuF,kDAAkD;AACzI;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,8BAA8B;AACnD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,gBAAgB;AACtC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,WAAW;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD,qBAAqB,+BAA+B;AACpD;AACA;AACA;AACA;;AAEA;AACA,wFAAwF,mDAAmD;AAC3I;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,+BAA+B;AACpD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC,sBAAsB,YAAY;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,qBAAqB,8BAA8B;AACnD;AACA;AACA;AACA;;AAEA;AACA,uFAAuF,kDAAkD;AACzI;AACA;AACA;AACA,mBAAmB,+BAA+B;AAClD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,8BAA8B;AACnD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,iCAAiC;AACpD,qBAAqB,+BAA+B;AACpD;AACA;AACA;AACA;;AAEA;AACA,wFAAwF,mDAAmD;AAC3I;AACA;AACA;AACA,mBAAmB,gCAAgC;AACnD,mBAAmB,iBAAiB;AACpC,qBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4BAA4B;AAC/C,mBAAmB,OAAO;AAC1B,qBAAqB,+BAA+B;AACpD,oBAAoB,MAAM;AAC1B,oBAAoB,6BAA6B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;AACA,CAAC;;AAED;;;;;;;AC90FA,+C","file":"browser-client.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"browser-client\"] = factory();\n\telse\n\t\troot[\"browser-client\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Agent_1 = require(\"../../../proto/js/Agent\");\nconst { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage, } = Agent_1.agent;\nclass PolykeyClient {\n constructor(getStream) {\n this.getStream = getStream;\n }\n async sendRequestToAgent(request) {\n const stream = this.getStream();\n const responseList = await new Promise((resolve, reject) => {\n try {\n const responseList = [];\n stream.on('data', (data) => {\n if (data instanceof Uint8Array) {\n responseList.push(data);\n }\n else {\n responseList.push(...data);\n }\n });\n stream.on('error', (err) => {\n reject(err);\n });\n stream.on('end', () => {\n resolve(responseList);\n });\n if (!stream.writableEnded) {\n stream.write(request);\n }\n }\n catch (err) {\n reject(err);\n }\n });\n return responseList;\n }\n async handleAgentCommunication(type, nodePath, request) {\n // Encode message and sent\n const agentMessage = AgentMessage.encode({\n type: type,\n isResponse: false,\n nodePath: nodePath,\n subMessage: request,\n }).finish();\n const responseList = await this.sendRequestToAgent(agentMessage);\n const agentMessageList = [];\n for (const response of responseList.values()) {\n const { subMessage, type } = AgentMessage.decode(response);\n if (type == Type.ERROR) {\n const { error } = ErrorMessage.decode(subMessage);\n const reason = new Error(`Agent Error: ${error}`);\n throw reason;\n }\n else {\n agentMessageList.push(AgentMessage.decode(response));\n }\n }\n return agentMessageList;\n }\n async registerNode(path, passphrase) {\n var _a;\n const registerNodeRequest = RegisterNodeRequestMessage.encode({ passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.REGISTER_NODE, path, registerNodeRequest);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.REGISTER_NODE)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = RegisterNodeResponseMessage.decode(subMessage);\n return successful;\n }\n async newNode(path, name, email, passphrase, nbits) {\n var _a;\n const newNodeRequest = NewNodeRequestMessage.encode({ name, email, passphrase, nbits }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.NEW_NODE, path, newNodeRequest);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.NEW_NODE)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = NewNodeResponseMessage.decode(subMessage);\n return successful;\n }\n async listNodes(unlockedOnly = true) {\n var _a;\n const newNodeRequest = ListNodesRequestMessage.encode({ unlockedOnly }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_NODES, undefined, newNodeRequest);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_NODES)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { nodes } = ListNodesResponseMessage.decode(subMessage);\n return nodes;\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async deriveKey(nodePath, keyName, passphrase) {\n var _a;\n const request = DeriveKeyRequestMessage.encode({ keyName, passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DERIVE_KEY, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DERIVE_KEY)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = DeriveKeyResponseMessage.decode(subMessage);\n return successful;\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async signFile(nodePath, filePath, privateKeyPath, passphrase) {\n var _a;\n const request = SignFileRequestMessage.encode({ filePath, privateKeyPath, passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.SIGN_FILE, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.SIGN_FILE)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { signaturePath } = SignFileResponseMessage.decode(subMessage);\n return signaturePath;\n }\n async verifyFile(nodePath, filePath, signaturePath) {\n var _a;\n const request = VerifyFileRequestMessage.encode({ filePath, signaturePath }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.VERIFY_FILE, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.VERIFY_FILE)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { verified } = VerifyFileResponseMessage.decode(subMessage);\n return verified;\n }\n //////////////////////\n // Vault Operations //\n //////////////////////\n async listVaults(nodePath) {\n var _a;\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_VAULTS, nodePath);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_VAULTS)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { vaultNames } = ListVaultsResponseMessage.decode(subMessage);\n return vaultNames;\n }\n async newVault(nodePath, vaultName) {\n var _a;\n const request = NewVaultRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.NEW_VAULT, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.NEW_VAULT)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = NewVaultResponseMessage.decode(subMessage);\n return successful;\n }\n async destroyVault(nodePath, vaultName) {\n var _a;\n const request = DestroyVaultRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_VAULT, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DESTROY_VAULT)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = DestroyVaultResponseMessage.decode(subMessage);\n return successful;\n }\n ///////////////////////\n // Secret Operations //\n ///////////////////////\n async listSecrets(nodePath, vaultName) {\n var _a;\n const request = ListSecretsRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_SECRETS, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_SECRETS)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { secretNames } = ListSecretsResponseMessage.decode(subMessage);\n return secretNames;\n }\n async createSecret(nodePath, vaultName, secretName, secret) {\n var _a;\n let request;\n if (typeof secret == 'string') {\n request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretPath: secret }).finish();\n }\n else {\n request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretContent: secret }).finish();\n }\n const encodedResponse = await this.handleAgentCommunication(Type.CREATE_SECRET, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.CREATE_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = CreateSecretResponseMessage.decode(subMessage);\n return successful;\n }\n async destroySecret(nodePath, vaultName, secretName) {\n var _a;\n const request = DestroySecretRequestMessage.encode({ vaultName, secretName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_SECRET, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DESTROY_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = DestroySecretResponseMessage.decode(subMessage);\n return successful;\n }\n async getSecret(nodePath, vaultName, secretName) {\n var _a;\n const request = GetSecretRequestMessage.encode({ vaultName, secretName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.GET_SECRET, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.GET_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { secret } = GetSecretResponseMessage.decode(subMessage);\n return Buffer.from(secret);\n }\n ///////////////////\n // Agent control //\n ///////////////////\n async getAgentStatus() {\n var _a;\n try {\n const encodedResponse = await this.handleAgentCommunication(Type.STATUS);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.STATUS)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const status = Buffer.from(subMessage).toString();\n return status;\n }\n catch (err) {\n console.log(err);\n return 'stopped';\n }\n }\n async stopAgent() {\n try {\n // Tell it to start shutting and wait for response\n await this.handleAgentCommunication(Type.STOP_AGENT);\n return true;\n }\n catch (err) {\n return (await this.getAgentStatus()) != 'online';\n }\n }\n}\nexports.default = PolykeyClient;\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","module.exports = require(\"base64-js\");","module.exports = require(\"ieee754\");","module.exports = require(\"isarray\");","/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/\n\"use strict\";\n\nvar $protobuf = require(\"protobufjs/minimal\");\n\n// Common aliases\nvar $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nvar $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\n$root.agent = (function() {\n\n /**\n * Namespace agent.\n * @exports agent\n * @namespace\n */\n var agent = {};\n\n /**\n * Type enum.\n * @name agent.Type\n * @enum {number}\n * @property {number} ERROR=0 ERROR value\n * @property {number} STOP_AGENT=1 STOP_AGENT value\n * @property {number} STATUS=2 STATUS value\n * @property {number} REGISTER_NODE=3 REGISTER_NODE value\n * @property {number} NEW_NODE=4 NEW_NODE value\n * @property {number} LIST_NODES=5 LIST_NODES value\n * @property {number} DERIVE_KEY=6 DERIVE_KEY value\n * @property {number} SIGN_FILE=7 SIGN_FILE value\n * @property {number} VERIFY_FILE=8 VERIFY_FILE value\n * @property {number} LIST_VAULTS=9 LIST_VAULTS value\n * @property {number} NEW_VAULT=10 NEW_VAULT value\n * @property {number} DESTROY_VAULT=11 DESTROY_VAULT value\n * @property {number} LIST_SECRETS=12 LIST_SECRETS value\n * @property {number} CREATE_SECRET=13 CREATE_SECRET value\n * @property {number} DESTROY_SECRET=14 DESTROY_SECRET value\n * @property {number} GET_SECRET=15 GET_SECRET value\n */\n agent.Type = (function() {\n var valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"ERROR\"] = 0;\n values[valuesById[1] = \"STOP_AGENT\"] = 1;\n values[valuesById[2] = \"STATUS\"] = 2;\n values[valuesById[3] = \"REGISTER_NODE\"] = 3;\n values[valuesById[4] = \"NEW_NODE\"] = 4;\n values[valuesById[5] = \"LIST_NODES\"] = 5;\n values[valuesById[6] = \"DERIVE_KEY\"] = 6;\n values[valuesById[7] = \"SIGN_FILE\"] = 7;\n values[valuesById[8] = \"VERIFY_FILE\"] = 8;\n values[valuesById[9] = \"LIST_VAULTS\"] = 9;\n values[valuesById[10] = \"NEW_VAULT\"] = 10;\n values[valuesById[11] = \"DESTROY_VAULT\"] = 11;\n values[valuesById[12] = \"LIST_SECRETS\"] = 12;\n values[valuesById[13] = \"CREATE_SECRET\"] = 13;\n values[valuesById[14] = \"DESTROY_SECRET\"] = 14;\n values[valuesById[15] = \"GET_SECRET\"] = 15;\n return values;\n })();\n\n agent.AgentMessage = (function() {\n\n /**\n * Properties of an AgentMessage.\n * @memberof agent\n * @interface IAgentMessage\n * @property {agent.Type|null} [type] AgentMessage type\n * @property {boolean|null} [isResponse] AgentMessage isResponse\n * @property {string|null} [nodePath] AgentMessage nodePath\n * @property {Uint8Array|null} [subMessage] AgentMessage subMessage\n */\n\n /**\n * Constructs a new AgentMessage.\n * @memberof agent\n * @classdesc Represents an AgentMessage.\n * @implements IAgentMessage\n * @constructor\n * @param {agent.IAgentMessage=} [p] Properties to set\n */\n function AgentMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * AgentMessage type.\n * @member {agent.Type} type\n * @memberof agent.AgentMessage\n * @instance\n */\n AgentMessage.prototype.type = 0;\n\n /**\n * AgentMessage isResponse.\n * @member {boolean} isResponse\n * @memberof agent.AgentMessage\n * @instance\n */\n AgentMessage.prototype.isResponse = false;\n\n /**\n * AgentMessage nodePath.\n * @member {string} nodePath\n * @memberof agent.AgentMessage\n * @instance\n */\n AgentMessage.prototype.nodePath = \"\";\n\n /**\n * AgentMessage subMessage.\n * @member {Uint8Array} subMessage\n * @memberof agent.AgentMessage\n * @instance\n */\n AgentMessage.prototype.subMessage = $util.newBuffer([]);\n\n /**\n * Creates a new AgentMessage instance using the specified properties.\n * @function create\n * @memberof agent.AgentMessage\n * @static\n * @param {agent.IAgentMessage=} [properties] Properties to set\n * @returns {agent.AgentMessage} AgentMessage instance\n */\n AgentMessage.create = function create(properties) {\n return new AgentMessage(properties);\n };\n\n /**\n * Encodes the specified AgentMessage message. Does not implicitly {@link agent.AgentMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.AgentMessage\n * @static\n * @param {agent.IAgentMessage} m AgentMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n AgentMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.type != null && Object.hasOwnProperty.call(m, \"type\"))\n w.uint32(8).int32(m.type);\n if (m.isResponse != null && Object.hasOwnProperty.call(m, \"isResponse\"))\n w.uint32(16).bool(m.isResponse);\n if (m.nodePath != null && Object.hasOwnProperty.call(m, \"nodePath\"))\n w.uint32(26).string(m.nodePath);\n if (m.subMessage != null && Object.hasOwnProperty.call(m, \"subMessage\"))\n w.uint32(34).bytes(m.subMessage);\n return w;\n };\n\n /**\n * Decodes an AgentMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.AgentMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.AgentMessage} AgentMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n AgentMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.AgentMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.type = r.int32();\n break;\n case 2:\n m.isResponse = r.bool();\n break;\n case 3:\n m.nodePath = r.string();\n break;\n case 4:\n m.subMessage = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return AgentMessage;\n })();\n\n agent.ErrorMessage = (function() {\n\n /**\n * Properties of an ErrorMessage.\n * @memberof agent\n * @interface IErrorMessage\n * @property {string|null} [error] ErrorMessage error\n */\n\n /**\n * Constructs a new ErrorMessage.\n * @memberof agent\n * @classdesc Represents an ErrorMessage.\n * @implements IErrorMessage\n * @constructor\n * @param {agent.IErrorMessage=} [p] Properties to set\n */\n function ErrorMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ErrorMessage error.\n * @member {string} error\n * @memberof agent.ErrorMessage\n * @instance\n */\n ErrorMessage.prototype.error = \"\";\n\n /**\n * Creates a new ErrorMessage instance using the specified properties.\n * @function create\n * @memberof agent.ErrorMessage\n * @static\n * @param {agent.IErrorMessage=} [properties] Properties to set\n * @returns {agent.ErrorMessage} ErrorMessage instance\n */\n ErrorMessage.create = function create(properties) {\n return new ErrorMessage(properties);\n };\n\n /**\n * Encodes the specified ErrorMessage message. Does not implicitly {@link agent.ErrorMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ErrorMessage\n * @static\n * @param {agent.IErrorMessage} m ErrorMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ErrorMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.error != null && Object.hasOwnProperty.call(m, \"error\"))\n w.uint32(10).string(m.error);\n return w;\n };\n\n /**\n * Decodes an ErrorMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ErrorMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ErrorMessage} ErrorMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ErrorMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ErrorMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.error = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ErrorMessage;\n })();\n\n agent.RegisterNodeRequestMessage = (function() {\n\n /**\n * Properties of a RegisterNodeRequestMessage.\n * @memberof agent\n * @interface IRegisterNodeRequestMessage\n * @property {string|null} [passphrase] RegisterNodeRequestMessage passphrase\n */\n\n /**\n * Constructs a new RegisterNodeRequestMessage.\n * @memberof agent\n * @classdesc Represents a RegisterNodeRequestMessage.\n * @implements IRegisterNodeRequestMessage\n * @constructor\n * @param {agent.IRegisterNodeRequestMessage=} [p] Properties to set\n */\n function RegisterNodeRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * RegisterNodeRequestMessage passphrase.\n * @member {string} passphrase\n * @memberof agent.RegisterNodeRequestMessage\n * @instance\n */\n RegisterNodeRequestMessage.prototype.passphrase = \"\";\n\n /**\n * Creates a new RegisterNodeRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.RegisterNodeRequestMessage\n * @static\n * @param {agent.IRegisterNodeRequestMessage=} [properties] Properties to set\n * @returns {agent.RegisterNodeRequestMessage} RegisterNodeRequestMessage instance\n */\n RegisterNodeRequestMessage.create = function create(properties) {\n return new RegisterNodeRequestMessage(properties);\n };\n\n /**\n * Encodes the specified RegisterNodeRequestMessage message. Does not implicitly {@link agent.RegisterNodeRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.RegisterNodeRequestMessage\n * @static\n * @param {agent.IRegisterNodeRequestMessage} m RegisterNodeRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n RegisterNodeRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.passphrase != null && Object.hasOwnProperty.call(m, \"passphrase\"))\n w.uint32(10).string(m.passphrase);\n return w;\n };\n\n /**\n * Decodes a RegisterNodeRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.RegisterNodeRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.RegisterNodeRequestMessage} RegisterNodeRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n RegisterNodeRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.RegisterNodeRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.passphrase = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return RegisterNodeRequestMessage;\n })();\n\n agent.RegisterNodeResponseMessage = (function() {\n\n /**\n * Properties of a RegisterNodeResponseMessage.\n * @memberof agent\n * @interface IRegisterNodeResponseMessage\n * @property {boolean|null} [successful] RegisterNodeResponseMessage successful\n */\n\n /**\n * Constructs a new RegisterNodeResponseMessage.\n * @memberof agent\n * @classdesc Represents a RegisterNodeResponseMessage.\n * @implements IRegisterNodeResponseMessage\n * @constructor\n * @param {agent.IRegisterNodeResponseMessage=} [p] Properties to set\n */\n function RegisterNodeResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * RegisterNodeResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.RegisterNodeResponseMessage\n * @instance\n */\n RegisterNodeResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new RegisterNodeResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.RegisterNodeResponseMessage\n * @static\n * @param {agent.IRegisterNodeResponseMessage=} [properties] Properties to set\n * @returns {agent.RegisterNodeResponseMessage} RegisterNodeResponseMessage instance\n */\n RegisterNodeResponseMessage.create = function create(properties) {\n return new RegisterNodeResponseMessage(properties);\n };\n\n /**\n * Encodes the specified RegisterNodeResponseMessage message. Does not implicitly {@link agent.RegisterNodeResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.RegisterNodeResponseMessage\n * @static\n * @param {agent.IRegisterNodeResponseMessage} m RegisterNodeResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n RegisterNodeResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a RegisterNodeResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.RegisterNodeResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.RegisterNodeResponseMessage} RegisterNodeResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n RegisterNodeResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.RegisterNodeResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return RegisterNodeResponseMessage;\n })();\n\n agent.NewNodeRequestMessage = (function() {\n\n /**\n * Properties of a NewNodeRequestMessage.\n * @memberof agent\n * @interface INewNodeRequestMessage\n * @property {string|null} [name] NewNodeRequestMessage name\n * @property {string|null} [email] NewNodeRequestMessage email\n * @property {string|null} [passphrase] NewNodeRequestMessage passphrase\n * @property {number|null} [nbits] NewNodeRequestMessage nbits\n */\n\n /**\n * Constructs a new NewNodeRequestMessage.\n * @memberof agent\n * @classdesc Represents a NewNodeRequestMessage.\n * @implements INewNodeRequestMessage\n * @constructor\n * @param {agent.INewNodeRequestMessage=} [p] Properties to set\n */\n function NewNodeRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * NewNodeRequestMessage name.\n * @member {string} name\n * @memberof agent.NewNodeRequestMessage\n * @instance\n */\n NewNodeRequestMessage.prototype.name = \"\";\n\n /**\n * NewNodeRequestMessage email.\n * @member {string} email\n * @memberof agent.NewNodeRequestMessage\n * @instance\n */\n NewNodeRequestMessage.prototype.email = \"\";\n\n /**\n * NewNodeRequestMessage passphrase.\n * @member {string} passphrase\n * @memberof agent.NewNodeRequestMessage\n * @instance\n */\n NewNodeRequestMessage.prototype.passphrase = \"\";\n\n /**\n * NewNodeRequestMessage nbits.\n * @member {number} nbits\n * @memberof agent.NewNodeRequestMessage\n * @instance\n */\n NewNodeRequestMessage.prototype.nbits = 0;\n\n /**\n * Creates a new NewNodeRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.NewNodeRequestMessage\n * @static\n * @param {agent.INewNodeRequestMessage=} [properties] Properties to set\n * @returns {agent.NewNodeRequestMessage} NewNodeRequestMessage instance\n */\n NewNodeRequestMessage.create = function create(properties) {\n return new NewNodeRequestMessage(properties);\n };\n\n /**\n * Encodes the specified NewNodeRequestMessage message. Does not implicitly {@link agent.NewNodeRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.NewNodeRequestMessage\n * @static\n * @param {agent.INewNodeRequestMessage} m NewNodeRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n NewNodeRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.name != null && Object.hasOwnProperty.call(m, \"name\"))\n w.uint32(10).string(m.name);\n if (m.email != null && Object.hasOwnProperty.call(m, \"email\"))\n w.uint32(18).string(m.email);\n if (m.passphrase != null && Object.hasOwnProperty.call(m, \"passphrase\"))\n w.uint32(26).string(m.passphrase);\n if (m.nbits != null && Object.hasOwnProperty.call(m, \"nbits\"))\n w.uint32(32).int32(m.nbits);\n return w;\n };\n\n /**\n * Decodes a NewNodeRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.NewNodeRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.NewNodeRequestMessage} NewNodeRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n NewNodeRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewNodeRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.name = r.string();\n break;\n case 2:\n m.email = r.string();\n break;\n case 3:\n m.passphrase = r.string();\n break;\n case 4:\n m.nbits = r.int32();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return NewNodeRequestMessage;\n })();\n\n agent.NewNodeResponseMessage = (function() {\n\n /**\n * Properties of a NewNodeResponseMessage.\n * @memberof agent\n * @interface INewNodeResponseMessage\n * @property {boolean|null} [successful] NewNodeResponseMessage successful\n */\n\n /**\n * Constructs a new NewNodeResponseMessage.\n * @memberof agent\n * @classdesc Represents a NewNodeResponseMessage.\n * @implements INewNodeResponseMessage\n * @constructor\n * @param {agent.INewNodeResponseMessage=} [p] Properties to set\n */\n function NewNodeResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * NewNodeResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.NewNodeResponseMessage\n * @instance\n */\n NewNodeResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new NewNodeResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.NewNodeResponseMessage\n * @static\n * @param {agent.INewNodeResponseMessage=} [properties] Properties to set\n * @returns {agent.NewNodeResponseMessage} NewNodeResponseMessage instance\n */\n NewNodeResponseMessage.create = function create(properties) {\n return new NewNodeResponseMessage(properties);\n };\n\n /**\n * Encodes the specified NewNodeResponseMessage message. Does not implicitly {@link agent.NewNodeResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.NewNodeResponseMessage\n * @static\n * @param {agent.INewNodeResponseMessage} m NewNodeResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n NewNodeResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a NewNodeResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.NewNodeResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.NewNodeResponseMessage} NewNodeResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n NewNodeResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewNodeResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return NewNodeResponseMessage;\n })();\n\n agent.ListNodesRequestMessage = (function() {\n\n /**\n * Properties of a ListNodesRequestMessage.\n * @memberof agent\n * @interface IListNodesRequestMessage\n * @property {boolean|null} [unlockedOnly] ListNodesRequestMessage unlockedOnly\n */\n\n /**\n * Constructs a new ListNodesRequestMessage.\n * @memberof agent\n * @classdesc Represents a ListNodesRequestMessage.\n * @implements IListNodesRequestMessage\n * @constructor\n * @param {agent.IListNodesRequestMessage=} [p] Properties to set\n */\n function ListNodesRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListNodesRequestMessage unlockedOnly.\n * @member {boolean} unlockedOnly\n * @memberof agent.ListNodesRequestMessage\n * @instance\n */\n ListNodesRequestMessage.prototype.unlockedOnly = false;\n\n /**\n * Creates a new ListNodesRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListNodesRequestMessage\n * @static\n * @param {agent.IListNodesRequestMessage=} [properties] Properties to set\n * @returns {agent.ListNodesRequestMessage} ListNodesRequestMessage instance\n */\n ListNodesRequestMessage.create = function create(properties) {\n return new ListNodesRequestMessage(properties);\n };\n\n /**\n * Encodes the specified ListNodesRequestMessage message. Does not implicitly {@link agent.ListNodesRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListNodesRequestMessage\n * @static\n * @param {agent.IListNodesRequestMessage} m ListNodesRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListNodesRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.unlockedOnly != null && Object.hasOwnProperty.call(m, \"unlockedOnly\"))\n w.uint32(8).bool(m.unlockedOnly);\n return w;\n };\n\n /**\n * Decodes a ListNodesRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListNodesRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListNodesRequestMessage} ListNodesRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListNodesRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListNodesRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.unlockedOnly = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListNodesRequestMessage;\n })();\n\n agent.ListNodesResponseMessage = (function() {\n\n /**\n * Properties of a ListNodesResponseMessage.\n * @memberof agent\n * @interface IListNodesResponseMessage\n * @property {Array.|null} [nodes] ListNodesResponseMessage nodes\n */\n\n /**\n * Constructs a new ListNodesResponseMessage.\n * @memberof agent\n * @classdesc Represents a ListNodesResponseMessage.\n * @implements IListNodesResponseMessage\n * @constructor\n * @param {agent.IListNodesResponseMessage=} [p] Properties to set\n */\n function ListNodesResponseMessage(p) {\n this.nodes = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListNodesResponseMessage nodes.\n * @member {Array.} nodes\n * @memberof agent.ListNodesResponseMessage\n * @instance\n */\n ListNodesResponseMessage.prototype.nodes = $util.emptyArray;\n\n /**\n * Creates a new ListNodesResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListNodesResponseMessage\n * @static\n * @param {agent.IListNodesResponseMessage=} [properties] Properties to set\n * @returns {agent.ListNodesResponseMessage} ListNodesResponseMessage instance\n */\n ListNodesResponseMessage.create = function create(properties) {\n return new ListNodesResponseMessage(properties);\n };\n\n /**\n * Encodes the specified ListNodesResponseMessage message. Does not implicitly {@link agent.ListNodesResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListNodesResponseMessage\n * @static\n * @param {agent.IListNodesResponseMessage} m ListNodesResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListNodesResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.nodes != null && m.nodes.length) {\n for (var i = 0; i < m.nodes.length; ++i)\n w.uint32(10).string(m.nodes[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ListNodesResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListNodesResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListNodesResponseMessage} ListNodesResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListNodesResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListNodesResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.nodes && m.nodes.length))\n m.nodes = [];\n m.nodes.push(r.string());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListNodesResponseMessage;\n })();\n\n agent.SignFileRequestMessage = (function() {\n\n /**\n * Properties of a SignFileRequestMessage.\n * @memberof agent\n * @interface ISignFileRequestMessage\n * @property {string|null} [filePath] SignFileRequestMessage filePath\n * @property {string|null} [privateKeyPath] SignFileRequestMessage privateKeyPath\n * @property {string|null} [passphrase] SignFileRequestMessage passphrase\n */\n\n /**\n * Constructs a new SignFileRequestMessage.\n * @memberof agent\n * @classdesc Represents a SignFileRequestMessage.\n * @implements ISignFileRequestMessage\n * @constructor\n * @param {agent.ISignFileRequestMessage=} [p] Properties to set\n */\n function SignFileRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * SignFileRequestMessage filePath.\n * @member {string} filePath\n * @memberof agent.SignFileRequestMessage\n * @instance\n */\n SignFileRequestMessage.prototype.filePath = \"\";\n\n /**\n * SignFileRequestMessage privateKeyPath.\n * @member {string} privateKeyPath\n * @memberof agent.SignFileRequestMessage\n * @instance\n */\n SignFileRequestMessage.prototype.privateKeyPath = \"\";\n\n /**\n * SignFileRequestMessage passphrase.\n * @member {string} passphrase\n * @memberof agent.SignFileRequestMessage\n * @instance\n */\n SignFileRequestMessage.prototype.passphrase = \"\";\n\n /**\n * Creates a new SignFileRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.SignFileRequestMessage\n * @static\n * @param {agent.ISignFileRequestMessage=} [properties] Properties to set\n * @returns {agent.SignFileRequestMessage} SignFileRequestMessage instance\n */\n SignFileRequestMessage.create = function create(properties) {\n return new SignFileRequestMessage(properties);\n };\n\n /**\n * Encodes the specified SignFileRequestMessage message. Does not implicitly {@link agent.SignFileRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.SignFileRequestMessage\n * @static\n * @param {agent.ISignFileRequestMessage} m SignFileRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n SignFileRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.filePath != null && Object.hasOwnProperty.call(m, \"filePath\"))\n w.uint32(10).string(m.filePath);\n if (m.privateKeyPath != null && Object.hasOwnProperty.call(m, \"privateKeyPath\"))\n w.uint32(18).string(m.privateKeyPath);\n if (m.passphrase != null && Object.hasOwnProperty.call(m, \"passphrase\"))\n w.uint32(26).string(m.passphrase);\n return w;\n };\n\n /**\n * Decodes a SignFileRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.SignFileRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.SignFileRequestMessage} SignFileRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n SignFileRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.SignFileRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.filePath = r.string();\n break;\n case 2:\n m.privateKeyPath = r.string();\n break;\n case 3:\n m.passphrase = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return SignFileRequestMessage;\n })();\n\n agent.SignFileResponseMessage = (function() {\n\n /**\n * Properties of a SignFileResponseMessage.\n * @memberof agent\n * @interface ISignFileResponseMessage\n * @property {string|null} [signaturePath] SignFileResponseMessage signaturePath\n */\n\n /**\n * Constructs a new SignFileResponseMessage.\n * @memberof agent\n * @classdesc Represents a SignFileResponseMessage.\n * @implements ISignFileResponseMessage\n * @constructor\n * @param {agent.ISignFileResponseMessage=} [p] Properties to set\n */\n function SignFileResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * SignFileResponseMessage signaturePath.\n * @member {string} signaturePath\n * @memberof agent.SignFileResponseMessage\n * @instance\n */\n SignFileResponseMessage.prototype.signaturePath = \"\";\n\n /**\n * Creates a new SignFileResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.SignFileResponseMessage\n * @static\n * @param {agent.ISignFileResponseMessage=} [properties] Properties to set\n * @returns {agent.SignFileResponseMessage} SignFileResponseMessage instance\n */\n SignFileResponseMessage.create = function create(properties) {\n return new SignFileResponseMessage(properties);\n };\n\n /**\n * Encodes the specified SignFileResponseMessage message. Does not implicitly {@link agent.SignFileResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.SignFileResponseMessage\n * @static\n * @param {agent.ISignFileResponseMessage} m SignFileResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n SignFileResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.signaturePath != null && Object.hasOwnProperty.call(m, \"signaturePath\"))\n w.uint32(10).string(m.signaturePath);\n return w;\n };\n\n /**\n * Decodes a SignFileResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.SignFileResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.SignFileResponseMessage} SignFileResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n SignFileResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.SignFileResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.signaturePath = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return SignFileResponseMessage;\n })();\n\n agent.VerifyFileRequestMessage = (function() {\n\n /**\n * Properties of a VerifyFileRequestMessage.\n * @memberof agent\n * @interface IVerifyFileRequestMessage\n * @property {string|null} [filePath] VerifyFileRequestMessage filePath\n * @property {string|null} [signaturePath] VerifyFileRequestMessage signaturePath\n */\n\n /**\n * Constructs a new VerifyFileRequestMessage.\n * @memberof agent\n * @classdesc Represents a VerifyFileRequestMessage.\n * @implements IVerifyFileRequestMessage\n * @constructor\n * @param {agent.IVerifyFileRequestMessage=} [p] Properties to set\n */\n function VerifyFileRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * VerifyFileRequestMessage filePath.\n * @member {string} filePath\n * @memberof agent.VerifyFileRequestMessage\n * @instance\n */\n VerifyFileRequestMessage.prototype.filePath = \"\";\n\n /**\n * VerifyFileRequestMessage signaturePath.\n * @member {string} signaturePath\n * @memberof agent.VerifyFileRequestMessage\n * @instance\n */\n VerifyFileRequestMessage.prototype.signaturePath = \"\";\n\n /**\n * Creates a new VerifyFileRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.VerifyFileRequestMessage\n * @static\n * @param {agent.IVerifyFileRequestMessage=} [properties] Properties to set\n * @returns {agent.VerifyFileRequestMessage} VerifyFileRequestMessage instance\n */\n VerifyFileRequestMessage.create = function create(properties) {\n return new VerifyFileRequestMessage(properties);\n };\n\n /**\n * Encodes the specified VerifyFileRequestMessage message. Does not implicitly {@link agent.VerifyFileRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.VerifyFileRequestMessage\n * @static\n * @param {agent.IVerifyFileRequestMessage} m VerifyFileRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n VerifyFileRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.filePath != null && Object.hasOwnProperty.call(m, \"filePath\"))\n w.uint32(10).string(m.filePath);\n if (m.signaturePath != null && Object.hasOwnProperty.call(m, \"signaturePath\"))\n w.uint32(18).string(m.signaturePath);\n return w;\n };\n\n /**\n * Decodes a VerifyFileRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.VerifyFileRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.VerifyFileRequestMessage} VerifyFileRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n VerifyFileRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.VerifyFileRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.filePath = r.string();\n break;\n case 2:\n m.signaturePath = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return VerifyFileRequestMessage;\n })();\n\n agent.VerifyFileResponseMessage = (function() {\n\n /**\n * Properties of a VerifyFileResponseMessage.\n * @memberof agent\n * @interface IVerifyFileResponseMessage\n * @property {boolean|null} [verified] VerifyFileResponseMessage verified\n */\n\n /**\n * Constructs a new VerifyFileResponseMessage.\n * @memberof agent\n * @classdesc Represents a VerifyFileResponseMessage.\n * @implements IVerifyFileResponseMessage\n * @constructor\n * @param {agent.IVerifyFileResponseMessage=} [p] Properties to set\n */\n function VerifyFileResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * VerifyFileResponseMessage verified.\n * @member {boolean} verified\n * @memberof agent.VerifyFileResponseMessage\n * @instance\n */\n VerifyFileResponseMessage.prototype.verified = false;\n\n /**\n * Creates a new VerifyFileResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.VerifyFileResponseMessage\n * @static\n * @param {agent.IVerifyFileResponseMessage=} [properties] Properties to set\n * @returns {agent.VerifyFileResponseMessage} VerifyFileResponseMessage instance\n */\n VerifyFileResponseMessage.create = function create(properties) {\n return new VerifyFileResponseMessage(properties);\n };\n\n /**\n * Encodes the specified VerifyFileResponseMessage message. Does not implicitly {@link agent.VerifyFileResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.VerifyFileResponseMessage\n * @static\n * @param {agent.IVerifyFileResponseMessage} m VerifyFileResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n VerifyFileResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.verified != null && Object.hasOwnProperty.call(m, \"verified\"))\n w.uint32(8).bool(m.verified);\n return w;\n };\n\n /**\n * Decodes a VerifyFileResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.VerifyFileResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.VerifyFileResponseMessage} VerifyFileResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n VerifyFileResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.VerifyFileResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.verified = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return VerifyFileResponseMessage;\n })();\n\n agent.ListVaultsRequestMessage = (function() {\n\n /**\n * Properties of a ListVaultsRequestMessage.\n * @memberof agent\n * @interface IListVaultsRequestMessage\n */\n\n /**\n * Constructs a new ListVaultsRequestMessage.\n * @memberof agent\n * @classdesc Represents a ListVaultsRequestMessage.\n * @implements IListVaultsRequestMessage\n * @constructor\n * @param {agent.IListVaultsRequestMessage=} [p] Properties to set\n */\n function ListVaultsRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Creates a new ListVaultsRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListVaultsRequestMessage\n * @static\n * @param {agent.IListVaultsRequestMessage=} [properties] Properties to set\n * @returns {agent.ListVaultsRequestMessage} ListVaultsRequestMessage instance\n */\n ListVaultsRequestMessage.create = function create(properties) {\n return new ListVaultsRequestMessage(properties);\n };\n\n /**\n * Encodes the specified ListVaultsRequestMessage message. Does not implicitly {@link agent.ListVaultsRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListVaultsRequestMessage\n * @static\n * @param {agent.IListVaultsRequestMessage} m ListVaultsRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListVaultsRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n return w;\n };\n\n /**\n * Decodes a ListVaultsRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListVaultsRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListVaultsRequestMessage} ListVaultsRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListVaultsRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListVaultsRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListVaultsRequestMessage;\n })();\n\n agent.ListVaultsResponseMessage = (function() {\n\n /**\n * Properties of a ListVaultsResponseMessage.\n * @memberof agent\n * @interface IListVaultsResponseMessage\n * @property {Array.|null} [vaultNames] ListVaultsResponseMessage vaultNames\n */\n\n /**\n * Constructs a new ListVaultsResponseMessage.\n * @memberof agent\n * @classdesc Represents a ListVaultsResponseMessage.\n * @implements IListVaultsResponseMessage\n * @constructor\n * @param {agent.IListVaultsResponseMessage=} [p] Properties to set\n */\n function ListVaultsResponseMessage(p) {\n this.vaultNames = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListVaultsResponseMessage vaultNames.\n * @member {Array.} vaultNames\n * @memberof agent.ListVaultsResponseMessage\n * @instance\n */\n ListVaultsResponseMessage.prototype.vaultNames = $util.emptyArray;\n\n /**\n * Creates a new ListVaultsResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListVaultsResponseMessage\n * @static\n * @param {agent.IListVaultsResponseMessage=} [properties] Properties to set\n * @returns {agent.ListVaultsResponseMessage} ListVaultsResponseMessage instance\n */\n ListVaultsResponseMessage.create = function create(properties) {\n return new ListVaultsResponseMessage(properties);\n };\n\n /**\n * Encodes the specified ListVaultsResponseMessage message. Does not implicitly {@link agent.ListVaultsResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListVaultsResponseMessage\n * @static\n * @param {agent.IListVaultsResponseMessage} m ListVaultsResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListVaultsResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultNames != null && m.vaultNames.length) {\n for (var i = 0; i < m.vaultNames.length; ++i)\n w.uint32(10).string(m.vaultNames[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ListVaultsResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListVaultsResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListVaultsResponseMessage} ListVaultsResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListVaultsResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListVaultsResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.vaultNames && m.vaultNames.length))\n m.vaultNames = [];\n m.vaultNames.push(r.string());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListVaultsResponseMessage;\n })();\n\n agent.NewVaultRequestMessage = (function() {\n\n /**\n * Properties of a NewVaultRequestMessage.\n * @memberof agent\n * @interface INewVaultRequestMessage\n * @property {string|null} [vaultName] NewVaultRequestMessage vaultName\n */\n\n /**\n * Constructs a new NewVaultRequestMessage.\n * @memberof agent\n * @classdesc Represents a NewVaultRequestMessage.\n * @implements INewVaultRequestMessage\n * @constructor\n * @param {agent.INewVaultRequestMessage=} [p] Properties to set\n */\n function NewVaultRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * NewVaultRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.NewVaultRequestMessage\n * @instance\n */\n NewVaultRequestMessage.prototype.vaultName = \"\";\n\n /**\n * Creates a new NewVaultRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.NewVaultRequestMessage\n * @static\n * @param {agent.INewVaultRequestMessage=} [properties] Properties to set\n * @returns {agent.NewVaultRequestMessage} NewVaultRequestMessage instance\n */\n NewVaultRequestMessage.create = function create(properties) {\n return new NewVaultRequestMessage(properties);\n };\n\n /**\n * Encodes the specified NewVaultRequestMessage message. Does not implicitly {@link agent.NewVaultRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.NewVaultRequestMessage\n * @static\n * @param {agent.INewVaultRequestMessage} m NewVaultRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n NewVaultRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n return w;\n };\n\n /**\n * Decodes a NewVaultRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.NewVaultRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.NewVaultRequestMessage} NewVaultRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n NewVaultRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewVaultRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return NewVaultRequestMessage;\n })();\n\n agent.NewVaultResponseMessage = (function() {\n\n /**\n * Properties of a NewVaultResponseMessage.\n * @memberof agent\n * @interface INewVaultResponseMessage\n * @property {boolean|null} [successful] NewVaultResponseMessage successful\n */\n\n /**\n * Constructs a new NewVaultResponseMessage.\n * @memberof agent\n * @classdesc Represents a NewVaultResponseMessage.\n * @implements INewVaultResponseMessage\n * @constructor\n * @param {agent.INewVaultResponseMessage=} [p] Properties to set\n */\n function NewVaultResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * NewVaultResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.NewVaultResponseMessage\n * @instance\n */\n NewVaultResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new NewVaultResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.NewVaultResponseMessage\n * @static\n * @param {agent.INewVaultResponseMessage=} [properties] Properties to set\n * @returns {agent.NewVaultResponseMessage} NewVaultResponseMessage instance\n */\n NewVaultResponseMessage.create = function create(properties) {\n return new NewVaultResponseMessage(properties);\n };\n\n /**\n * Encodes the specified NewVaultResponseMessage message. Does not implicitly {@link agent.NewVaultResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.NewVaultResponseMessage\n * @static\n * @param {agent.INewVaultResponseMessage} m NewVaultResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n NewVaultResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a NewVaultResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.NewVaultResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.NewVaultResponseMessage} NewVaultResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n NewVaultResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.NewVaultResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return NewVaultResponseMessage;\n })();\n\n agent.DestroyVaultRequestMessage = (function() {\n\n /**\n * Properties of a DestroyVaultRequestMessage.\n * @memberof agent\n * @interface IDestroyVaultRequestMessage\n * @property {string|null} [vaultName] DestroyVaultRequestMessage vaultName\n */\n\n /**\n * Constructs a new DestroyVaultRequestMessage.\n * @memberof agent\n * @classdesc Represents a DestroyVaultRequestMessage.\n * @implements IDestroyVaultRequestMessage\n * @constructor\n * @param {agent.IDestroyVaultRequestMessage=} [p] Properties to set\n */\n function DestroyVaultRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DestroyVaultRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.DestroyVaultRequestMessage\n * @instance\n */\n DestroyVaultRequestMessage.prototype.vaultName = \"\";\n\n /**\n * Creates a new DestroyVaultRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.DestroyVaultRequestMessage\n * @static\n * @param {agent.IDestroyVaultRequestMessage=} [properties] Properties to set\n * @returns {agent.DestroyVaultRequestMessage} DestroyVaultRequestMessage instance\n */\n DestroyVaultRequestMessage.create = function create(properties) {\n return new DestroyVaultRequestMessage(properties);\n };\n\n /**\n * Encodes the specified DestroyVaultRequestMessage message. Does not implicitly {@link agent.DestroyVaultRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DestroyVaultRequestMessage\n * @static\n * @param {agent.IDestroyVaultRequestMessage} m DestroyVaultRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DestroyVaultRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n return w;\n };\n\n /**\n * Decodes a DestroyVaultRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DestroyVaultRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DestroyVaultRequestMessage} DestroyVaultRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DestroyVaultRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroyVaultRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DestroyVaultRequestMessage;\n })();\n\n agent.DestroyVaultResponseMessage = (function() {\n\n /**\n * Properties of a DestroyVaultResponseMessage.\n * @memberof agent\n * @interface IDestroyVaultResponseMessage\n * @property {boolean|null} [successful] DestroyVaultResponseMessage successful\n */\n\n /**\n * Constructs a new DestroyVaultResponseMessage.\n * @memberof agent\n * @classdesc Represents a DestroyVaultResponseMessage.\n * @implements IDestroyVaultResponseMessage\n * @constructor\n * @param {agent.IDestroyVaultResponseMessage=} [p] Properties to set\n */\n function DestroyVaultResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DestroyVaultResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.DestroyVaultResponseMessage\n * @instance\n */\n DestroyVaultResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new DestroyVaultResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.DestroyVaultResponseMessage\n * @static\n * @param {agent.IDestroyVaultResponseMessage=} [properties] Properties to set\n * @returns {agent.DestroyVaultResponseMessage} DestroyVaultResponseMessage instance\n */\n DestroyVaultResponseMessage.create = function create(properties) {\n return new DestroyVaultResponseMessage(properties);\n };\n\n /**\n * Encodes the specified DestroyVaultResponseMessage message. Does not implicitly {@link agent.DestroyVaultResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DestroyVaultResponseMessage\n * @static\n * @param {agent.IDestroyVaultResponseMessage} m DestroyVaultResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DestroyVaultResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a DestroyVaultResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DestroyVaultResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DestroyVaultResponseMessage} DestroyVaultResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DestroyVaultResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroyVaultResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DestroyVaultResponseMessage;\n })();\n\n agent.ListSecretsRequestMessage = (function() {\n\n /**\n * Properties of a ListSecretsRequestMessage.\n * @memberof agent\n * @interface IListSecretsRequestMessage\n * @property {string|null} [vaultName] ListSecretsRequestMessage vaultName\n */\n\n /**\n * Constructs a new ListSecretsRequestMessage.\n * @memberof agent\n * @classdesc Represents a ListSecretsRequestMessage.\n * @implements IListSecretsRequestMessage\n * @constructor\n * @param {agent.IListSecretsRequestMessage=} [p] Properties to set\n */\n function ListSecretsRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListSecretsRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.ListSecretsRequestMessage\n * @instance\n */\n ListSecretsRequestMessage.prototype.vaultName = \"\";\n\n /**\n * Creates a new ListSecretsRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListSecretsRequestMessage\n * @static\n * @param {agent.IListSecretsRequestMessage=} [properties] Properties to set\n * @returns {agent.ListSecretsRequestMessage} ListSecretsRequestMessage instance\n */\n ListSecretsRequestMessage.create = function create(properties) {\n return new ListSecretsRequestMessage(properties);\n };\n\n /**\n * Encodes the specified ListSecretsRequestMessage message. Does not implicitly {@link agent.ListSecretsRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListSecretsRequestMessage\n * @static\n * @param {agent.IListSecretsRequestMessage} m ListSecretsRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListSecretsRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n return w;\n };\n\n /**\n * Decodes a ListSecretsRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListSecretsRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListSecretsRequestMessage} ListSecretsRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListSecretsRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListSecretsRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListSecretsRequestMessage;\n })();\n\n agent.ListSecretsResponseMessage = (function() {\n\n /**\n * Properties of a ListSecretsResponseMessage.\n * @memberof agent\n * @interface IListSecretsResponseMessage\n * @property {Array.|null} [secretNames] ListSecretsResponseMessage secretNames\n */\n\n /**\n * Constructs a new ListSecretsResponseMessage.\n * @memberof agent\n * @classdesc Represents a ListSecretsResponseMessage.\n * @implements IListSecretsResponseMessage\n * @constructor\n * @param {agent.IListSecretsResponseMessage=} [p] Properties to set\n */\n function ListSecretsResponseMessage(p) {\n this.secretNames = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ListSecretsResponseMessage secretNames.\n * @member {Array.} secretNames\n * @memberof agent.ListSecretsResponseMessage\n * @instance\n */\n ListSecretsResponseMessage.prototype.secretNames = $util.emptyArray;\n\n /**\n * Creates a new ListSecretsResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.ListSecretsResponseMessage\n * @static\n * @param {agent.IListSecretsResponseMessage=} [properties] Properties to set\n * @returns {agent.ListSecretsResponseMessage} ListSecretsResponseMessage instance\n */\n ListSecretsResponseMessage.create = function create(properties) {\n return new ListSecretsResponseMessage(properties);\n };\n\n /**\n * Encodes the specified ListSecretsResponseMessage message. Does not implicitly {@link agent.ListSecretsResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.ListSecretsResponseMessage\n * @static\n * @param {agent.IListSecretsResponseMessage} m ListSecretsResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ListSecretsResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.secretNames != null && m.secretNames.length) {\n for (var i = 0; i < m.secretNames.length; ++i)\n w.uint32(10).string(m.secretNames[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ListSecretsResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.ListSecretsResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.ListSecretsResponseMessage} ListSecretsResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ListSecretsResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.ListSecretsResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.secretNames && m.secretNames.length))\n m.secretNames = [];\n m.secretNames.push(r.string());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return ListSecretsResponseMessage;\n })();\n\n agent.CreateSecretRequestMessage = (function() {\n\n /**\n * Properties of a CreateSecretRequestMessage.\n * @memberof agent\n * @interface ICreateSecretRequestMessage\n * @property {string|null} [vaultName] CreateSecretRequestMessage vaultName\n * @property {string|null} [secretName] CreateSecretRequestMessage secretName\n * @property {string|null} [secretPath] CreateSecretRequestMessage secretPath\n * @property {Uint8Array|null} [secretContent] CreateSecretRequestMessage secretContent\n */\n\n /**\n * Constructs a new CreateSecretRequestMessage.\n * @memberof agent\n * @classdesc Represents a CreateSecretRequestMessage.\n * @implements ICreateSecretRequestMessage\n * @constructor\n * @param {agent.ICreateSecretRequestMessage=} [p] Properties to set\n */\n function CreateSecretRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * CreateSecretRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.CreateSecretRequestMessage\n * @instance\n */\n CreateSecretRequestMessage.prototype.vaultName = \"\";\n\n /**\n * CreateSecretRequestMessage secretName.\n * @member {string} secretName\n * @memberof agent.CreateSecretRequestMessage\n * @instance\n */\n CreateSecretRequestMessage.prototype.secretName = \"\";\n\n /**\n * CreateSecretRequestMessage secretPath.\n * @member {string} secretPath\n * @memberof agent.CreateSecretRequestMessage\n * @instance\n */\n CreateSecretRequestMessage.prototype.secretPath = \"\";\n\n /**\n * CreateSecretRequestMessage secretContent.\n * @member {Uint8Array} secretContent\n * @memberof agent.CreateSecretRequestMessage\n * @instance\n */\n CreateSecretRequestMessage.prototype.secretContent = $util.newBuffer([]);\n\n /**\n * Creates a new CreateSecretRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.CreateSecretRequestMessage\n * @static\n * @param {agent.ICreateSecretRequestMessage=} [properties] Properties to set\n * @returns {agent.CreateSecretRequestMessage} CreateSecretRequestMessage instance\n */\n CreateSecretRequestMessage.create = function create(properties) {\n return new CreateSecretRequestMessage(properties);\n };\n\n /**\n * Encodes the specified CreateSecretRequestMessage message. Does not implicitly {@link agent.CreateSecretRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.CreateSecretRequestMessage\n * @static\n * @param {agent.ICreateSecretRequestMessage} m CreateSecretRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n CreateSecretRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n if (m.secretName != null && Object.hasOwnProperty.call(m, \"secretName\"))\n w.uint32(18).string(m.secretName);\n if (m.secretPath != null && Object.hasOwnProperty.call(m, \"secretPath\"))\n w.uint32(26).string(m.secretPath);\n if (m.secretContent != null && Object.hasOwnProperty.call(m, \"secretContent\"))\n w.uint32(34).bytes(m.secretContent);\n return w;\n };\n\n /**\n * Decodes a CreateSecretRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.CreateSecretRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.CreateSecretRequestMessage} CreateSecretRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n CreateSecretRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.CreateSecretRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n case 2:\n m.secretName = r.string();\n break;\n case 3:\n m.secretPath = r.string();\n break;\n case 4:\n m.secretContent = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return CreateSecretRequestMessage;\n })();\n\n agent.CreateSecretResponseMessage = (function() {\n\n /**\n * Properties of a CreateSecretResponseMessage.\n * @memberof agent\n * @interface ICreateSecretResponseMessage\n * @property {boolean|null} [successful] CreateSecretResponseMessage successful\n */\n\n /**\n * Constructs a new CreateSecretResponseMessage.\n * @memberof agent\n * @classdesc Represents a CreateSecretResponseMessage.\n * @implements ICreateSecretResponseMessage\n * @constructor\n * @param {agent.ICreateSecretResponseMessage=} [p] Properties to set\n */\n function CreateSecretResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * CreateSecretResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.CreateSecretResponseMessage\n * @instance\n */\n CreateSecretResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new CreateSecretResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.CreateSecretResponseMessage\n * @static\n * @param {agent.ICreateSecretResponseMessage=} [properties] Properties to set\n * @returns {agent.CreateSecretResponseMessage} CreateSecretResponseMessage instance\n */\n CreateSecretResponseMessage.create = function create(properties) {\n return new CreateSecretResponseMessage(properties);\n };\n\n /**\n * Encodes the specified CreateSecretResponseMessage message. Does not implicitly {@link agent.CreateSecretResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.CreateSecretResponseMessage\n * @static\n * @param {agent.ICreateSecretResponseMessage} m CreateSecretResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n CreateSecretResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a CreateSecretResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.CreateSecretResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.CreateSecretResponseMessage} CreateSecretResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n CreateSecretResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.CreateSecretResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return CreateSecretResponseMessage;\n })();\n\n agent.DestroySecretRequestMessage = (function() {\n\n /**\n * Properties of a DestroySecretRequestMessage.\n * @memberof agent\n * @interface IDestroySecretRequestMessage\n * @property {string|null} [vaultName] DestroySecretRequestMessage vaultName\n * @property {string|null} [secretName] DestroySecretRequestMessage secretName\n */\n\n /**\n * Constructs a new DestroySecretRequestMessage.\n * @memberof agent\n * @classdesc Represents a DestroySecretRequestMessage.\n * @implements IDestroySecretRequestMessage\n * @constructor\n * @param {agent.IDestroySecretRequestMessage=} [p] Properties to set\n */\n function DestroySecretRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DestroySecretRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.DestroySecretRequestMessage\n * @instance\n */\n DestroySecretRequestMessage.prototype.vaultName = \"\";\n\n /**\n * DestroySecretRequestMessage secretName.\n * @member {string} secretName\n * @memberof agent.DestroySecretRequestMessage\n * @instance\n */\n DestroySecretRequestMessage.prototype.secretName = \"\";\n\n /**\n * Creates a new DestroySecretRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.DestroySecretRequestMessage\n * @static\n * @param {agent.IDestroySecretRequestMessage=} [properties] Properties to set\n * @returns {agent.DestroySecretRequestMessage} DestroySecretRequestMessage instance\n */\n DestroySecretRequestMessage.create = function create(properties) {\n return new DestroySecretRequestMessage(properties);\n };\n\n /**\n * Encodes the specified DestroySecretRequestMessage message. Does not implicitly {@link agent.DestroySecretRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DestroySecretRequestMessage\n * @static\n * @param {agent.IDestroySecretRequestMessage} m DestroySecretRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DestroySecretRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n if (m.secretName != null && Object.hasOwnProperty.call(m, \"secretName\"))\n w.uint32(18).string(m.secretName);\n return w;\n };\n\n /**\n * Decodes a DestroySecretRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DestroySecretRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DestroySecretRequestMessage} DestroySecretRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DestroySecretRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroySecretRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n case 2:\n m.secretName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DestroySecretRequestMessage;\n })();\n\n agent.DestroySecretResponseMessage = (function() {\n\n /**\n * Properties of a DestroySecretResponseMessage.\n * @memberof agent\n * @interface IDestroySecretResponseMessage\n * @property {boolean|null} [successful] DestroySecretResponseMessage successful\n */\n\n /**\n * Constructs a new DestroySecretResponseMessage.\n * @memberof agent\n * @classdesc Represents a DestroySecretResponseMessage.\n * @implements IDestroySecretResponseMessage\n * @constructor\n * @param {agent.IDestroySecretResponseMessage=} [p] Properties to set\n */\n function DestroySecretResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DestroySecretResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.DestroySecretResponseMessage\n * @instance\n */\n DestroySecretResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new DestroySecretResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.DestroySecretResponseMessage\n * @static\n * @param {agent.IDestroySecretResponseMessage=} [properties] Properties to set\n * @returns {agent.DestroySecretResponseMessage} DestroySecretResponseMessage instance\n */\n DestroySecretResponseMessage.create = function create(properties) {\n return new DestroySecretResponseMessage(properties);\n };\n\n /**\n * Encodes the specified DestroySecretResponseMessage message. Does not implicitly {@link agent.DestroySecretResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DestroySecretResponseMessage\n * @static\n * @param {agent.IDestroySecretResponseMessage} m DestroySecretResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DestroySecretResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a DestroySecretResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DestroySecretResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DestroySecretResponseMessage} DestroySecretResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DestroySecretResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DestroySecretResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DestroySecretResponseMessage;\n })();\n\n agent.GetSecretRequestMessage = (function() {\n\n /**\n * Properties of a GetSecretRequestMessage.\n * @memberof agent\n * @interface IGetSecretRequestMessage\n * @property {string|null} [vaultName] GetSecretRequestMessage vaultName\n * @property {string|null} [secretName] GetSecretRequestMessage secretName\n */\n\n /**\n * Constructs a new GetSecretRequestMessage.\n * @memberof agent\n * @classdesc Represents a GetSecretRequestMessage.\n * @implements IGetSecretRequestMessage\n * @constructor\n * @param {agent.IGetSecretRequestMessage=} [p] Properties to set\n */\n function GetSecretRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * GetSecretRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.GetSecretRequestMessage\n * @instance\n */\n GetSecretRequestMessage.prototype.vaultName = \"\";\n\n /**\n * GetSecretRequestMessage secretName.\n * @member {string} secretName\n * @memberof agent.GetSecretRequestMessage\n * @instance\n */\n GetSecretRequestMessage.prototype.secretName = \"\";\n\n /**\n * Creates a new GetSecretRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.GetSecretRequestMessage\n * @static\n * @param {agent.IGetSecretRequestMessage=} [properties] Properties to set\n * @returns {agent.GetSecretRequestMessage} GetSecretRequestMessage instance\n */\n GetSecretRequestMessage.create = function create(properties) {\n return new GetSecretRequestMessage(properties);\n };\n\n /**\n * Encodes the specified GetSecretRequestMessage message. Does not implicitly {@link agent.GetSecretRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.GetSecretRequestMessage\n * @static\n * @param {agent.IGetSecretRequestMessage} m GetSecretRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n GetSecretRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n if (m.secretName != null && Object.hasOwnProperty.call(m, \"secretName\"))\n w.uint32(18).string(m.secretName);\n return w;\n };\n\n /**\n * Decodes a GetSecretRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.GetSecretRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.GetSecretRequestMessage} GetSecretRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n GetSecretRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.GetSecretRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n case 2:\n m.secretName = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return GetSecretRequestMessage;\n })();\n\n agent.GetSecretResponseMessage = (function() {\n\n /**\n * Properties of a GetSecretResponseMessage.\n * @memberof agent\n * @interface IGetSecretResponseMessage\n * @property {Uint8Array|null} [secret] GetSecretResponseMessage secret\n */\n\n /**\n * Constructs a new GetSecretResponseMessage.\n * @memberof agent\n * @classdesc Represents a GetSecretResponseMessage.\n * @implements IGetSecretResponseMessage\n * @constructor\n * @param {agent.IGetSecretResponseMessage=} [p] Properties to set\n */\n function GetSecretResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * GetSecretResponseMessage secret.\n * @member {Uint8Array} secret\n * @memberof agent.GetSecretResponseMessage\n * @instance\n */\n GetSecretResponseMessage.prototype.secret = $util.newBuffer([]);\n\n /**\n * Creates a new GetSecretResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.GetSecretResponseMessage\n * @static\n * @param {agent.IGetSecretResponseMessage=} [properties] Properties to set\n * @returns {agent.GetSecretResponseMessage} GetSecretResponseMessage instance\n */\n GetSecretResponseMessage.create = function create(properties) {\n return new GetSecretResponseMessage(properties);\n };\n\n /**\n * Encodes the specified GetSecretResponseMessage message. Does not implicitly {@link agent.GetSecretResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.GetSecretResponseMessage\n * @static\n * @param {agent.IGetSecretResponseMessage} m GetSecretResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n GetSecretResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.secret != null && Object.hasOwnProperty.call(m, \"secret\"))\n w.uint32(10).bytes(m.secret);\n return w;\n };\n\n /**\n * Decodes a GetSecretResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.GetSecretResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.GetSecretResponseMessage} GetSecretResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n GetSecretResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.GetSecretResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.secret = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return GetSecretResponseMessage;\n })();\n\n agent.DeriveKeyRequestMessage = (function() {\n\n /**\n * Properties of a DeriveKeyRequestMessage.\n * @memberof agent\n * @interface IDeriveKeyRequestMessage\n * @property {string|null} [vaultName] DeriveKeyRequestMessage vaultName\n * @property {string|null} [keyName] DeriveKeyRequestMessage keyName\n * @property {string|null} [passphrase] DeriveKeyRequestMessage passphrase\n */\n\n /**\n * Constructs a new DeriveKeyRequestMessage.\n * @memberof agent\n * @classdesc Represents a DeriveKeyRequestMessage.\n * @implements IDeriveKeyRequestMessage\n * @constructor\n * @param {agent.IDeriveKeyRequestMessage=} [p] Properties to set\n */\n function DeriveKeyRequestMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DeriveKeyRequestMessage vaultName.\n * @member {string} vaultName\n * @memberof agent.DeriveKeyRequestMessage\n * @instance\n */\n DeriveKeyRequestMessage.prototype.vaultName = \"\";\n\n /**\n * DeriveKeyRequestMessage keyName.\n * @member {string} keyName\n * @memberof agent.DeriveKeyRequestMessage\n * @instance\n */\n DeriveKeyRequestMessage.prototype.keyName = \"\";\n\n /**\n * DeriveKeyRequestMessage passphrase.\n * @member {string} passphrase\n * @memberof agent.DeriveKeyRequestMessage\n * @instance\n */\n DeriveKeyRequestMessage.prototype.passphrase = \"\";\n\n /**\n * Creates a new DeriveKeyRequestMessage instance using the specified properties.\n * @function create\n * @memberof agent.DeriveKeyRequestMessage\n * @static\n * @param {agent.IDeriveKeyRequestMessage=} [properties] Properties to set\n * @returns {agent.DeriveKeyRequestMessage} DeriveKeyRequestMessage instance\n */\n DeriveKeyRequestMessage.create = function create(properties) {\n return new DeriveKeyRequestMessage(properties);\n };\n\n /**\n * Encodes the specified DeriveKeyRequestMessage message. Does not implicitly {@link agent.DeriveKeyRequestMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DeriveKeyRequestMessage\n * @static\n * @param {agent.IDeriveKeyRequestMessage} m DeriveKeyRequestMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DeriveKeyRequestMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.vaultName != null && Object.hasOwnProperty.call(m, \"vaultName\"))\n w.uint32(10).string(m.vaultName);\n if (m.keyName != null && Object.hasOwnProperty.call(m, \"keyName\"))\n w.uint32(18).string(m.keyName);\n if (m.passphrase != null && Object.hasOwnProperty.call(m, \"passphrase\"))\n w.uint32(26).string(m.passphrase);\n return w;\n };\n\n /**\n * Decodes a DeriveKeyRequestMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DeriveKeyRequestMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DeriveKeyRequestMessage} DeriveKeyRequestMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DeriveKeyRequestMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DeriveKeyRequestMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.vaultName = r.string();\n break;\n case 2:\n m.keyName = r.string();\n break;\n case 3:\n m.passphrase = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DeriveKeyRequestMessage;\n })();\n\n agent.DeriveKeyResponseMessage = (function() {\n\n /**\n * Properties of a DeriveKeyResponseMessage.\n * @memberof agent\n * @interface IDeriveKeyResponseMessage\n * @property {boolean|null} [successful] DeriveKeyResponseMessage successful\n */\n\n /**\n * Constructs a new DeriveKeyResponseMessage.\n * @memberof agent\n * @classdesc Represents a DeriveKeyResponseMessage.\n * @implements IDeriveKeyResponseMessage\n * @constructor\n * @param {agent.IDeriveKeyResponseMessage=} [p] Properties to set\n */\n function DeriveKeyResponseMessage(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * DeriveKeyResponseMessage successful.\n * @member {boolean} successful\n * @memberof agent.DeriveKeyResponseMessage\n * @instance\n */\n DeriveKeyResponseMessage.prototype.successful = false;\n\n /**\n * Creates a new DeriveKeyResponseMessage instance using the specified properties.\n * @function create\n * @memberof agent.DeriveKeyResponseMessage\n * @static\n * @param {agent.IDeriveKeyResponseMessage=} [properties] Properties to set\n * @returns {agent.DeriveKeyResponseMessage} DeriveKeyResponseMessage instance\n */\n DeriveKeyResponseMessage.create = function create(properties) {\n return new DeriveKeyResponseMessage(properties);\n };\n\n /**\n * Encodes the specified DeriveKeyResponseMessage message. Does not implicitly {@link agent.DeriveKeyResponseMessage.verify|verify} messages.\n * @function encode\n * @memberof agent.DeriveKeyResponseMessage\n * @static\n * @param {agent.IDeriveKeyResponseMessage} m DeriveKeyResponseMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n DeriveKeyResponseMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.successful != null && Object.hasOwnProperty.call(m, \"successful\"))\n w.uint32(8).bool(m.successful);\n return w;\n };\n\n /**\n * Decodes a DeriveKeyResponseMessage message from the specified reader or buffer.\n * @function decode\n * @memberof agent.DeriveKeyResponseMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {agent.DeriveKeyResponseMessage} DeriveKeyResponseMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n DeriveKeyResponseMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.agent.DeriveKeyResponseMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.successful = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n return DeriveKeyResponseMessage;\n })();\n\n return agent;\n})();\n\nmodule.exports = $root;\n","module.exports = require(\"protobufjs/minimal\");"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/lib/internal/daemon-script.js b/dist/lib/internal/daemon-script.js index f9faa2e455..27cb13abaf 100644 --- a/dist/lib/internal/daemon-script.js +++ b/dist/lib/internal/daemon-script.js @@ -1 +1,109 @@ -!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=1)}([function(e,t){e.exports=require("../polykey.js")},function(e,t,r){"use strict";r.r(t);var n=r(0);process.title="polykey-agent",new n.PolykeyAgent}]); \ No newline at end of file +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 1); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +module.exports = require("../polykey.js"); + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Polykey__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); +/* harmony import */ var _Polykey__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Polykey__WEBPACK_IMPORTED_MODULE_0__); + + +process.title = 'polykey-agent'; + +new _Polykey__WEBPACK_IMPORTED_MODULE_0__["PolykeyAgent"](); + + +/***/ }) +/******/ ]); \ No newline at end of file diff --git a/dist/lib/polykey.d.ts b/dist/lib/polykey.d.ts index bd260252ca..4bc68b6816 100644 --- a/dist/lib/polykey.d.ts +++ b/dist/lib/polykey.d.ts @@ -34,7 +34,7 @@ declare module 'polykey/src/lib/Polykey' { } declare module 'polykey/src/lib/agent/PolykeyAgent' { import PolykeyClient from 'polykey/src/lib/agent/PolykeyClient'; - import { PassThrough } from 'readable-stream'; + import { Duplex } from 'readable-stream'; class PolykeyAgent { private socketPath; private server; @@ -61,7 +61,7 @@ declare module 'polykey/src/lib/agent/PolykeyAgent' { private createSecret; private destroySecret; private getSecret; - static connectToAgent(getStream?: () => PassThrough): PolykeyClient; + static connectToAgent(getStream?: () => Duplex): PolykeyClient; static get SocketPath(): string; static get LogPath(): string; static DAEMON_SCRIPT_PATH: string; @@ -72,10 +72,10 @@ declare module 'polykey/src/lib/agent/PolykeyAgent' { } declare module 'polykey/src/lib/agent/PolykeyClient' { /// - import { PassThrough } from 'readable-stream'; + import { Duplex } from 'readable-stream'; class PolykeyClient { private getStream; - constructor(getStream: () => PassThrough); + constructor(getStream: () => Duplex); sendRequestToAgent(request: Uint8Array): Promise; private handleAgentCommunication; registerNode(path: string, passphrase: string): Promise; @@ -88,7 +88,7 @@ declare module 'polykey/src/lib/agent/PolykeyClient' { newVault(nodePath: string, vaultName: string): Promise; destroyVault(nodePath: string, vaultName: string): Promise; listSecrets(nodePath: string, vaultName: string): Promise; - createSecret(nodePath: string, vaultName: string, secretName: string, secretPath: string): Promise; + createSecret(nodePath: string, vaultName: string, secretName: string, secret: string | Buffer): Promise; destroySecret(nodePath: string, vaultName: string, secretName: string): Promise; getSecret(nodePath: string, vaultName: string, secretName: string): Promise; getAgentStatus(): Promise; @@ -804,13 +804,13 @@ declare module 'polykey/src/lib/vaults/Vault' { import { EncryptedFS } from 'encryptedfs'; class Vault { private key; - private keyLen; name: string; private efs; vaultPath: string; private secrets; private sharedPubKeys; private metadataPath; + private mutex; constructor(name: string, symKey: Buffer, baseDir: string); /** * Returns the Encrypted File System used for vault operations @@ -870,10 +870,7 @@ declare module 'polykey/src/lib/vaults/Vault' { * @param getSocket Function to get an active connection to provided address */ pullVault(gitClient: GitClient): Promise; - /** - * Initializes the git repository for new vaults - */ - initRepository(): Promise; + getVaultHistory(depth?: number): Promise; private writeMetadata; private loadMetadata; private commitChanges; diff --git a/dist/lib/polykey.js b/dist/lib/polykey.js index 08f716e7fc..0b3da04fac 100644 --- a/dist/lib/polykey.js +++ b/dist/lib/polykey.js @@ -1,2 +1,4061 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.polykey=t():e.polykey=t()}(this,(function(){return function(e){var t={};function s(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,s),a.l=!0,a.exports}return s.m=e,s.c=t,s.d=function(e,t,r){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(s.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)s.d(r,a,function(t){return e[t]}.bind(null,a));return r},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=4)}([function(e,t){e.exports=require("path")},function(e,t){e.exports=require("os")},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("readable-stream")},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(1)),i=r(s(20));t.KeyManager=i.default;const n=r(s(23));t.PeerManager=n.default;const o=r(s(43));t.VaultManager=o.default;const c=r(s(45));t.PolykeyAgent=c.default;const u=r(s(18));t.PolykeyClient=u.default;t.default=class{constructor(e=a.default.homedir()+"/.polykey",t,s,r,c){this.polykeyPath=e,this.keyManager=null!=s?s:new i.default(this.polykeyPath,t),this.vaultManager=null!=r?r:new o.default(this.polykeyPath,t,this.keyManager),this.peerManager=null!=c?c:new n.default(this.polykeyPath,t,this.keyManager,this.vaultManager)}}},function(e,t){e.exports=require("crypto")},function(e,t){e.exports=require("@grpc/grpc-js")},function(e,t){e.exports=require("../../proto/compiled/Git_grpc_pb")},function(e,t){e.exports=require("../../proto/compiled/Git_pb")},function(e,t,s){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=class{static flush(){return Buffer.from("0000","utf8")}static encode(e){"string"==typeof e&&(e=Buffer.from(e));const t=function(e,t){const s=t.toString(16);return"0".repeat(e-s.length)+s}(4,e.length+4);return Buffer.concat([Buffer.from(t,"utf8"),e])}static streamReader(e){return async function(){try{let t=await e.slice(4);if(null===t)return!0;if(t=parseInt(t.toString("utf8"),16),0===t)return null;let s=await e.slice(t-4);return null===s||s}catch(e){return console.log("error",e),!0}}}}},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(0)),i=r(s(27));function n(e,t){const s=e.replace(/\^\{\}$/,""),r=t.replace(/\^\{\}$/,""),a=-(sr);return 0===a?e.endsWith("^{}")?1:-1:a}const o=["config","description","index","shallow","commondir"];class c{static async packedRefs(e,t){const s=e.readFileSync(t+"/packed-refs",{encoding:"utf8"});return i.default.from(s).refs}static async listRefs(e,t,s){const r=c.packedRefs(e,t);let i=[];try{i=await async function e(t,s){return new Promise((r,i)=>{let n=[];s.promises.readdir(t).then(async i=>{var o=i.length;if(!o)return r(n);i.forEach((async function(i){i=a.default.resolve(t,i),s.promises.stat(i).then(async t=>{if(t&&t.isDirectory()){const t=await e(i,s);n=n.concat(t),--o||r(n)}else n.push(i),--o||r(n)})}))}).catch(e=>{if(e)return i(e)})})}(`${t}/${s}`,e),i=i.map(e=>e.replace(`${t}/${s}/`,""))}catch(e){i=[]}for(let e of(await r).keys())e.startsWith(s)&&(e=e.replace(s+"/",""),i.includes(e)||i.push(e));return i.sort(n),i}static async resolve(e,t,s,r){if(void 0!==r&&-1===--r)return s;if(s.startsWith("ref: "))return s=s.slice("ref: ".length),c.resolve(e,t,s,r);if(40===s.length&&/[0-9a-f]{40}/.test(s))return s;const a=await c.packedRefs(e,t),i=(e=>[""+e,"refs/"+e,"refs/tags/"+e,"refs/heads/"+e,"refs/remotes/"+e,`refs/remotes/${e}/HEAD`])(s).filter(e=>!o.includes(e));for(const s of i){const i=e.readFileSync(`${t}/${s}`,{encoding:"utf8"}).toString()||a.get(s);if(i)return c.resolve(e,t,i.trim(),r)}throw Error("RefNotFound")}}t.default=c},function(e,t){e.exports=require("pako")},function(e,t,s){"use strict";function r(e){return 0===e?e:-e}function a(e){let t=(s=r(e),Math.sign(s)||(Object.is(s,-0)?-1:1));var s;e=Math.abs(e);let a=Math.floor(e/60);e-=60*a;let i=String(a),n=String(e);return i.length<2&&(i="0"+i),n.length<2&&(n="0"+n),(-1===t?"-":"+")+i+n}function i(e){let[,t,s,a]=e.match(/(\+|-)(\d\d)(\d\d)/);return a=("+"===t?1:-1)*(60*Number(s)+Number(a)),r(a)}function n(e){let[,t,s,r,a]=e.match(/^(.*) <(.*)> (.*) (.*)$/);return{name:t,email:s,timestamp:Number(r),timezoneOffset:i(a)}}function o(e){return e=(e=(e=e.replace(/\r/g,"")).replace(/^\n+/,"")).replace(/\n+$/,"")+"\n"}function c(e){return e.trim().split("\n").map(e=>" "+e).join("\n")+"\n"}Object.defineProperty(t,"__esModule",{value:!0});class u{constructor(e){if("string"==typeof e)this._commit=e;else if(Buffer.isBuffer(e))this._commit=e.toString("utf8");else{if("object"!=typeof e)throw new Error("invalid type passed to GitCommit constructor");this._commit=u.render(e)}}static fromPayloadSignature({payload:e,signature:t}){let s=u.justHeaders(e),r=u.justMessage(e),a=o(s+"\ngpgsig"+c(t)+"\n"+r);return new u(a)}static from(e){return new u(e)}toObject(){return Buffer.from(this._commit,"utf8")}headers(){return this.parseHeaders()}message(){return u.justMessage(this._commit)}parse(){return Object.assign({message:this.message()},this.headers())}static justMessage(e){return o(e.slice(e.indexOf("\n\n")+2))}static justHeaders(e){return e.slice(0,e.indexOf("\n\n"))}parseHeaders(){let e=u.justHeaders(this._commit).split("\n"),t=[];for(let s of e)" "===s[0]?t[t.length-1]+="\n"+s.slice(1):t.push(s);let s={parent:[]};for(let e of t){let t=e.slice(0,e.indexOf(" ")),r=e.slice(e.indexOf(" ")+1);Array.isArray(s[t])?s[t].push(r):s[t]=r}return s.author&&(s.author=n(s.author)),s.committer&&(s.committer=n(s.committer)),s}static renderHeaders(e){let t="";if(e.tree?t+=`tree ${e.tree}\n`:t+="tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n",e.parent){if(void 0===e.parent.length)throw new Error("commit 'parent' property should be an array");for(let s of e.parent)t+=`parent ${s}\n`}let s=e.author;t+=`author ${s.name} <${s.email}> ${s.timestamp} ${a(s.timezoneOffset)}\n`;let r=e.committer||e.author;return t+=`committer ${r.name} <${r.email}> ${r.timestamp} ${a(r.timezoneOffset)}\n`,e.gpgsig&&(t+="gpgsig"+c(e.gpgsig)),t}static render(e){return u.renderHeaders(e)+"\n"+o(e.message)}render(){return this._commit}withoutSignature(){let e=o(this._commit);return-1===e.indexOf("\ngpgsig")?e:o(e.slice(0,e.indexOf("\ngpgsig"))+"\n"+e.slice(e.indexOf("-----END PGP SIGNATURE-----\n")+"-----END PGP SIGNATURE-----\n".length))}isolateSignature(){let e=this._commit.slice(this._commit.indexOf("-----BEGIN PGP SIGNATURE-----"),this._commit.indexOf("-----END PGP SIGNATURE-----")+"-----END PGP SIGNATURE-----".length);return e.split("\n").map(e=>e.replace(/^ /,"")).join("\n")}}t.default=u},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(2)),i=r(s(11)),n=r(s(0)),o=r(s(32)),c=new Map;class u{static async read(e,t,s,r="content"){let l=e.readFileSync(`${t}/objects/${s.slice(0,2)}/${s.slice(2)}`),d=`./objects/${s.slice(0,2)}/${s.slice(2)}`;if(!l){const r=s=>u.read(e,t,s);let i=a.default.readdirSync(n.default.join(t,"/objects/pack"));i=i.filter(e=>e.endsWith(".pack"));for(let a of i){let i=c.get(a);if(i.offsets.has(s)){if(!i.pack){const s=e.readFileSync(`${t}/objects/pack/${a}`);await i.load({pack:s})}let n=await i.read({oid:s,getExternalRefDelta:r});return n.source="./objects/pack/"+a,n}}}if(!l){let r=e.readFileSync(t+"/shallow",{encoding:"utf8"});if(null!==r&&r.includes(s))throw new Error("ReadShallowObjectFail: "+s)}if(!l)throw new Error("ReadObjectFail: "+s);if("deflated"===r)return{format:"deflated",object:l,source:d};let f=Buffer.from(i.default.inflate(l));if("wrapped"===r)return{format:"wrapped",object:f,source:d};let{type:h,object:y}=o.default.unwrap({oid:s,buffer:f});return"content"===r?{type:h,format:"content",object:y,source:d}:void 0}}t.default=u},function(e,t,s){"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(e,t){this.ip=e,this.port=t}static parse(e){const t=e.split(":"),s=t[0],a=t[1];return new r(s,a)}static fromAddressInfo(e){const t="::"==e.address?"localhost":e.address;return new r(t,e.port.toString())}toString(){return`${this.ip}:${this.port}`}}t.Address=r,r.prototype.toString=function(){return`${this.ip}:${this.port}`};t.default=class{constructor(e,t=[],s){this.publicKey=e,this.addresses=new Set(t.map(e=>r.parse(e))),this.connectedAddr=s?r.parse(s):void 0}connect(e){this.addresses.has(e)||this.addresses.add(e),this.connectedAddr=e}disconnect(){this.connectedAddr=void 0}get AdressStringList(){return Array.from(this.addresses.values()).map(e=>e.toString())}}},function(e,t){e.exports=require("isomorphic-git")},function(e,t){e.exports=require("encryptedfs")},function(e,t){e.exports=require("virtualfs")},function(e,t,s){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=s(19),{AgentMessage:a,CreateSecretRequestMessage:i,CreateSecretResponseMessage:n,DeriveKeyRequestMessage:o,DeriveKeyResponseMessage:c,DestroySecretRequestMessage:u,DestroySecretResponseMessage:l,DestroyVaultRequestMessage:d,DestroyVaultResponseMessage:f,ErrorMessage:h,GetSecretRequestMessage:y,GetSecretResponseMessage:p,ListNodesRequestMessage:m,ListNodesResponseMessage:g,ListSecretsRequestMessage:w,ListSecretsResponseMessage:P,ListVaultsRequestMessage:S,ListVaultsResponseMessage:v,NewNodeRequestMessage:k,NewNodeResponseMessage:b,NewVaultRequestMessage:M,NewVaultResponseMessage:_,RegisterNodeRequestMessage:E,RegisterNodeResponseMessage:K,SignFileRequestMessage:R,SignFileResponseMessage:x,Type:j,VerifyFileRequestMessage:I,VerifyFileResponseMessage:A}=r.agent;t.default=class{constructor(e){this.getStream=e}async sendRequestToAgent(e){const t=this.getStream(),s=await new Promise((s,r)=>{try{const a=[];t.on("data",e=>{a.push(e)}),t.on("error",e=>{r(e)}),t.on("end",()=>{s(a)}),t.write(e)}catch(e){r(e)}});return t.end(),s}async handleAgentCommunication(e,t,s){const r=a.encode({type:e,isResponse:!1,nodePath:t,subMessage:s}).finish(),i=await this.sendRequestToAgent(r),n=[];for(const e of i){const{subMessage:t,type:s}=a.decode(e);if(s==j.ERROR){const{error:e}=h.decode(t);throw new Error(e)}n.push(a.decode(e))}return n}async registerNode(e,t){const s=E.encode({passphrase:t}).finish(),r=await this.handleAgentCommunication(j.REGISTER_NODE,e,s);if(0==r.length)throw Error("agent did not respond");const{successful:a}=K.decode(r[0].subMessage);return a}async newNode(e,t,s,r,a){const i=k.encode({name:t,email:s,passphrase:r,nbits:a}).finish(),n=await this.handleAgentCommunication(j.NEW_NODE,e,i);if(0==n.length)throw Error("agent did not respond");const{successful:o}=b.decode(n[0].subMessage);return o}async listNodes(e=!0){const t=m.encode({unlockedOnly:e}).finish(),s=await this.handleAgentCommunication(j.LIST_NODES,void 0,t);if(0==s.length)throw Error("agent did not respond");const{nodes:r}=g.decode(s[0].subMessage);return r}async deriveKey(e,t,s){const r=o.encode({keyName:t,passphrase:s}).finish(),a=await this.handleAgentCommunication(j.DERIVE_KEY,e,r);if(0==a.length)throw Error("agent did not respond");const{successful:i}=c.decode(a[0].subMessage);return i}async signFile(e,t,s,r){const a=R.encode({filePath:t,privateKeyPath:s,passphrase:r}).finish(),i=await this.handleAgentCommunication(j.SIGN_FILE,e,a);if(0==i.length)throw Error("agent did not respond");const{signaturePath:n}=x.decode(i[0].subMessage);return n}async verifyFile(e,t,s){const r=I.encode({filePath:t,signaturePath:s}).finish(),a=await this.handleAgentCommunication(j.VERIFY_FILE,e,r);if(0==a.length)throw Error("agent did not respond");const{verified:i}=A.decode(a[0].subMessage);return i}async listVaults(e){const t=await this.handleAgentCommunication(j.LIST_VAULTS,e);if(0==t.length)throw Error("agent did not respond");const{vaultNames:s}=v.decode(t[0].subMessage);return s}async newVault(e,t){const s=M.encode({vaultName:t}).finish(),r=await this.handleAgentCommunication(j.NEW_VAULT,e,s);if(0==r.length)throw Error("agent did not respond");const{successful:a}=_.decode(r[0].subMessage);return a}async destroyVault(e,t){const s=d.encode({vaultName:t}).finish(),r=await this.handleAgentCommunication(j.DESTROY_VAULT,e,s);if(0==r.length)throw Error("agent did not respond");const{successful:a}=f.decode(r[0].subMessage);return a}async listSecrets(e,t){const s=w.encode({vaultName:t}).finish(),r=await this.handleAgentCommunication(j.LIST_SECRETS,e,s);if(0==r.length)throw Error("agent did not respond");const{secretNames:a}=P.decode(r[0].subMessage);return a}async createSecret(e,t,s,r){const a=i.encode({vaultName:t,secretName:s,secretPath:r}).finish(),o=await this.handleAgentCommunication(j.CREATE_SECRET,e,a);if(0==o.length)throw Error("agent did not respond");const{successful:c}=n.decode(o[0].subMessage);return c}async destroySecret(e,t,s){const r=u.encode({vaultName:t,secretName:s}).finish(),a=await this.handleAgentCommunication(j.DESTROY_SECRET,e,r);if(0==a.length)throw Error("agent did not respond");const{successful:i}=l.decode(a[0].subMessage);return i}async getSecret(e,t,s){const r=y.encode({vaultName:t,secretName:s}).finish(),a=await this.handleAgentCommunication(j.GET_SECRET,e,r);if(0==a.length)throw Error("agent did not respond");const{secret:i}=p.decode(a[0].subMessage);return Buffer.from(i)}async getAgentStatus(){try{const e=await this.handleAgentCommunication(j.STATUS);if(0==e.length)throw Error("agent did not respond");return e[0].subMessage.toString()}catch(e){return"stopped"}}async stopAgent(){try{return await this.handleAgentCommunication(j.STOP_AGENT),!0}catch(e){return"online"!=await this.getAgentStatus()}}}},function(e,t){e.exports=require("../../proto/js/Agent")},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(1)),i=r(s(2)),n=r(s(0)),o=r(s(21)),c=r(s(5)),u=s(22);t.default=class{constructor(e=a.default.homedir()+"/.polykey",t,s=!1,r){this.primaryKeyPair={private:null,public:null},this.metadata={privateKeyPath:null,publicKeyPath:null,pkiKeyPath:null,pkiCertPath:null,caCertPath:null},this.pkiInfo={key:null,cert:null,caCert:null},this.useWebWorkers=s,this.workerPool=r,this.derivedKeys=new Map,this.fileSystem=t,this.polykeyPath=e,this.keypairPath=n.default.join(e,".keypair"),this.fileSystem.existsSync(this.keypairPath)||this.fileSystem.mkdirSync(this.keypairPath,{recursive:!0}),this.metadataPath=n.default.join(this.keypairPath,"metadata"),this.loadMetadata(),this.metadata.privateKeyPath&&this.metadata.publicKeyPath&&this.loadKeyPair(this.metadata.publicKeyPath,this.metadata.privateKeyPath),this.metadata.pkiKeyPath&&(this.pkiInfo.key=i.default.readFileSync(this.metadata.pkiKeyPath)),this.metadata.pkiCertPath&&(this.pkiInfo.cert=i.default.readFileSync(this.metadata.pkiCertPath)),this.metadata.caCertPath&&(this.pkiInfo.caCert=i.default.readFileSync(this.metadata.caCertPath)),this.loadPKIInfo(this.pkiInfo.key,this.pkiInfo.cert,this.pkiInfo.caCert,!0)}get identityLoaded(){return!!this.primaryIdentity}async generateKeyPair(e,t,s,r=4096,a=!1,i){if(r<1024)throw new Error("nbits must be greater than 1024 for keypair generation");const c=o.default.const.openpgp,l={asp:i?new o.default.ASP({progress_hook:i}):void 0,userid:`${e} <${t}>`,primary:{nbits:r,flags:c.certify_keys|c.sign_data|c.auth|c.encrypt_comm|c.encrypt_storage,expire_in:0},subkeys:[]},d=await u.promisify(o.default.KeyManager.generate)(l);await u.promisify(d.sign.bind(d))({});const f=await u.promisify(d.export_pgp_public.bind(d))({}),h={private:await u.promisify(d.export_pgp_private.bind(d))({passphrase:s}),public:f};if(a){this.primaryKeyPair=h,this.primaryIdentity=d;const e=n.default.join(this.keypairPath,"private_key"),t=n.default.join(this.keypairPath,"public_key");await this.fileSystem.promises.writeFile(e,h.private),await this.fileSystem.promises.writeFile(t,h.public),this.metadata.privateKeyPath=e,this.metadata.publicKeyPath=t,this.writeMetadata()}return h}getKeyPair(){return this.primaryKeyPair}hasPublicKey(){return!!this.primaryKeyPair.public}getPublicKey(){if(!this.primaryKeyPair.public)throw new Error("Public key does not exist in memory");return this.primaryKeyPair.public}getPrivateKey(){if(!this.primaryKeyPair.private)throw new Error("Private key does not exist in memory");return this.primaryKeyPair.private}loadKeyPair(e,t){this.loadPrivateKey(t),this.loadPublicKey(e)}loadPrivateKey(e){let t;"string"==typeof e?(t=this.fileSystem.readFileSync(e),this.metadata.privateKeyPath=e,this.writeMetadata()):t=e,this.primaryKeyPair.private=t.toString()}loadPublicKey(e){let t;"string"==typeof e?(t=this.fileSystem.readFileSync(e),this.metadata.publicKeyPath=e,this.writeMetadata()):t=e,this.primaryKeyPair.public=t.toString()}async unlockIdentity(e){const t=this.getPublicKey(),s=this.getPrivateKey(),r=await u.promisify(o.default.KeyManager.import_from_armored_pgp)({armored:t});await u.promisify(r.merge_pgp_private.bind(r))({armored:s}),r.is_pgp_locked.bind(r)()&&await u.promisify(r.unlock_pgp.bind(r))({passphrase:e}),this.primaryIdentity=r}exportPrivateKey(e){this.fileSystem.writeFileSync(e,this.primaryKeyPair.private),this.metadata.privateKeyPath=e,this.writeMetadata()}exportPublicKey(e){this.fileSystem.writeFileSync(e,this.primaryKeyPair.public),this.metadata.publicKeyPath=e,this.writeMetadata()}generateKeySync(e,t){const s=c.default.randomBytes(32);return this.derivedKeys[e]=c.default.pbkdf2Sync(t,s,1e4,32,"sha256"),this.derivedKeys[e]}async generateKey(e,t){const s=c.default.randomBytes(32);return this.derivedKeys[e]=await u.promisify(c.default.pbkdf2)(t,s,1e4,32,"sha256"),this.derivedKeys[e]}importKeySync(e,t){this.derivedKeys[e]="string"==typeof t?this.fileSystem.readFileSync(t):t}async importKey(e,t){this.derivedKeys[e]="string"==typeof t?await this.fileSystem.promises.readFile(t):t}exportKeySync(e,t,s){if(!this.derivedKeys.has(e))throw Error("There is no key loaded for name: "+e);s&&this.fileSystem.mkdirSync(n.default.dirname(t),{recursive:!0}),this.fileSystem.writeFileSync(t,this.derivedKeys[e])}async exportKey(e,t,s){if(!this.derivedKeys.has(e))throw Error("There is no key loaded for name: "+e);s&&await this.fileSystem.promises.mkdir(n.default.dirname(t),{recursive:!0}),await this.fileSystem.promises.writeFile(t,this.derivedKeys[e])}async getIdentityFromPublicKey(e){return await u.promisify(o.default.KeyManager.import_from_armored_pgp)({armored:e})}async getIdentityFromPrivateKey(e,t){const s=await u.promisify(o.default.KeyManager.import_from_armored_pgp)({armored:e});return s.is_pgp_locked()&&await u.promisify(s.unlock_pgp)({passphrase:t}),s}async signData(e,t,s){let r;if(t){if(!s)throw new Error("passphrase for private key was not provided");r=await this.getIdentityFromPrivateKey(t,s)}else{if(!this.primaryIdentity)throw new Error("key pair is not loaded");r=this.primaryIdentity}if(this.useWebWorkers&&this.workerPool){return await this.workerPool.queue(async t=>await t.signData(e,r))}{const t={msg:e.toString(),sign_with:r},s=await u.promisify(o.default.box)(t);return Buffer.from(s)}}async signFile(e,t,s){let r;t&&(r="string"==typeof t?this.fileSystem.readFileSync(t):t);const a=this.fileSystem.readFileSync(e),i=await this.signData(a,r,s),n=e+".sig";return this.fileSystem.writeFileSync(n,i),n}async verifyData(e,t,s){const r=new o.default.keyring.KeyRing;let a;if(s)a=await this.getIdentityFromPublicKey(s);else{if(!this.primaryIdentity)throw new Error("key pair is not loaded");a=this.primaryIdentity}if(r.add_key_manager(a),this.useWebWorkers&&this.workerPool){return await this.workerPool.queue(async s=>await s.verifyData(e,t,a))}{const s={armored:t,data:e,keyfetch:r};let a,i=(await u.promisify(o.default.unbox)(s))[0].get_data_signer();return i&&(a=i.get_key_manager()),!!a&&!!a.get_pgp_fingerprint()}}async verifyFile(e,t,s){let r;s&&(r="string"==typeof s?this.fileSystem.readFileSync(s):s);const a=this.fileSystem.readFileSync(e),i=this.fileSystem.readFileSync(t);return await this.verifyData(a,i,r)}async encryptData(e,t){let s;if(t)s=await this.getIdentityFromPublicKey(t);else{if(!this.primaryIdentity)throw new Error("Identity could not be resolved for encrypting");s=this.primaryIdentity}if(this.useWebWorkers&&this.workerPool){return await this.workerPool.queue(async t=>await t.encryptData(e,s))}{const t={msg:e,encrypt_for:s};return await u.promisify(o.default.box)(t)}}async decryptData(e,t,s){var r=new o.default.keyring.KeyRing;let a;if(t){if(!s)throw new Error("A key passphrase must be supplied if a privateKey is specified");a=await this.getIdentityFromPrivateKey(t,s)}else{if(!this.primaryIdentity)throw Error("no identity available for decrypting");a=this.primaryIdentity}if(this.useWebWorkers&&this.workerPool){return await this.workerPool.queue(async t=>await t.decryptData(e,a))}{r.add_key_manager(a);const t={armored:e.toString(),keyfetch:r},s=await u.promisify(o.default.unbox)(t);return Buffer.from(s[0].toString())}}get PKIInfo(){return this.pkiInfo}loadPKIInfo(e,t,s,r=!1){if(e&&(this.pkiInfo.key=e),t&&(this.pkiInfo.cert=t),s&&(this.pkiInfo.caCert=s),r){const r=n.default.dirname(this.metadataPath);e&&(this.metadata.pkiKeyPath=n.default.join(r,"pki_private_key"),i.default.writeFileSync(this.metadata.pkiKeyPath,e)),t&&(this.metadata.pkiCertPath=n.default.join(r,"pki_cert"),i.default.writeFileSync(this.metadata.pkiCertPath,t)),s&&(this.metadata.caCertPath=n.default.join(r,"ca_cert"),i.default.writeFileSync(this.metadata.caCertPath,s))}}getKey(e){return this.derivedKeys[e]}hasKey(e){return!!this.derivedKeys[e]}writeMetadata(){const e=JSON.stringify(this.metadata);this.fileSystem.writeFileSync(this.metadataPath,e)}loadMetadata(){if(this.fileSystem.existsSync(this.metadataPath)){const e=this.fileSystem.readFileSync(this.metadataPath).toString();this.metadata=JSON.parse(e)}}}},function(e,t){e.exports=require("kbpgp")},function(e,t){e.exports=require("util")},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var s in e)Object.hasOwnProperty.call(e,s)&&(t[s]=e[s]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(1)),n=r(s(0)),o=a(s(6)),c=r(s(24)),u=r(s(25)),l=s(37),d=s(38),f=a(s(14)),h=r(s(39)),y=s(7),p=s(8),m={name:"Keybase",findUser:async(e,t)=>{const s=`https://keybase.io/_/api/1.0/user/lookup.json?${t}=${e}`;try{const e=await fetch(s);return(await e.json()).them[0].public_keys.primary.bundle}catch(e){throw new Error("User was not found: "+e.message)}}};t.default=class{constructor(e=i.default.homedir()+"/.polykey",t,s,r,a,c=[]){var l;this.metadata={localPeerInfo:null},this.serverStarted=!1,this.fileSystem=t,this.fileSystem.mkdirSync(e,{recursive:!0}),this.metadataPath=n.default.join(e,".peerMetadata"),this.keyManager=s,this.socialDiscoveryServices=c,this.loadMetadata(),a?(this.localPeerInfo=a,this.writeMetadata()):this.metadata.localPeerInfo?this.localPeerInfo=this.metadata.localPeerInfo:this.keyManager.hasPublicKey()&&(this.localPeerInfo=new f.default(this.keyManager.getPublicKey())),this.peerStore=new Map,this.socialDiscoveryServices=[],this.socialDiscoveryServices.push(m);for(const e of c)this.socialDiscoveryServices.push(e);this.multicastBroadcaster=new h.default(this.addPeer,this.localPeerInfo,this.keyManager),this.peerConnections=new Map,this.gitBackend=new u.default(e,r),this.server=new o.Server,this.server.addService(y.GitServerService,{requestInfo:this.requestInfo.bind(this),requestPack:this.requestPack.bind(this)});this.keyManager.PKIInfo;this.credentials=o.ServerCredentials.createInsecure(),this.server.bindAsync("0.0.0.0:"+(null!==(l=process.env.PK_PORT)&&void 0!==l?l:0),this.credentials,(e,t)=>{if(e)throw e;{const e=new f.Address("localhost",t.toString());this.server.start(),this.localPeerInfo.connect(e),this.serverStarted=!0}})}async requestInfo(e,t){const s=e.request.getVaultname(),r=new p.InfoReply;r.setVaultname(s),r.setBody(await this.gitBackend.handleInfoRequest(s)),t(null,r)}async requestPack(e,t){const s=e.request,r=s.getVaultname(),a=Buffer.from(s.getBody_asB64(),"base64"),i=new p.PackReply;i.setVaultname(r),i.setBody(await this.gitBackend.handlePackRequest(r,a)),t(null,i)}getLocalPeerInfo(){return this.localPeerInfo}connectLocalPeerInfo(e){this.localPeerInfo.connect(e)}addPeer(e){this.peerStore.set(e.publicKey,e)}getPeer(e){var t;return null!==(t=this.peerStore.get(e))&&void 0!==t?t:null}hasPeer(e){return this.peerStore.has(e)}async findPubKey(e){return new Promise((t,s)=>{this.multicastBroadcaster.requestPeerContact(e),this.multicastBroadcaster.on("found",s=>{s.publicKey==e&&t(s)}),this.multicastBroadcaster.on("timeout",t=>{t==e&&s("The broadcaster stopped looking")})})}async findSocialUser(e,t){const s=[];for(const r of this.socialDiscoveryServices)try{s.push(r.findUser(e,t))}catch(e){console.log("Could not find user on this discovery service: "+r.name)}const r=await d.firstPromiseFulfilled(s);if(r.length>1)throw new Error("Could not find public key from services");const a=r[0];return await this.findPubKey(a)}connectToPeer(e){var t;if(e==this.localPeerInfo.connectedAddr||e==this.localPeerInfo.publicKey)throw new Error("Cannot connect to self");let s;if("string"==typeof e){const r=this.peerConnections.get(e);if(r)return r;const a=null===(t=this.getPeer(e))||void 0===t?void 0:t.connectedAddr;if(!a)throw new Error("Peer does not exist in peer store");s=a}else s=e;const r=new c.default(s,this.keyManager);return"string"==typeof e&&this.peerConnections.set(e,r),r}writeMetadata(){var e;const t=this.localPeerInfo,s=l.peer.PeerInfoMessage.encode({addresses:t.AdressStringList,connectedAddr:null===(e=t.connectedAddr)||void 0===e?void 0:e.toString(),pubKey:t.publicKey}).finish();this.fileSystem.writeFileSync(this.metadataPath,s)}loadMetadata(){if(this.fileSystem.existsSync(this.metadataPath)){const e=this.fileSystem.readFileSync(this.metadataPath),{addresses:t,connectedAddr:s,pubKey:r}=l.peer.PeerInfoMessage.decode(e);this.localPeerInfo=new f.default(r,t,s)}}}},function(e,t,s){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var s in e)Object.hasOwnProperty.call(e,s)&&(t[s]=e[s]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(6)),i=s(7),n=s(8);t.default=class{constructor(e,t){this.credentials=a.credentials.createInsecure(),this.client=new i.GitServerClient(e.toString(),this.credentials)}async request({url:e,method:t,headers:s,body:r,onProgress:a}){return new Promise(async(a,i)=>{const n=new URL(e);if("GET"==t){const r=n.pathname.match(/\/(.+)\/info\/refs$/);r&&!/\.\./.test(r[1])||i(new Error("Error"));const o=r[1],c=await this.requestInfo(o);a({url:e,method:t,statusCode:200,statusMessage:"OK",body:this.iteratorFromData(c),headers:s})}else if("POST"==t){const o=n.pathname.match(/\/(.+)\/git-(.+)/);o&&!/\.\./.test(o[1])||i(new Error("Error"));const c=o[1],u=await this.requestPack(c,r[0]);a({url:e,method:t,statusCode:200,statusMessage:"OK",body:this.iteratorFromData(u),headers:s})}else i(new Error("Method not supported"))})}async requestInfo(e){return new Promise((t,s)=>{const r=new n.InfoRequest;r.setVaultname(e),this.client.requestInfo(r,(function(e,r){e?s(e):t(Buffer.from(r.getBody_asB64(),"base64"))}))})}async requestPack(e,t){return new Promise((s,r)=>{const a=new n.PackRequest;a.setVaultname(e),a.setBody(t),this.client.requestPack(a,(function(e,t){e?r(e):s(Buffer.from(t.getBody_asB64(),"base64"))}))})}iteratorFromData(e){let t=!1;return{next:()=>new Promise((s,r)=>{if(t)return s({done:!0});t=!0,s({value:e,done:!1})})}}}},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(0)),i=s(3),n=r(s(26)),o=r(s(28)),c=r(s(30));t.default=class{constructor(e,t){this.polykeyPath=e,this.vaultManager=t}exists(e,t){try{const s=this.vaultManager.getVault(e);return!!s&&s.peerCanAccess(t)}catch(e){return!1}}async handleInfoRequest(e){var t;const s=[];if(!this.exists(e,""))throw new Error("Vault does not exist");{s.push(Buffer.from(this.createGitPacketLine("# service=git-upload-pack\n"))),s.push(Buffer.from("0000"));const r=null===(t=this.vaultManager.getVault(e))||void 0===t?void 0:t.EncryptedFS,i=await n.default(r,a.default.join(this.polykeyPath,e),void 0,!0),o=null!=i?i:[];s.push(...o)}return Buffer.concat(s)}async handlePackRequest(e,t){return new Promise(async(s,r)=>{var n;const u=[];if(!this.exists(e,""))throw new Error("Vault does not exist");const l=null===(n=this.vaultManager.getVault(e))||void 0===n?void 0:n.EncryptedFS;if(l&&"want"==t.toString().slice(4,8)){const n=t.toString().slice(9,49),d=await c.default(l,a.default.join(this.polykeyPath,e),[n],void 0);u.push(Buffer.from("0008NAK\n"));const f=new i.PassThrough,h=new i.PassThrough,y=o.default.mux("side-band-64",f,d.packstream,h,[]);y.on("data",e=>{u.push(e)}),y.on("end",()=>{s(Buffer.concat(u))}),y.on("error",e=>{r(e)}),h.write(Buffer.from("0014progress is at 50%\n")),h.end()}})}createGitPacketLine(e){const t=(4+e.length).toString(16);return Array(4-t.length+1).join("0")+t+e}}},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(0)),i=r(s(9)),n=r(s(10));t.default=async function(e,t,s=a.default.join(t,".git"),r=!1){try{if(r){const t=["side-band-64k"];let r=await n.default.listRefs(e,s,"refs");r=r.map(e=>"refs/"+e);const a={};r.unshift("HEAD");for(const t of r)a[t]=await n.default.resolve(e,s,t);const o={};return o.HEAD=await n.default.resolve(e,s,"HEAD",2),async function({capabilities:e,refs:t,symrefs:s}){const r=[];let a="";for(const[e,t]of Object.entries(s))a+=`symref=${e}:${t} `;let n=`\0${[...e].join(" ")} ${a}agent=git/isomorphic-git@1.4.0`;for(const[e,s]of Object.entries(t))r.push(i.default.encode(`${s} ${e}${n}\n`)),n="";return r.push(i.default.flush()),r}({capabilities:t,refs:a,symrefs:o})}}catch(e){throw e.caller="git.uploadPack",e}}},function(e,t,s){"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(e){if(this.refs=new Map,this.parsedConfig=[],e){let t;this.parsedConfig=e.trim().split("\n").map(e=>{if(/^\s*#/.test(e))return{line:e,comment:!0};const s=e.indexOf(" ");if(e.startsWith("^")){const s=e.slice(1);return this.refs.set(t+"^{}",s),{line:e,ref:t,peeled:s}}{const r=e.slice(0,s);return t=e.slice(s+1),this.refs.set(t,r),{line:e,ref:t,oid:r}}})}return this}static from(e){return new r(e)}}t.default=r},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=s(29),i=s(3),n=r(s(9));function o(e,t){const s=[];let r=0;for(;r{null===e?l.write(n.default.flush()):l.write(n.default.encode(e))});let d=!0,f=!1,h=!1,y=a.Buffer.concat([n.default.encode(a.Buffer.from("010A","hex")),n.default.flush()]);return s.on("data",e=>{d=!1;const t=o(e,u);for(const e of t)l.write(n.default.encode(a.Buffer.concat([a.Buffer.from("01","hex"),e])))}).on("end",()=>{f=!0,d||l.write(y),h&&l.end()}),r.on("data",e=>{const t=o(e,u);for(const e of t)l.write(n.default.encode(a.Buffer.concat([a.Buffer.from("02","hex"),e])))}).on("end",()=>{h=!0,f&&l.end()}),l}}},function(e,t){e.exports=require("buffer")},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(11)),i=r(s(0)),n=r(s(31)),o=r(s(35)),c=r(s(36)),u=r(s(12)),l=s(3),d=r(s(13)),f={commit:16,tree:32,blob:48,tag:64,ofs_delta:96,ref_delta:112};async function h(e,t,s=i.default.join(t,".git"),r){let a=new Set,n=new Set,c=new Set;async function l(t){let{type:r,object:i}=await d.default.read(e,s,t);if("commit"===r){a.add(t);let e=u.default.from(i).headers().tree;await l(e)}else if("tree"===r){n.add(t);let e=o.default.from(i);for(let t of e)"blob"===t.type&&c.add(t.oid),"tree"===t.type&&await l(t.oid)}}for(let e of r)await l(e);return[...a,...n,...c]}async function y(e,t,s=i.default.join(t,".git"),r,n){let o=c.default("sha1");function u(e,t){t?n.write(e,t):n.write(e),o.update(e,t)}function l(e,t){let s,r,i,n=f[t];if(void 0===n)throw new Error("Unrecognized type: "+t);i=e.length,r=i>15?128:0,s=15&i,i>>>=4;let o=(r|n|s).toString(16);for(u(o,"hex");r;){r=i>127?128:0,o=r|127&i;const e=o.toString(16);u("0".repeat(2-e.length)+e,"hex"),i>>>=7}u(Buffer.from(a.default.deflate(e)))}u("PACK"),u("00000002","hex");const h=r.length.toString(16);u("0".repeat(8-h.length)+h,"hex");for(let t of r){let{type:r,object:a}=await d.default.read(e,s,t);l(a,r)}let y=o.digest();return n.end(y),n}t.listObjects=h,t.pack=y,t.default=async function(e,t,s,r,a){const o=i.default.join(t,".git");let c=new Set,u=new Set,d=new Set,f=[];a=a||[];for(const i of s)try{let s=await n.default(e,t,o,void 0,i,r,void 0),l=[];for(let e=0;ee.oid).includes(r.oid)||f.push(r)}if(0===f.length)break;f.sort(u)}return a}catch(e){throw e.caller="git.log",e}}},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(33));t.default=class{static hash({type:e,object:t}){let s=Buffer.concat([Buffer.from(`${e} ${t.byteLength.toString()}\0`),Buffer.from(t)]);return a.default(s)}static wrap({type:e,object:t}){let s=Buffer.concat([Buffer.from(`${e} ${t.byteLength.toString()}\0`),t]);return{oid:a.default(s),buffer:s}}static unwrap({oid:e,buffer:t}){if(e){let s=a.default(t);if(s!==e)throw new Error(`SHA check failed! Expected ${e}, computed ${s}`)}let s=t.indexOf(32),r=t.indexOf(0),i=t.slice(0,s).toString("utf8"),n=t.slice(s+1,r).toString("utf8"),o=t.length-(r+1);if(parseInt(n)!==o)throw new Error(`Length mismatch: expected ${n} bytes but got ${o} instead.`);return{type:i,object:Buffer.from(t.slice(r+1))}}}},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(34));t.default=function(e){return(new a.default).update(e).digest("hex")}},function(e,t){e.exports=require("sha.js/sha1")},function(e,t,s){"use strict";function r(e){return!e.oid&&e.sha&&(e.oid=e.sha),e.mode=function(e){if("number"==typeof e&&(e=e.toString(8)),e.match(/^0?4.*/))return"40000";if(e.match(/^1006.*/))return"100644";if(e.match(/^1007.*/))return"100755";if(e.match(/^120.*/))return"120000";if(e.match(/^160.*/))return"160000";throw new Error("Could not understand file mode: "+e)}(e.mode),e.type||(e.type="blob"),e}Object.defineProperty(t,"__esModule",{value:!0});class a{constructor(e){if(Buffer.isBuffer(e))this._entries=function(e){let t=[],s=0;for(;s`${e.mode} ${e.type} ${e.oid} ${e.path}`).join("\n")}toObject(){return Buffer.concat(this._entries.map(e=>{let t=Buffer.from(e.mode.replace(/^0/,"")),s=Buffer.from(" "),r=Buffer.from(e.path),a=Buffer.from([0]),i=Buffer.from(e.oid.match(/../g).map(e=>parseInt(e,16)));return Buffer.concat([t,s,r,a,i])}))}entries(){return this._entries}*[Symbol.iterator](){for(let e of this._entries)yield e}}t.default=a},function(e,t){e.exports=require("sha.js")},function(e,t){e.exports=require("../../proto/js/Peer")},function(e,t,s){"use strict";function r(e){return new Promise((t,s)=>e.then(s,t))}Object.defineProperty(t,"__esModule",{value:!0}),t.randomString=function(){return Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,5)},t.firstPromiseFulfilled=function(e){return r(Promise.all(e.map(r)))}},function(e,t,s){"use strict";var r,a,i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=i(s(40)),o=i(s(5)),c=i(s(14)),u=s(41),l=s(42),{HandshakeMessage:d,PeerInfoMessage:f}=l.peer,h=parseInt(null!==(r=process.env.UDP_MULTICAST_PORT)&&void 0!==r?r:"5353"),y=null!==(a=process.env.UDP_MULTICAST_ADDR)&&void 0!==a?a:"224.0.0.251";class p extends u.EventEmitter{constructor(e,t,s){super(),this.peerPubKeyMessages=new Map,this.addPeer=e,this.localPeerInfo=t,this.keyManager=s,this.interval=1e3,this.queryInterval=null,this.socket=n.default.createSocket({type:"udp4",reuseAddr:!0}),this.socket.bind(h),this.socket.on("listening",(()=>{this.socket.addMembership(y);this.socket.address()}).bind(this)),this.socket.on("message",this.handleHandshakeMessages.bind(this)),this.queryInterval=this.queryLAN()}async requestPeerContact(e){const t=Buffer.from(e),s=o.default.randomBytes(16),r=await this.keyManager.encryptData(t,t),a=await this.keyManager.encryptData(s,t),i=await this.keyManager.encryptData(Buffer.from(this.keyManager.getPublicKey()),t);this.peerPubKeyMessages.set(e,{encryptedLocalPubKey:Buffer.from(i),encryptedPeerPubKey:Buffer.from(r),rawRandomMessage:s,encryptedRandomMessage:Buffer.from(a)})}queryLAN(){const e=()=>{for(const e of this.peerPubKeyMessages.keys()){const t=this.peerPubKeyMessages.get(e);if(t){const e=d.encode({targetPubKey:t.encryptedPeerPubKey,requestingPubKey:t.encryptedLocalPubKey,message:t.encryptedRandomMessage}).finish();this.socket.send(e,0,e.length,h,y)}}};return e(),setInterval(e,this.interval)}async handleHandshakeMessages(e,t){var s,r;try{const{message:t,requestingPubKey:a,responsePeerInfo:i,targetPubKey:n}=d.decode(e),o=await this.keyManager.decryptData(Buffer.from(t)),u=await this.keyManager.decryptData(Buffer.from(n)),l=await this.keyManager.decryptData(Buffer.from(a)),p=this.keyManager.getPublicKey();if(l.toString()==p){const e=null===(s=this.peerPubKeyMessages.get(u.toString()))||void 0===s?void 0:s.rawRandomMessage;if(o.toString()==(null==e?void 0:e.toString())){const{addresses:e,connectedAddr:t,pubKey:s}=f.decode(i),r=new c.default(s,e,t);if(r){this.addPeer(r);const e=r.publicKey;this.peerPubKeyMessages.delete(e),console.log("New peer added to the store"),this.emit("found",r)}else this.emit("error","I got a validated response. But no peerInfo")}}else{const e=await this.keyManager.encryptData(Buffer.from(p),l),t=await this.keyManager.encryptData(o,l),s=await this.keyManager.encryptData(l,l),a=f.encode({addresses:this.localPeerInfo.AdressStringList,connectedAddr:null===(r=this.localPeerInfo.connectedAddr)||void 0===r?void 0:r.toString(),pubKey:this.localPeerInfo.publicKey}).finish(),i=d.encode({targetPubKey:Buffer.from(e),requestingPubKey:Buffer.from(s),message:Buffer.from(t),responsePeerInfo:a}).finish();this.socket.send(i,0,i.length,h,y)}}catch(e){}}}t.default=p},function(e,t){e.exports=require("dgram")},function(e,t){e.exports=require("events")},function(e,t){e.exports=require("../../proto/js/Peer.js")},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(1)),i=r(s(0)),n=r(s(15)),o=r(s(44)),c=s(16);t.default=class{constructor(e=a.default.homedir()+"/.polykey",t,s){this.polykeyPath=e,this.fileSystem=t,this.keyManager=s,this.metadataPath=i.default.join(e,".vaultKeys"),this.fileSystem.mkdirSync(this.polykeyPath,{recursive:!0}),this.vaults=new Map,this.vaultKeys=new Map,this.loadMetadata();for(const[e,t]of this.vaultKeys.entries()){const s=i.default.join(this.polykeyPath,e);if(this.fileSystem.existsSync(s)){const s=new o.default(e,t,this.polykeyPath);this.vaults.set(e,s)}}}getVault(e){if(this.vaults.has(e)){return this.vaults.get(e)}if(this.vaultKeys.has(e)){this.validateVault(e);const t=this.vaultKeys.get(e),s=new o.default(e,t,this.polykeyPath);return this.vaults.set(e,s),s}throw new Error("Vault does not exist in memory")}async createVault(e,t){if(this.vaultExists(e))throw Error("Vault already exists!");try{const s=i.default.join(this.polykeyPath,e);let r;this.fileSystem.mkdirSync(s,{recursive:!0}),r=t||await this.keyManager.generateKey(e+"-Key",this.keyManager.getPrivateKey()),this.vaultKeys.set(e,r),this.writeMetadata();const a=new o.default(e,r,this.polykeyPath);return await a.initRepository(),this.vaults.set(e,a),this.getVault(e)}catch(t){throw this.destroyVault(e),t}}async cloneVault(e,t){if(this.vaultExists(e))throw new Error("Vault name already exists locally, try pulling instead");const r="http://0.0.0.0/"+e;if(!(await n.default.getRemoteInfo({http:t,url:r})).refs)throw new Error(`Peer does not have vault: '${e}'`);const a=await this.keyManager.generateKey(e+"-Key",this.keyManager.getPrivateKey()),u=new(s(17).VirtualFS),l=new c.EncryptedFS(a,u,u,this.fileSystem,process);await n.default.clone({fs:{promises:l.promises},http:t,dir:i.default.join(this.polykeyPath,e),url:r,ref:"master",singleBranch:!0});const d=new o.default(e,a,this.polykeyPath);return this.vaults.set(e,d),d}vaultExists(e){const t=i.default.join(this.polykeyPath,e);return this.fileSystem.existsSync(t)}destroyVault(e){const t=i.default.join(this.polykeyPath,e);if(this.fileSystem.existsSync(t)&&this.fileSystem.rmdirSync(t,{recursive:!0}),this.vaults.delete(e),this.vaultKeys.delete(e),this.writeMetadata(),this.fileSystem.existsSync(t))throw new Error("Vault folder could not be destroyed!")}listVaults(){return Array.from(this.vaults.keys())}validateVault(e){if(!this.vaults.has(e))throw Error("Vault does not exist in memory");if(!this.vaultKeys.has(e))throw Error("Vault key does not exist in memory");const t=i.default.join(this.polykeyPath,e);if(!this.fileSystem.existsSync(t))throw Error("Vault directory does not exist")}async writeMetadata(){const e=JSON.stringify([...this.vaultKeys]),t=await this.keyManager.encryptData(Buffer.from(e));await this.fileSystem.promises.writeFile(this.metadataPath,t)}async loadMetadata(){if(this.fileSystem.existsSync(this.metadataPath)&&this.keyManager.identityLoaded){const e=this.fileSystem.readFileSync(this.metadataPath),t=(await this.keyManager.decryptData(e)).toString();for(const[e,s]of new Map(JSON.parse(t)))this.vaultKeys[e]=Buffer.from(s)}}}},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(s(2)),i=r(s(0)),n=r(s(15)),o=s(16);t.default=class{constructor(e,t,r){this.key=t,this.keyLen=t.length;const n=new(s(17).VirtualFS);this.efs=new o.EncryptedFS(this.key,n,n,a.default,process),this.name=e,this.vaultPath=i.default.join(r,e),this.efs.mkdirSync(this.vaultPath,{recursive:!0}),this.secrets=new Map,this.loadSecrets(),this.metadataPath=i.default.join(this.vaultPath,".vault","metadata"),this.loadMetadata()}get EncryptedFS(){return this.efs}secretExists(e){const t=i.default.join(this.vaultPath,e);return this.secrets.has(e)&&this.efs.existsSync(t)}async addSecret(e,t){if(this.secrets.has(e))throw new Error("Secret already exists, try updating it instead.");const s=i.default.join(this.vaultPath,e);await this.efs.promises.writeFile(s,t,{}),this.secrets.set(e,t),await this.commitChanges("Add secret: "+e,e,"added")}async updateSecret(e,t){if(!this.secrets.has(e))throw new Error("Secret does not exist, try adding it instead.");const s=i.default.join(this.vaultPath,e);await this.efs.promises.writeFile(s,t,{}),this.secrets.set(e,t),await this.commitChanges("Update secret: "+e,e,"modified")}getSecret(e){if(this.secrets.has(e)){const t=this.secrets.get(e);if(t)return t;{const t=i.default.join(this.vaultPath,e),s=this.efs.readFileSync(t,{});return this.secrets.set(e,s),s}}throw Error("Secret: "+e+" does not exist")}async removeSecret(e){if(this.secrets.has(e)){const t=this.secrets.delete(e);if(await this.efs.promises.unlink(i.default.join(this.vaultPath,e)),await this.commitChanges("Remove secret: "+e,e,"removed"),t)return;throw Error("Secret: "+e+" was not removed")}throw Error("Secret: "+e+" does not exist")}listSecrets(){return Array.from(this.secrets.keys())}tagVault(){}untagVault(){}shareVault(e){if(this.sharedPubKeys.has(name))throw new Error("Vault is already shared with given public key");this.sharedPubKeys.add(e),this.writeMetadata()}unshareVault(e){if(!this.sharedPubKeys.has(e))throw new Error("Vault is not shared with given public key");this.sharedPubKeys.delete(e),this.writeMetadata()}peerCanAccess(e){return!0}async pullVault(e){await n.default.currentBranch({fs:{promises:this.efs.promises},dir:this.vaultPath,fullname:!0}),await n.default.pull({fs:{promises:this.efs.promises},http:e,dir:this.vaultPath,url:"http://0.0.0.0:0/"+this.name,ref:"HEAD",singleBranch:!0,author:{name:this.name}}),this.loadSecrets()}async initRepository(){const e=this.efs;await n.default.init({fs:e,dir:this.vaultPath}),await n.default.commit({fs:e,dir:this.vaultPath,author:{name:this.name},message:"init commit"}),this.efs.writeFileSync(i.default.join(this.vaultPath,".git","packed-refs"),"# pack-refs with: peeled fully-peeled sorted")}writeMetadata(){this.efs.mkdirSync(i.default.dirname(this.metadataPath),{recursive:!0});const e={sharedPubKeys:Array.from(this.sharedPubKeys.keys())};this.efs.writeFileSync(this.metadataPath,JSON.stringify(e))}loadMetadata(){if(this.efs.existsSync(this.metadataPath)){const e=this.efs.readFileSync(this.metadataPath).toString(),t=JSON.parse(e);this.sharedPubKeys=new Set(t.sharedPubKeys)}else this.sharedPubKeys=new Set,this.writeMetadata()}async commitChanges(e,t,s){return"removed"==s?await n.default.remove({fs:this.efs,dir:this.vaultPath,filepath:t}):await n.default.add({fs:this.efs,dir:this.vaultPath,filepath:t}),await n.default.commit({fs:this.efs,dir:this.vaultPath,author:{name:this.name},message:e})}loadSecrets(){const e=a.default.readdirSync(this.vaultPath,void 0);for(const t of e.filter(e=>"."!=e[0]))this.secrets.set(t,null)}}},function(e,t,s){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var s in e)Object.hasOwnProperty.call(e,s)&&(t[s]=e[s]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(1)),n=r(s(2)),o=r(s(46)),c=r(s(0)),u=r(s(47)),l=s(48),d=a(s(4)),f=r(s(49)),h=r(s(18)),y=s(19),p=s(3),{AgentMessage:m,CreateSecretRequestMessage:g,CreateSecretResponseMessage:w,DeriveKeyRequestMessage:P,DeriveKeyResponseMessage:S,DestroySecretRequestMessage:v,DestroySecretResponseMessage:k,DestroyVaultRequestMessage:b,DestroyVaultResponseMessage:M,ErrorMessage:_,GetSecretRequestMessage:E,GetSecretResponseMessage:K,ListNodesRequestMessage:R,ListNodesResponseMessage:x,ListSecretsRequestMessage:j,ListSecretsResponseMessage:I,ListVaultsRequestMessage:A,ListVaultsResponseMessage:N,NewNodeRequestMessage:O,NewNodeResponseMessage:q,NewVaultRequestMessage:D,NewVaultResponseMessage:F,RegisterNodeRequestMessage:B,RegisterNodeResponseMessage:C,SignFileRequestMessage:T,SignFileResponseMessage:V,Type:$,VerifyFileRequestMessage:L,VerifyFileResponseMessage:G}=y.agent;class U{constructor(){this.persistentStore=new f.default("polykey"),this.polykeyMap=new Map,this.socketPath=U.SocketPath,n.default.existsSync(this.socketPath)&&n.default.unlinkSync(this.socketPath),n.default.existsSync(c.default.dirname(this.socketPath))||n.default.promises.mkdir(c.default.dirname(this.socketPath));const e=this.persistentStore.get("nodePaths");if(e)for(const t of e)n.default.existsSync(t)?this.polykeyMap.set(t,new d.default(t,n.default)):this.removeFromNodePaths(t);else this.persistentStore.set("nodePaths",[]);this.server=o.default.createServer().listen(this.socketPath),this.server.on("connection",e=>{this.handleClientCommunication(e)})}get AllNodePaths(){return Array.from(this.polykeyMap.keys()).filter(e=>{try{return this.getPolykey(e),!0}catch(e){return!1}})}get UnlockedNodePaths(){return this.AllNodePaths.filter(e=>{try{return this.getPolykey(e).keyManager.identityLoaded}catch(e){return!1}})}stop(){this.server.close()}addToNodePaths(e,t){this.polykeyMap.set(e,t);const s=new Set(this.persistentStore.get("nodePaths"));s.add(e),this.persistentStore.set("nodePaths",Array.from(s.values()))}removeFromNodePaths(e){this.polykeyMap.delete(e);const t=new Set(this.persistentStore.get("nodePaths"));t.delete(e),this.persistentStore.set("nodePaths",Array.from(t.values()))}handleClientCommunication(e){e.on("data",async t=>{var s;try{const{type:s,nodePath:r,subMessage:a}=m.decode(t);let i=void 0;switch(s){case $.STATUS:i=Buffer.from("online");break;case $.STOP_AGENT:this.stop(),u.default.exit();case $.REGISTER_NODE:i=await this.registerNode(r,a);break;case $.NEW_NODE:i=await this.newNode(r,a);break;case $.LIST_NODES:i=this.listNodes(a);break;case $.DERIVE_KEY:i=await this.deriveKey(r,a);break;case $.SIGN_FILE:i=await this.signFile(r,a);break;case $.VERIFY_FILE:i=await this.verifyFile(r,a);break;case $.LIST_VAULTS:i=await this.listVaults(r);break;case $.NEW_VAULT:i=await this.newVault(r,a);break;case $.DESTROY_VAULT:i=await this.destroyVault(r,a);break;case $.LIST_SECRETS:i=await this.listSecrets(r,a);break;case $.CREATE_SECRET:i=await this.createSecret(r,a);break;case $.DESTROY_SECRET:i=await this.destroySecret(r,a);break;case $.GET_SECRET:i=await this.getSecret(r,a);break;default:throw Error("message type not supported: "+s)}if(!i)throw Error("something went wrong");{const t=m.encode({type:s,isResponse:!0,nodePath:r,subMessage:i}).finish();e.write(t)}}catch(t){const r=m.encode({type:$.ERROR,isResponse:!0,nodePath:void 0,subMessage:_.encode({error:null!==(s=t.message)&&void 0!==s?s:t}).finish()}).finish();e.write(r)}e.end()})}async registerNode(e,t){const{passphrase:s}=B.decode(t);let r=this.polykeyMap.get(e);if(r){if(r.keyManager.identityLoaded)throw Error(`node path is already loaded and unlocked: '${e}'`);await r.keyManager.unlockIdentity(s)}else{const t=new d.KeyManager(e,n.default);await t.unlockIdentity(s),r=new d.default(e,n.default,t)}return this.addToNodePaths(e,r),q.encode({successful:r.keyManager.identityLoaded&&this.polykeyMap.has(e)}).finish()}async newNode(e,t){if(this.polykeyMap.has(e)&&n.default.existsSync(e))throw Error(`node path '${e}' is already loaded`);if(n.default.existsSync(e))throw Error(`node path already exists: '${e}'`);const{name:s,email:r,passphrase:a,nbits:i}=O.decode(t),o=new d.KeyManager(e,n.default);await o.generateKeyPair(s,r,a,0==i?void 0:i,!0,e=>{});const c=new d.default(e,n.default,o);return this.addToNodePaths(e,c),q.encode({successful:o.identityLoaded&&this.polykeyMap.has(e)}).finish()}listNodes(e){const{unlockedOnly:t}=R.decode(e);return t?x.encode({nodes:this.UnlockedNodePaths}).finish():x.encode({nodes:this.AllNodePaths}).finish()}getPolykey(e){var t;if(this.polykeyMap.has(e))return this.polykeyMap.get(e);if(n.default.existsSync(e))throw Error(`polykey node has not been loaded yet: '${e}'`);{const s=new Set(null!==(t=this.persistentStore.get("nodePaths"))&&void 0!==t?t:[]);throw s.delete(e),this.persistentStore.set("nodePaths",s),Error(`node path does not exist: '${e}'`)}}async deriveKey(e,t){const{keyName:s,passphrase:r}=P.decode(t),a=this.getPolykey(e);return await a.keyManager.generateKey(s,r),S.encode({successful:!0}).finish()}async signFile(e,t){const{filePath:s,privateKeyPath:r,passphrase:a}=T.decode(t),i=this.getPolykey(e),n=await i.keyManager.signFile(s,r,a);return V.encode({signaturePath:n}).finish()}async verifyFile(e,t){const{filePath:s,signaturePath:r}=L.decode(t),a=this.getPolykey(e),i=await a.keyManager.verifyFile(s,r);return G.encode({verified:i}).finish()}async listVaults(e){const t=this.getPolykey(e).vaultManager.listVaults();return N.encode({vaultNames:t}).finish()}async newVault(e,t){const{vaultName:s}=D.decode(t),r=this.getPolykey(e);return await r.vaultManager.createVault(s),F.encode({successful:!0}).finish()}async destroyVault(e,t){const{vaultName:s}=b.decode(t);return this.getPolykey(e).vaultManager.destroyVault(s),M.encode({successful:!0}).finish()}async listSecrets(e,t){const{vaultName:s}=j.decode(t),r=this.getPolykey(e).vaultManager.getVault(s).listSecrets();return I.encode({secretNames:r}).finish()}async createSecret(e,t){const{vaultName:s,secretName:r,secretPath:a}=g.decode(t),i=this.getPolykey(e).vaultManager.getVault(s),o=await n.default.promises.readFile(a);return await i.addSecret(r,o),w.encode({successful:!0}).finish()}async destroySecret(e,t){const{vaultName:s,secretName:r}=v.decode(t),a=this.getPolykey(e).vaultManager.getVault(s);return await a.removeSecret(r),k.encode({successful:!0}).finish()}async getSecret(e,t){const{vaultName:s,secretName:r}=E.decode(t),a=this.getPolykey(e).vaultManager.getVault(s),i=Buffer.from(a.getSecret(r));return K.encode({secret:i}).finish()}static connectToAgent(e){return new h.default(null!=e?e:()=>{const e=new p.PassThrough,t=o.default.createConnection(U.SocketPath);return t.pipe(e),e.pipe(t),e})}static get SocketPath(){const e=i.default.platform(),t=i.default.userInfo();return"win32"==e?c.default.join("\\\\?\\pipe",u.default.cwd(),"polykey-agent"):`/run/user/${t.uid}/polykey/S.polykey-agent`}static get LogPath(){const e=i.default.platform(),t=i.default.userInfo();return"win32"==e?c.default.join(i.default.tmpdir(),"polykey","log"):`/run/user/${t.uid}/polykey/log`}static async startAgent(e=!1){return new Promise((t,s)=>{try{let s={uid:u.default.getuid(),detached:e};e&&(n.default.rmdirSync(U.LogPath,{recursive:!0}),n.default.mkdirSync(U.LogPath,{recursive:!0}),s.stdio=["ipc",n.default.openSync(c.default.join(U.LogPath,"output.log"),"a"),n.default.openSync(c.default.join(U.LogPath,"error.log"),"a"),,]);const r=l.fork(U.DAEMON_SCRIPT_PATH,void 0,s),a=r.pid;r.unref(),t(a)}catch(e){s(e)}})}}U.DAEMON_SCRIPT_PATH=c.default.join(__dirname,"internal","daemon-script.js"),t.default=U},function(e,t){e.exports=require("net")},function(e,t){e.exports=require("process")},function(e,t){e.exports=require("child_process")},function(e,t){e.exports=require("configstore")}])})); +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["polykey"] = factory(); + else + root["polykey"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 4); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +module.exports = require("path"); + +/***/ }), +/* 1 */ +/***/ (function(module, exports) { + +module.exports = require("os"); + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + +module.exports = require("fs"); + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + +module.exports = require("readable-stream"); + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os_1 = __importDefault(__webpack_require__(1)); +const KeyManager_1 = __importDefault(__webpack_require__(20)); +exports.KeyManager = KeyManager_1.default; +const PeerManager_1 = __importDefault(__webpack_require__(23)); +exports.PeerManager = PeerManager_1.default; +const VaultManager_1 = __importDefault(__webpack_require__(43)); +exports.VaultManager = VaultManager_1.default; +const PolykeyAgent_1 = __importDefault(__webpack_require__(46)); +exports.PolykeyAgent = PolykeyAgent_1.default; +const PolykeyClient_1 = __importDefault(__webpack_require__(18)); +exports.PolykeyClient = PolykeyClient_1.default; +class Polykey { + constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager, vaultManager, peerManager) { + this.polykeyPath = polykeyPath; + // Set key manager + this.keyManager = keyManager !== null && keyManager !== void 0 ? keyManager : new KeyManager_1.default(this.polykeyPath, fileSystem); + // Set or Initialize vaultManager + this.vaultManager = vaultManager !== null && vaultManager !== void 0 ? vaultManager : new VaultManager_1.default(this.polykeyPath, fileSystem, this.keyManager); + // Initialize peer store and peer discovery classes + this.peerManager = peerManager !== null && peerManager !== void 0 ? peerManager : new PeerManager_1.default(this.polykeyPath, fileSystem, this.keyManager, this.vaultManager); + } +} +exports.default = Polykey; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + +module.exports = require("crypto"); + +/***/ }), +/* 6 */ +/***/ (function(module, exports) { + +module.exports = require("@grpc/grpc-js"); + +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + +module.exports = require("../../proto/compiled/Git_grpc_pb"); + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + +module.exports = require("../../proto/compiled/Git_pb"); + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +/** +pkt-line Format +--------------- + +Much (but not all) of the payload is described around pkt-lines. + +A pkt-line is a variable length binary string. The first four bytes +of the line, the pkt-len, indicates the total length of the line, +in hexadecimal. The pkt-len includes the 4 bytes used to contain +the length's hexadecimal representation. + +A pkt-line MAY contain binary data, so implementors MUST ensure +pkt-line parsing/formatting routines are 8-bit clean. + +A non-binary line SHOULD BE terminated by an LF, which if present +MUST be included in the total length. Receivers MUST treat pkt-lines +with non-binary data the same whether or not they contain the trailing +LF (stripping the LF if present, and not complaining when it is +missing). + +The maximum length of a pkt-line's data component is 65516 bytes. +Implementations MUST NOT send pkt-line whose length exceeds 65520 +(65516 bytes of payload + 4 bytes of length data). + +Implementations SHOULD NOT send an empty pkt-line ("0004"). + +A pkt-line with a length field of 0 ("0000"), called a flush-pkt, +is a special case and MUST be handled differently than an empty +pkt-line ("0004"). + +---- + pkt-line = data-pkt / flush-pkt + + data-pkt = pkt-len pkt-payload + pkt-len = 4*(HEXDIG) + pkt-payload = (pkt-len - 4)*(OCTET) + + flush-pkt = "0000" +---- + +Examples (as C-style strings): + +---- + pkt-line actual value + --------------------------------- + "0006a\n" "a\n" + "0005a" "a" + "000bfoobar\n" "foobar\n" + "0004" "" +---- +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +function padHex(b, n) { + const s = n.toString(16); + return '0'.repeat(b - s.length) + s; +} +// I'm really using this more as a namespace. +// There's not a lot of "state" in a pkt-line +class GitPktLine { + static flush() { + return Buffer.from('0000', 'utf8'); + } + static encode(line) { + if (typeof line === 'string') { + line = Buffer.from(line); + } + const length = line.length + 4; + const hexlength = padHex(4, length); + return Buffer.concat([Buffer.from(hexlength, 'utf8'), line]); + } + static streamReader(stream) { + return async function read() { + try { + let length = await stream.slice(4); + if (length === null) + return true; + length = parseInt(length.toString('utf8'), 16); + if (length === 0) + return null; + let buffer = await stream.slice(length - 4); + if (buffer === null) + return true; + return buffer; + } + catch (err) { + console.log('error', err); + return true; + } + }; + } +} +exports.default = GitPktLine; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// This is a convenience wrapper for reading and writing files in the 'refs' directory. +const path_1 = __importDefault(__webpack_require__(0)); +const GitPackedRefs_1 = __importDefault(__webpack_require__(27)); +// @see https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions +const refpaths = (ref) => [ + `${ref}`, + `refs/${ref}`, + `refs/tags/${ref}`, + `refs/heads/${ref}`, + `refs/remotes/${ref}`, + `refs/remotes/${ref}/HEAD`, +]; +function compareRefNames(a, b) { + // https://stackoverflow.com/a/40355107/2168416 + const _a = a.replace(/\^\{\}$/, ''); + const _b = b.replace(/\^\{\}$/, ''); + const tmp = -(_a < _b) || +(_a > _b); + if (tmp === 0) { + return a.endsWith('^{}') ? 1 : -1; + } + return tmp; +} +// @see https://git-scm.com/docs/gitrepository-layout +const GIT_FILES = ['config', 'description', 'index', 'shallow', 'commondir']; +// This function is used to get all the files in the refs folder for listRefs function +async function recursiveDirectoryWalk(dir, fileSystem) { + return new Promise((resolve, reject) => { + let results = []; + fileSystem.promises + .readdir(dir) + .then(async (list) => { + var pending = list.length; + if (!pending) + return resolve(results); + list.forEach(async function (file) { + file = path_1.default.resolve(dir, file); + fileSystem.promises.stat(file).then(async (stat) => { + if (stat && stat.isDirectory()) { + const res = await recursiveDirectoryWalk(file, fileSystem); + results = results.concat(res); + if (!--pending) + resolve(results); + } + else { + results.push(file); + if (!--pending) + resolve(results); + } + }); + }); + }) + .catch((err) => { + if (err) + return reject(err); + }); + }); +} +class GitRefManager { + static async packedRefs(fileSystem, gitdir) { + const text = fileSystem.readFileSync(`${gitdir}/packed-refs`, { encoding: 'utf8' }); + const packed = GitPackedRefs_1.default.from(text); + return packed.refs; + } + // List all the refs that match the `filepath` prefix + static async listRefs(fileSystem, gitdir, filepath) { + const packedMap = GitRefManager.packedRefs(fileSystem, gitdir); + let files = []; + try { + files = await recursiveDirectoryWalk(`${gitdir}/${filepath}`, fileSystem); + files = files.map((x) => x.replace(`${gitdir}/${filepath}/`, '')); + } + catch (err) { + files = []; + } + for (let key of (await packedMap).keys()) { + // filter by prefix + if (key.startsWith(filepath)) { + // remove prefix + key = key.replace(filepath + '/', ''); + // Don't include duplicates; the loose files have precedence anyway + if (!files.includes(key)) { + files.push(key); + } + } + } + // since we just appended things onto an array, we need to sort them now + files.sort(compareRefNames); + return files; + } + static async resolve(fileSystem, gitdir, ref, depth) { + if (depth !== undefined) { + depth--; + if (depth === -1) { + return ref; + } + } + // Is it a ref pointer? + if (ref.startsWith('ref: ')) { + ref = ref.slice('ref: '.length); + return GitRefManager.resolve(fileSystem, gitdir, ref, depth); + } + // Is it a complete and valid SHA? + if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) { + return ref; + } + // We need to alternate between the file system and the packed-refs + const packedMap = await GitRefManager.packedRefs(fileSystem, gitdir); + // Look in all the proper paths, in this order + const allpaths = refpaths(ref).filter((p) => !GIT_FILES.includes(p)); // exclude git system files (#709) + for (const ref of allpaths) { + const sha = fileSystem.readFileSync(`${gitdir}/${ref}`, { encoding: 'utf8' }).toString() || packedMap.get(ref); + if (sha) { + return GitRefManager.resolve(fileSystem, gitdir, sha.trim(), depth); + } + } + // Do we give up? + throw Error('RefNotFound'); + } +} +exports.default = GitRefManager; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports) { + +module.exports = require("pako"); + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +// The amount of work that went into crafting these cases to handle +// -0 (just so we don't lose that information when parsing and reconstructing) +// but can also default to +0 was extraordinary. +Object.defineProperty(exports, "__esModule", { value: true }); +function simpleSign(n) { + return Math.sign(n) || (Object.is(n, -0) ? -1 : 1); +} +function negateExceptForZero(n) { + return n === 0 ? n : -n; +} +function formatTimezoneOffset(minutes) { + let sign = simpleSign(negateExceptForZero(minutes)); + minutes = Math.abs(minutes); + let hours = Math.floor(minutes / 60); + minutes -= hours * 60; + let strHours = String(hours); + let strMinutes = String(minutes); + if (strHours.length < 2) + strHours = '0' + strHours; + if (strMinutes.length < 2) + strMinutes = '0' + strMinutes; + return (sign === -1 ? '-' : '+') + strHours + strMinutes; +} +function parseTimezoneOffset(offset) { + let [, sign, hours, minutes] = offset.match(/(\+|-)(\d\d)(\d\d)/); + minutes = (sign === '+' ? 1 : -1) * (Number(hours) * 60 + Number(minutes)); + return negateExceptForZero(minutes); +} +function parseAuthor(author) { + let [, name, email, timestamp, offset] = author.match(/^(.*) <(.*)> (.*) (.*)$/); + return { + name: name, + email: email, + timestamp: Number(timestamp), + timezoneOffset: parseTimezoneOffset(offset), + }; +} +function normalize(str) { + // remove all + str = str.replace(/\r/g, ''); + // no extra newlines up front + str = str.replace(/^\n+/, ''); + // and a single newline at the end + str = str.replace(/\n+$/, '') + '\n'; + return str; +} +function indent(str) { + return (str + .trim() + .split('\n') + .map((x) => ' ' + x) + .join('\n') + '\n'); +} +function outdent(str) { + return str + .split('\n') + .map((x) => x.replace(/^ /, '')) + .join('\n'); +} +// TODO: Make all functions have static async signature? +class GitCommit { + constructor(commit) { + if (typeof commit === 'string') { + this._commit = commit; + } + else if (Buffer.isBuffer(commit)) { + this._commit = commit.toString('utf8'); + } + else if (typeof commit === 'object') { + this._commit = GitCommit.render(commit); + } + else { + throw new Error('invalid type passed to GitCommit constructor'); + } + } + static fromPayloadSignature({ payload, signature }) { + let headers = GitCommit.justHeaders(payload); + let message = GitCommit.justMessage(payload); + let commit = normalize(headers + '\ngpgsig' + indent(signature) + '\n' + message); + return new GitCommit(commit); + } + static from(commit) { + return new GitCommit(commit); + } + toObject() { + return Buffer.from(this._commit, 'utf8'); + } + // Todo: allow setting the headers and message + headers() { + return this.parseHeaders(); + } + // Todo: allow setting the headers and message + message() { + return GitCommit.justMessage(this._commit); + } + parse() { + return Object.assign({ message: this.message() }, this.headers()); + } + static justMessage(commit) { + return normalize(commit.slice(commit.indexOf('\n\n') + 2)); + } + static justHeaders(commit) { + return commit.slice(0, commit.indexOf('\n\n')); + } + parseHeaders() { + let headers = GitCommit.justHeaders(this._commit).split('\n'); + let hs = []; + for (let h of headers) { + if (h[0] === ' ') { + // combine with previous header (without space indent) + hs[hs.length - 1] += '\n' + h.slice(1); + } + else { + hs.push(h); + } + } + let obj = { + parent: [], + }; + for (let h of hs) { + let key = h.slice(0, h.indexOf(' ')); + let value = h.slice(h.indexOf(' ') + 1); + if (Array.isArray(obj[key])) { + obj[key].push(value); + } + else { + obj[key] = value; + } + } + if (obj.author) { + obj.author = parseAuthor(obj.author); + } + if (obj.committer) { + obj.committer = parseAuthor(obj.committer); + } + return obj; + } + static renderHeaders(obj) { + let headers = ''; + if (obj.tree) { + headers += `tree ${obj.tree}\n`; + } + else { + headers += `tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n`; // the null tree + } + if (obj.parent) { + if (obj.parent.length === undefined) { + throw new Error(`commit 'parent' property should be an array`); + } + for (let p of obj.parent) { + headers += `parent ${p}\n`; + } + } + let author = obj.author; + headers += `author ${author.name} <${author.email}> ${author.timestamp} ${formatTimezoneOffset(author.timezoneOffset)}\n`; + let committer = obj.committer || obj.author; + headers += `committer ${committer.name} <${committer.email}> ${committer.timestamp} ${formatTimezoneOffset(committer.timezoneOffset)}\n`; + if (obj.gpgsig) { + headers += 'gpgsig' + indent(obj.gpgsig); + } + return headers; + } + static render(obj) { + return GitCommit.renderHeaders(obj) + '\n' + normalize(obj.message); + } + render() { + return this._commit; + } + withoutSignature() { + let commit = normalize(this._commit); + if (commit.indexOf('\ngpgsig') === -1) + return commit; + let headers = commit.slice(0, commit.indexOf('\ngpgsig')); + let message = commit.slice(commit.indexOf('-----END PGP SIGNATURE-----\n') + '-----END PGP SIGNATURE-----\n'.length); + return normalize(headers + '\n' + message); + } + isolateSignature() { + let signature = this._commit.slice(this._commit.indexOf('-----BEGIN PGP SIGNATURE-----'), this._commit.indexOf('-----END PGP SIGNATURE-----') + '-----END PGP SIGNATURE-----'.length); + return outdent(signature); + } +} +exports.default = GitCommit; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs_1 = __importDefault(__webpack_require__(2)); +const pako_1 = __importDefault(__webpack_require__(11)); +const path_1 = __importDefault(__webpack_require__(0)); +const GitObject_1 = __importDefault(__webpack_require__(32)); +const PackfileCache = new Map(); +class GitObjectManager { + static async read(fileSystem, gitdir, oid, format = 'content') { + // Look for it in the loose object directory. + let file = fileSystem.readFileSync(`${gitdir}/objects/${oid.slice(0, 2)}/${oid.slice(2)}`); + let source = `./objects/${oid.slice(0, 2)}/${oid.slice(2)}`; + // Check to see if it's in a packfile. + if (!file) { + // Curry the current read method so that the packfile un-deltification + // process can acquire external ref-deltas. + const getExternalRefDelta = (oid) => GitObjectManager.read(fileSystem, gitdir, oid); + // Iterate through all the .pack files + let list = fs_1.default.readdirSync(path_1.default.join(gitdir, '/objects/pack')); + list = list.filter((x) => x.endsWith('.pack')); + for (let filename of list) { + // Try to get the packfile from the in-memory cache + let p = PackfileCache.get(filename); + // If the packfile DOES have the oid we're looking for... + if (p.offsets.has(oid)) { + // Make sure the packfile is loaded in memory + if (!p.pack) { + const pack = fileSystem.readFileSync(`${gitdir}/objects/pack/${filename}`); + await p.load({ pack }); + } + // Get the resolved git object from the packfile + let result = await p.read({ oid, getExternalRefDelta }); + result.source = `./objects/pack/${filename}`; + return result; + } + } + } + // Check to see if it's in shallow commits. + if (!file) { + let text = fileSystem.readFileSync(`${gitdir}/shallow`, { encoding: 'utf8' }); + if (text !== null && text.includes(oid)) { + throw new Error(`ReadShallowObjectFail: ${oid}`); + } + } + // Finally + if (!file) { + throw new Error(`ReadObjectFail: ${oid}`); + } + if (format === 'deflated') { + return { format: 'deflated', object: file, source }; + } + let buffer = Buffer.from(pako_1.default.inflate(file)); + if (format === 'wrapped') { + return { format: 'wrapped', object: buffer, source }; + } + let { type, object } = GitObject_1.default.unwrap({ oid, buffer }); + if (format === 'content') + return { type, format: 'content', object, source }; + } +} +exports.default = GitObjectManager; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +class Address { + constructor(ip, port) { + this.ip = ip; + this.port = port; + } + /** + * Create an address object from a address string + * @param addressString Address string in the format of `${this.ip}:${this.port}` + */ + static parse(addressString) { + const components = addressString.split(':'); + const ip = components[0]; + const port = components[1]; + return new Address(ip, port); + } + /** + * Create an address object from a net.AddressInfo + * @param addressInfo AddressInfo of desired address + */ + static fromAddressInfo(addressInfo) { + const ip = addressInfo.address == '::' ? 'localhost' : addressInfo.address; + return new Address(ip, addressInfo.port.toString()); + } + /** + * Convert address into string of format `${this.ip}:${this.port}` + */ + toString() { + return `${this.ip}:${this.port}`; + } +} +exports.Address = Address; +Address.prototype.toString = function () { + return `${this.ip}:${this.port}`; +}; +class PeerInfo { + constructor(pubKey, addresses = [], connectedAddr) { + this.publicKey = pubKey; + this.addresses = new Set(addresses.map((addr) => { + return Address.parse(addr); + })); + this.connectedAddr = connectedAddr ? Address.parse(connectedAddr) : undefined; + } + /** + * Sets the main server address for the peer + * @param address Main server address for peer + */ + connect(address) { + if (!this.addresses.has(address)) { + this.addresses.add(address); + } + this.connectedAddr = address; + } + /** + * Clears the main server address for the peer + */ + disconnect() { + this.connectedAddr = undefined; + } + get AdressStringList() { + return Array.from(this.addresses.values()).map((addr) => { + return addr.toString(); + }); + } +} +exports.default = PeerInfo; + + +/***/ }), +/* 15 */ +/***/ (function(module, exports) { + +module.exports = require("isomorphic-git"); + +/***/ }), +/* 16 */ +/***/ (function(module, exports) { + +module.exports = require("encryptedfs"); + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + +module.exports = require("virtualfs"); + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const Agent_1 = __webpack_require__(19); +const { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage, } = Agent_1.agent; +class PolykeyClient { + constructor(getStream) { + this.getStream = getStream; + } + async sendRequestToAgent(request) { + const stream = this.getStream(); + const responseList = await new Promise((resolve, reject) => { + try { + const responseList = []; + stream.on('data', (data) => { + if (data instanceof Uint8Array) { + responseList.push(data); + } + else { + responseList.push(...data); + } + }); + stream.on('error', (err) => { + reject(err); + }); + stream.on('end', () => { + resolve(responseList); + }); + if (!stream.writableEnded) { + stream.write(request); + } + } + catch (err) { + reject(err); + } + }); + return responseList; + } + async handleAgentCommunication(type, nodePath, request) { + // Encode message and sent + const agentMessage = AgentMessage.encode({ + type: type, + isResponse: false, + nodePath: nodePath, + subMessage: request, + }).finish(); + const responseList = await this.sendRequestToAgent(agentMessage); + const agentMessageList = []; + for (const response of responseList.values()) { + const { subMessage, type } = AgentMessage.decode(response); + if (type == Type.ERROR) { + const { error } = ErrorMessage.decode(subMessage); + const reason = new Error(`Agent Error: ${error}`); + throw reason; + } + else { + agentMessageList.push(AgentMessage.decode(response)); + } + } + return agentMessageList; + } + async registerNode(path, passphrase) { + var _a; + const registerNodeRequest = RegisterNodeRequestMessage.encode({ passphrase }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.REGISTER_NODE, path, registerNodeRequest); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.REGISTER_NODE)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = RegisterNodeResponseMessage.decode(subMessage); + return successful; + } + async newNode(path, name, email, passphrase, nbits) { + var _a; + const newNodeRequest = NewNodeRequestMessage.encode({ name, email, passphrase, nbits }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.NEW_NODE, path, newNodeRequest); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.NEW_NODE)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = NewNodeResponseMessage.decode(subMessage); + return successful; + } + async listNodes(unlockedOnly = true) { + var _a; + const newNodeRequest = ListNodesRequestMessage.encode({ unlockedOnly }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.LIST_NODES, undefined, newNodeRequest); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_NODES)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { nodes } = ListNodesResponseMessage.decode(subMessage); + return nodes; + } + ///////////////////// + // Crypto commands // + ///////////////////// + async deriveKey(nodePath, keyName, passphrase) { + var _a; + const request = DeriveKeyRequestMessage.encode({ keyName, passphrase }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.DERIVE_KEY, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DERIVE_KEY)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = DeriveKeyResponseMessage.decode(subMessage); + return successful; + } + ///////////////////// + // Crypto commands // + ///////////////////// + async signFile(nodePath, filePath, privateKeyPath, passphrase) { + var _a; + const request = SignFileRequestMessage.encode({ filePath, privateKeyPath, passphrase }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.SIGN_FILE, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.SIGN_FILE)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { signaturePath } = SignFileResponseMessage.decode(subMessage); + return signaturePath; + } + async verifyFile(nodePath, filePath, signaturePath) { + var _a; + const request = VerifyFileRequestMessage.encode({ filePath, signaturePath }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.VERIFY_FILE, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.VERIFY_FILE)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { verified } = VerifyFileResponseMessage.decode(subMessage); + return verified; + } + ////////////////////// + // Vault Operations // + ////////////////////// + async listVaults(nodePath) { + var _a; + const encodedResponse = await this.handleAgentCommunication(Type.LIST_VAULTS, nodePath); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_VAULTS)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { vaultNames } = ListVaultsResponseMessage.decode(subMessage); + return vaultNames; + } + async newVault(nodePath, vaultName) { + var _a; + const request = NewVaultRequestMessage.encode({ vaultName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.NEW_VAULT, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.NEW_VAULT)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = NewVaultResponseMessage.decode(subMessage); + return successful; + } + async destroyVault(nodePath, vaultName) { + var _a; + const request = DestroyVaultRequestMessage.encode({ vaultName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_VAULT, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DESTROY_VAULT)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = DestroyVaultResponseMessage.decode(subMessage); + return successful; + } + /////////////////////// + // Secret Operations // + /////////////////////// + async listSecrets(nodePath, vaultName) { + var _a; + const request = ListSecretsRequestMessage.encode({ vaultName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.LIST_SECRETS, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_SECRETS)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { secretNames } = ListSecretsResponseMessage.decode(subMessage); + return secretNames; + } + async createSecret(nodePath, vaultName, secretName, secret) { + var _a; + let request; + if (typeof secret == 'string') { + request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretPath: secret }).finish(); + } + else { + request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretContent: secret }).finish(); + } + const encodedResponse = await this.handleAgentCommunication(Type.CREATE_SECRET, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.CREATE_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = CreateSecretResponseMessage.decode(subMessage); + return successful; + } + async destroySecret(nodePath, vaultName, secretName) { + var _a; + const request = DestroySecretRequestMessage.encode({ vaultName, secretName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_SECRET, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DESTROY_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { successful } = DestroySecretResponseMessage.decode(subMessage); + return successful; + } + async getSecret(nodePath, vaultName, secretName) { + var _a; + const request = GetSecretRequestMessage.encode({ vaultName, secretName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.GET_SECRET, nodePath, request); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.GET_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const { secret } = GetSecretResponseMessage.decode(subMessage); + return Buffer.from(secret); + } + /////////////////// + // Agent control // + /////////////////// + async getAgentStatus() { + var _a; + try { + const encodedResponse = await this.handleAgentCommunication(Type.STATUS); + const subMessage = (_a = encodedResponse.find((r) => r.type == Type.STATUS)) === null || _a === void 0 ? void 0 : _a.subMessage; + if (!subMessage) { + throw Error('agent did not respond'); + } + const status = Buffer.from(subMessage).toString(); + return status; + } + catch (err) { + console.log(err); + return 'stopped'; + } + } + async stopAgent() { + try { + // Tell it to start shutting and wait for response + await this.handleAgentCommunication(Type.STOP_AGENT); + return true; + } + catch (err) { + return (await this.getAgentStatus()) != 'online'; + } + } +} +exports.default = PolykeyClient; + + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + +module.exports = require("../../proto/js/Agent"); + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os_1 = __importDefault(__webpack_require__(1)); +const fs_1 = __importDefault(__webpack_require__(2)); +const path_1 = __importDefault(__webpack_require__(0)); +const kbpgp_1 = __importDefault(__webpack_require__(21)); +const crypto_1 = __importDefault(__webpack_require__(5)); +const util_1 = __webpack_require__(22); +class KeyManager { + constructor(polyKeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, useWebWorkers = false, workerPool) { + this.primaryKeyPair = { private: null, public: null }; + this.metadata = { + privateKeyPath: null, + publicKeyPath: null, + pkiKeyPath: null, + pkiCertPath: null, + caCertPath: null, + }; + ///////// + // PKI // + ///////// + this.pkiInfo = { key: null, cert: null, caCert: null }; + this.useWebWorkers = useWebWorkers; + this.workerPool = workerPool; + this.derivedKeys = new Map(); + this.fileSystem = fileSystem; + // Load key manager metadata + this.polykeyPath = polyKeyPath; + this.keypairPath = path_1.default.join(polyKeyPath, '.keypair'); + if (!this.fileSystem.existsSync(this.keypairPath)) { + this.fileSystem.mkdirSync(this.keypairPath, { recursive: true }); + } + this.metadataPath = path_1.default.join(this.keypairPath, 'metadata'); + this.loadMetadata(); + // Load keys if they were provided + if (this.metadata.privateKeyPath && this.metadata.publicKeyPath) { + // Load files into memory + this.loadKeyPair(this.metadata.publicKeyPath, this.metadata.privateKeyPath); + } + ///////// + // PKI // + ///////// + // Load pki keys and certs + if (this.metadata.pkiKeyPath) { + this.pkiInfo.key = fs_1.default.readFileSync(this.metadata.pkiKeyPath); + } + if (this.metadata.pkiCertPath) { + this.pkiInfo.cert = fs_1.default.readFileSync(this.metadata.pkiCertPath); + } + if (this.metadata.caCertPath) { + this.pkiInfo.caCert = fs_1.default.readFileSync(this.metadata.caCertPath); + } + this.loadPKIInfo(this.pkiInfo.key, this.pkiInfo.cert, this.pkiInfo.caCert, true); + } + get identityLoaded() { + return this.primaryIdentity ? true : false; + } + /** + * Generates a new assymetric key pair (publicKey and privateKey). + * @param name Name of keypair owner + * @param email Email of keypair owner + * @param passphrase Passphrase to lock the keypair + * @param nbits Size of the new keypair + * @param replacePrimary If true, the generated keypair becomes the new primary identity of the key manager + * @param progressCallback A progress hook for keypair generation + */ + async generateKeyPair(name, email, passphrase, nbits = 4096, replacePrimary = false, progressCallback) { + // kbpgp doesn't seem to work for small nbits so set a minimum of 1024 + if (nbits < 1024) { + throw Error('nbits must be greater than 1024 for keypair generation'); + } + // Define options + const flags = kbpgp_1.default['const'].openpgp; + const params = { + asp: progressCallback ? new kbpgp_1.default.ASP({ progress_hook: progressCallback }) : undefined, + userid: `${name} <${email}>`, + primary: { + nbits: nbits, + flags: flags.certify_keys | flags.sign_data | flags.auth | flags.encrypt_comm | flags.encrypt_storage, + expire_in: 0, + }, + subkeys: [], + }; + const identity = await util_1.promisify(kbpgp_1.default.KeyManager.generate)(params); + await util_1.promisify(identity.sign.bind(identity))({}); + // Export pub key first + const publicKey = await util_1.promisify(identity.export_pgp_public.bind(identity))({}); + // Finally export priv key + const privateKey = await util_1.promisify(identity.export_pgp_private.bind(identity))({ passphrase: passphrase }); + // Resolve to parent promise + const keypair = { private: privateKey, public: publicKey }; + if (replacePrimary) { + // Set the new keypair + this.primaryKeyPair = keypair; + // Set the new identity + this.primaryIdentity = identity; + // Overwrite in memory + const privateKeyPath = path_1.default.join(this.keypairPath, 'private_key'); + const publicKeyPath = path_1.default.join(this.keypairPath, 'public_key'); + await this.fileSystem.promises.writeFile(privateKeyPath, keypair.private); + await this.fileSystem.promises.writeFile(publicKeyPath, keypair.public); + // Set metadata + this.metadata.privateKeyPath = privateKeyPath; + this.metadata.publicKeyPath = publicKeyPath; + this.writeMetadata(); + } + return keypair; + } + /** + * Get the primary keypair + */ + getKeyPair() { + return this.primaryKeyPair; + } + /** + * Determines whether public key is loaded or not + */ + hasPublicKey() { + return this.primaryKeyPair.public ? true : false; + } + /** + * Get the public key of the primary keypair + */ + getPublicKey() { + if (!this.primaryKeyPair.public) { + throw Error('Public key does not exist in memory'); + } + return this.primaryKeyPair.public; + } + /** + * Get the private key of the primary keypair + */ + getPrivateKey() { + if (!this.primaryKeyPair.private) { + throw Error('Private key does not exist in memory'); + } + return this.primaryKeyPair.private; + } + /** + * Loads the keypair into the key manager as the primary identity + * @param publicKey Public Key + * @param privateKey Private Key + */ + loadKeyPair(publicKey, privateKey) { + this.loadPrivateKey(privateKey); + this.loadPublicKey(publicKey); + } + /** + * Loads the private key into the primary keypair + * @param privateKey Private Key + */ + loadPrivateKey(privateKey) { + let keyBuffer; + if (typeof privateKey === 'string') { + keyBuffer = this.fileSystem.readFileSync(privateKey); + this.metadata.privateKeyPath = privateKey; + this.writeMetadata(); + } + else { + keyBuffer = privateKey; + } + this.primaryKeyPair.private = keyBuffer.toString(); + } + /** + * Loads the public key into the primary keypair + * @param publicKey Public Key + */ + loadPublicKey(publicKey) { + let keyBuffer; + if (typeof publicKey === 'string') { + keyBuffer = this.fileSystem.readFileSync(publicKey); + this.metadata.publicKeyPath = publicKey; + this.writeMetadata(); + } + else { + keyBuffer = publicKey; + } + this.primaryKeyPair.public = keyBuffer.toString(); + } + /** + * Loads the primary identity into the key manager from the existing keypair + * @param passphrase Passphrase to unlock the private key + */ + async unlockIdentity(passphrase) { + const publicKey = this.getPublicKey(); + const privateKey = this.getPrivateKey(); + const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: publicKey }); + await util_1.promisify(identity.merge_pgp_private.bind(identity))({ armored: privateKey }); + if (identity.is_pgp_locked.bind(identity)()) { + await util_1.promisify(identity.unlock_pgp.bind(identity))({ passphrase: passphrase }); + } + this.primaryIdentity = identity; + } + /** + * Export the primary private key to a specified location + * @param path Destination path + */ + exportPrivateKey(path) { + this.fileSystem.writeFileSync(path, this.primaryKeyPair.private); + this.metadata.privateKeyPath = path; + this.writeMetadata(); + } + /** + * Export the primary public key to a specified location + * @param path Destination path + */ + exportPublicKey(path) { + this.fileSystem.writeFileSync(path, this.primaryKeyPair.public); + this.metadata.publicKeyPath = path; + this.writeMetadata(); + } + /** + * Synchronously generates a new symmetric key and stores it in the key manager + * @param name Unique name of the generated key + * @param passphrase Passphrase to derive the key from + */ + generateKeySync(name, passphrase) { + const salt = crypto_1.default.randomBytes(32); + this.derivedKeys[name] = crypto_1.default.pbkdf2Sync(passphrase, salt, 10000, 256 / 8, 'sha256'); + return this.derivedKeys[name]; + } + /** + * Asynchronously Generates a new symmetric key and stores it in the key manager + * @param name Unique name of the generated key + * @param passphrase Passphrase to derive the key from + */ + async generateKey(name, passphrase) { + const salt = crypto_1.default.randomBytes(32); + this.derivedKeys[name] = await util_1.promisify(crypto_1.default.pbkdf2)(passphrase, salt, 10000, 256 / 8, 'sha256'); + return this.derivedKeys[name]; + } + /** + * Synchronously imports an existing key from file or Buffer + * @param name Unique name of the imported key + * @param key Key to be imported + */ + importKeySync(name, key) { + if (typeof key === 'string') { + this.derivedKeys[name] = this.fileSystem.readFileSync(key); + } + else { + this.derivedKeys[name] = key; + } + } + /** + * Asynchronously imports an existing key from file or Buffer + * @param name Unique name of the imported key + * @param key Key to be imported + */ + async importKey(name, key) { + if (typeof key === 'string') { + this.derivedKeys[name] = await this.fileSystem.promises.readFile(key); + } + else { + this.derivedKeys[name] = key; + } + } + /** + * Synchronously exports an existing key from file or Buffer + * @param name Name of the key to be exported + * @param dest Destination path + * @param createPath If set to true, the path is recursively created + */ + exportKeySync(name, dest, createPath) { + if (!this.derivedKeys.has(name)) { + throw Error(`There is no key loaded for name: ${name}`); + } + if (createPath) { + this.fileSystem.mkdirSync(path_1.default.dirname(dest), { recursive: true }); + } + this.fileSystem.writeFileSync(dest, this.derivedKeys[name]); + } + /** + * Asynchronously exports an existing key from file or Buffer + * @param name Name of the key to be exported + * @param dest Destination path + * @param createPath If set to true, the path is recursively created + */ + async exportKey(name, dest, createPath) { + if (!this.derivedKeys.has(name)) { + throw Error(`There is no key loaded for name: ${name}`); + } + if (createPath) { + await this.fileSystem.promises.mkdir(path_1.default.dirname(dest), { recursive: true }); + } + await this.fileSystem.promises.writeFile(dest, this.derivedKeys[name]); + } + /** + * Loads an identity from the given public key + * @param publicKey Buffer containing the public key + */ + async getIdentityFromPublicKey(publicKey) { + const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: publicKey }); + return identity; + } + /** + * Loads an identity from the given private key + * @param publicKey Buffer containing the public key + */ + async getIdentityFromPrivateKey(privateKey, passphrase) { + const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: privateKey }); + if (identity.is_pgp_locked()) { + await util_1.promisify(identity.unlock_pgp)({ passphrase: passphrase }); + } + return identity; + } + /** + * Signs the given data with the provided key or the primary key if none is specified + * @param data Buffer or file containing the data to be signed + * @param privateKey Buffer containing the key to sign with. Defaults to primary private key if no key is given. + * @param keyPassphrase Required if privateKey is provided. + */ + async signData(data, privateKey, keyPassphrase) { + let resolvedIdentity; + if (privateKey) { + if (!keyPassphrase) { + throw Error('passphrase for private key was not provided'); + } + resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase); + } + else if (this.primaryIdentity) { + resolvedIdentity = this.primaryIdentity; + } + else { + throw Error('key pair is not loaded'); + } + if (this.useWebWorkers && this.workerPool) { + const workerResponse = await this.workerPool.queue(async (workerCrypto) => { + return await workerCrypto.signData(data, resolvedIdentity); + }); + return workerResponse; + } + else { + const params = { + msg: data.toString(), + sign_with: resolvedIdentity, + }; + const result_string = await util_1.promisify(kbpgp_1.default.box)(params); + return Buffer.from(result_string); + } + } + /** + * Signs the given file with the provided key or the primary key if none is specified + * @param filePath Path to file containing the data to be signed + * @param privateKey The key to sign with. Defaults to primary public key if no key is given. + * @param keyPassphrase Required if privateKey is provided. + */ + async signFile(filePath, privateKey, keyPassphrase) { + // Get key if provided + let keyBuffer; + if (privateKey) { + if (typeof privateKey === 'string') { + // Path + // Read in from fs + keyBuffer = this.fileSystem.readFileSync(privateKey); + } + else { + // Buffer + keyBuffer = privateKey; + } + } + // Read file into buffer + const buffer = this.fileSystem.readFileSync(filePath); + // Sign the buffer + const signedBuffer = await this.signData(buffer, keyBuffer, keyPassphrase); + // Write buffer to signed file + const signedPath = `${filePath}.sig`; + this.fileSystem.writeFileSync(signedPath, signedBuffer); + return signedPath; + } + /** + * Verifies the given data with the provided key or the primary key if none is specified + * @param data Buffer or file containing the data to be verified + * @param signature The PGP signature + * @param publicKey Buffer containing the key to verify with. Defaults to primary public key if no key is given. + */ + async verifyData(data, signature, publicKey) { + const ring = new kbpgp_1.default.keyring.KeyRing(); + let resolvedIdentity; + if (publicKey) { + resolvedIdentity = await this.getIdentityFromPublicKey(publicKey); + } + else if (this.primaryIdentity) { + resolvedIdentity = this.primaryIdentity; + } + else { + throw Error('key pair is not loaded'); + } + ring.add_key_manager(resolvedIdentity); + if (this.useWebWorkers && this.workerPool) { + const workerResponse = await this.workerPool.queue(async (workerCrypto) => { + return await workerCrypto.verifyData(data, signature, resolvedIdentity); + }); + return workerResponse; + } + else { + const params = { + armored: signature, + data: data, + keyfetch: ring, + }; + const literals = await util_1.promisify(kbpgp_1.default.unbox)(params); + // Get the identity that signed the data if any + let dataSigner = literals[0].get_data_signer(); + // Retrieve the key manager associated with that data signer + let keyManager; + if (dataSigner) { + keyManager = dataSigner.get_key_manager(); + } + // If we know the pgp finger print then we say the data is verified. + // Otherwise it is unverified. + if (keyManager) { + if (keyManager.get_pgp_fingerprint()) { + return true; + } + else { + return false; + } + } + else { + return false; + } + } + } + /** + * Verifies the given file with the provided key or the primary key if none is specified + * @param filePath Path to file containing the data to be verified + * @param signaturePath The path to the file containing the PGP signature + * @param publicKey Buffer containing the key to verify with. Defaults to primary public key if no key is given. + */ + async verifyFile(filePath, signaturePath, publicKey) { + // Get key if provided + let keyBuffer; + if (publicKey) { + if (typeof publicKey === 'string') { + // Path + // Read in from fs + keyBuffer = this.fileSystem.readFileSync(publicKey); + } + else { + // Buffer + keyBuffer = publicKey; + } + } + // Read in file buffer and signature + const fileBuffer = this.fileSystem.readFileSync(filePath); + const signatureBuffer = this.fileSystem.readFileSync(signaturePath); + const isVerified = await this.verifyData(fileBuffer, signatureBuffer, keyBuffer); + return isVerified; + } + /** + * Encrypts the given data for a specific public key + * @param data The data to be encrypted + * @param publicKey The key to encrypt for + */ + async encryptData(data, publicKey) { + let resolvedIdentity; + if (publicKey) { + resolvedIdentity = await this.getIdentityFromPublicKey(publicKey); + } + else if (this.primaryIdentity) { + resolvedIdentity = this.primaryIdentity; + } + else { + throw Error(`Identity could not be resolved for encrypting`); + } + if (this.useWebWorkers && this.workerPool) { + const workerResponse = await this.workerPool.queue(async (workerCrypto) => { + return await workerCrypto.encryptData(data, resolvedIdentity); + }); + return workerResponse; + } + else { + const params = { + msg: data, + encrypt_for: resolvedIdentity, + }; + const result_string = await util_1.promisify(kbpgp_1.default.box)(params); + return result_string; + } + } + /** + * Decrypts the given data with the provided key or the primary key if none is given + * @param data The data to be decrypted + * @param privateKey The key to decrypt with. Defaults to primary private key if no key is given. + * @param keyPassphrase Required if privateKey is provided. + */ + async decryptData(data, privateKey, keyPassphrase) { + var ring = new kbpgp_1.default.keyring.KeyRing(); + let resolvedIdentity; + if (privateKey) { + if (keyPassphrase) { + resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase); + } + else { + throw Error('A key passphrase must be supplied if a privateKey is specified'); + } + } + else if (this.primaryIdentity) { + resolvedIdentity = this.primaryIdentity; + } + else { + throw Error('no identity available for decrypting'); + } + if (this.useWebWorkers && this.workerPool) { + const workerResponse = await this.workerPool.queue(async (workerCrypto) => { + return await workerCrypto.decryptData(data, resolvedIdentity); + }); + return workerResponse; + } + else { + ring.add_key_manager(resolvedIdentity); + const params = { + armored: data.toString(), + keyfetch: ring, + }; + const literals = await util_1.promisify(kbpgp_1.default.unbox)(params); + const decryptedData = Buffer.from(literals[0].toString()); + return decryptedData; + } + } + ///////// + // PKI // + ///////// + get PKIInfo() { + return this.pkiInfo; + } + loadPKIInfo(key, cert, caCert, writeToFile = false) { + if (key) { + this.pkiInfo.key = key; + } + if (cert) { + this.pkiInfo.cert = cert; + } + if (caCert) { + this.pkiInfo.caCert = caCert; + } + if (writeToFile) { + // Store in the metadata path folder + const storagePath = path_1.default.dirname(this.metadataPath); + if (key) { + this.metadata.pkiKeyPath = path_1.default.join(storagePath, 'pki_private_key'); + fs_1.default.writeFileSync(this.metadata.pkiKeyPath, key); + } + if (cert) { + this.metadata.pkiCertPath = path_1.default.join(storagePath, 'pki_cert'); + fs_1.default.writeFileSync(this.metadata.pkiCertPath, cert); + } + if (caCert) { + this.metadata.caCertPath = path_1.default.join(storagePath, 'ca_cert'); + fs_1.default.writeFileSync(this.metadata.caCertPath, caCert); + } + } + } + /* ============ HELPERS =============== */ + /** + * Get the key for a given name + * @param name The unique name of the desired key + */ + getKey(name) { + return this.derivedKeys[name]; + } + /** + * Determines if the Key Manager has a certain key + * @param name The unique name of the desired key + */ + hasKey(name) { + if (this.derivedKeys[name]) { + return true; + } + return false; + } + writeMetadata() { + const metadata = JSON.stringify(this.metadata); + this.fileSystem.writeFileSync(this.metadataPath, metadata); + } + loadMetadata() { + // Check if file exists + if (this.fileSystem.existsSync(this.metadataPath)) { + const metadata = this.fileSystem.readFileSync(this.metadataPath).toString(); + this.metadata = JSON.parse(metadata); + } + } +} +exports.default = KeyManager; + + +/***/ }), +/* 21 */ +/***/ (function(module, exports) { + +module.exports = require("kbpgp"); + +/***/ }), +/* 22 */ +/***/ (function(module, exports) { + +module.exports = require("util"); + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os_1 = __importDefault(__webpack_require__(1)); +const path_1 = __importDefault(__webpack_require__(0)); +const grpc = __importStar(__webpack_require__(6)); +const GitClient_1 = __importDefault(__webpack_require__(24)); +const GitBackend_1 = __importDefault(__webpack_require__(25)); +const Peer_1 = __webpack_require__(37); +const utils_1 = __webpack_require__(38); +const PeerInfo_1 = __importStar(__webpack_require__(14)); +const MulticastBroadcaster_1 = __importDefault(__webpack_require__(39)); +const Git_grpc_pb_1 = __webpack_require__(7); +const Git_pb_1 = __webpack_require__(8); +const keybaseDiscovery = { + name: 'Keybase', + findUser: async (handle, service) => { + const url = `https://keybase.io/_/api/1.0/user/lookup.json?${service}=${handle}`; + try { + const response = await fetch(url); + const data = await response.json(); + const pubKey = data.them[0].public_keys.primary.bundle; + return pubKey; + } + catch (err) { + throw Error(`User was not found: ${err.message}`); + } + }, +}; +class PeerManager { + constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager, vaultManager, peerInfo, socialDiscoveryServices = []) { + var _a; + this.metadata = { localPeerInfo: null }; + this.serverStarted = false; + this.fileSystem = fileSystem; + this.fileSystem.mkdirSync(polykeyPath, { recursive: true }); + this.metadataPath = path_1.default.join(polykeyPath, '.peerMetadata'); + // Set given variables + this.keyManager = keyManager; + this.socialDiscoveryServices = socialDiscoveryServices; + // Load metadata with peer info + this.loadMetadata(); + // Load peer store and local peer info + if (peerInfo) { + this.localPeerInfo = peerInfo; + this.writeMetadata(); + } + else if (this.metadata.localPeerInfo) { + this.localPeerInfo = this.metadata.localPeerInfo; + } + else if (this.keyManager.hasPublicKey()) { + this.localPeerInfo = new PeerInfo_1.default(this.keyManager.getPublicKey()); + } + this.peerStore = new Map(); + this.socialDiscoveryServices = []; + this.socialDiscoveryServices.push(keybaseDiscovery); + for (const service of socialDiscoveryServices) { + this.socialDiscoveryServices.push(service); + } + this.multicastBroadcaster = new MulticastBroadcaster_1.default(this.addPeer, this.localPeerInfo, this.keyManager); + this.peerConnections = new Map(); + ///////////////// + // GRPC Server // + ///////////////// + this.gitBackend = new GitBackend_1.default(polykeyPath, vaultManager); + this.server = new grpc.Server(); + // Add service + this.server.addService(Git_grpc_pb_1.GitServerService, { + requestInfo: this.requestInfo.bind(this), + requestPack: this.requestPack.bind(this), + }); + // Create the server credentials. SSL only if ca cert exists + const pkiInfo = this.keyManager.PKIInfo; + if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) { + this.credentials = grpc.ServerCredentials.createSsl(pkiInfo.caCert, [ + { + private_key: pkiInfo.key, + cert_chain: pkiInfo.cert, + }, + ], true); + } + else { + this.credentials = grpc.ServerCredentials.createInsecure(); + } + this.server.bindAsync(`0.0.0.0:${(_a = process.env.PK_PORT) !== null && _a !== void 0 ? _a : 0}`, this.credentials, (err, boundPort) => { + if (err) { + throw err; + } + else { + const address = new PeerInfo_1.Address('localhost', boundPort.toString()); + this.server.start(); + this.localPeerInfo.connect(address); + this.serverStarted = true; + } + }); + } + async requestInfo(call, callback) { + const infoRequest = call.request; + const vaultName = infoRequest.getVaultname(); + const infoReply = new Git_pb_1.InfoReply(); + infoReply.setVaultname(vaultName); + infoReply.setBody(await this.gitBackend.handleInfoRequest(vaultName)); + callback(null, infoReply); + } + async requestPack(call, callback) { + const packRequest = call.request; + const vaultName = packRequest.getVaultname(); + const body = Buffer.from(packRequest.getBody_asB64(), 'base64'); + const reply = new Git_pb_1.PackReply(); + reply.setVaultname(vaultName); + reply.setBody(await this.gitBackend.handlePackRequest(vaultName, body)); + callback(null, reply); + } + //////////////// + // Peer store // + //////////////// + /** + * Get the peer info of the current keynode + */ + getLocalPeerInfo() { + return this.localPeerInfo; + } + /** + * Set the address of the active server + * @param adress Address of active server + */ + connectLocalPeerInfo(address) { + this.localPeerInfo.connect(address); + } + /** + * Add a peer's info to the peerStore + * @param peerInfo Info of the peer to be added + */ + addPeer(peerInfo) { + this.peerStore.set(peerInfo.publicKey, peerInfo); + } + /** + * Retrieves a peer for the given public key + * @param publicKey Public key of the desired peer + */ + getPeer(publicKey) { + var _a; + return (_a = this.peerStore.get(publicKey)) !== null && _a !== void 0 ? _a : null; + } + /** + * Determines if the peerStore contains the desired peer + * @param publicKey Public key of the desired peer + */ + hasPeer(pubKey) { + return this.peerStore.has(pubKey); + } + ////////////////////// + // Social discovery // + ////////////////////// + /** + * Finds an existing peer using multicast peer discovery + * @param publicKey Public key of the desired peer + */ + async findPubKey(publicKey) { + return new Promise((resolve, reject) => { + this.multicastBroadcaster.requestPeerContact(publicKey); + this.multicastBroadcaster.on('found', (peerInfo) => { + if (peerInfo.publicKey == publicKey) { + resolve(peerInfo); + } + }); + this.multicastBroadcaster.on('timeout', (timedOutPubKey) => { + if (timedOutPubKey == publicKey) { + reject('The broadcaster stopped looking'); + } + }); + }); + } + /** + * Finds an existing peer given a social service and handle + * @param handle Username or handle of the user (e.g. @john-smith) + * @param service Service on which to search for the user (e.g. github) + */ + async findSocialUser(handle, service) { + const tasks = []; + for (const socialDiscovery of this.socialDiscoveryServices) { + try { + tasks.push(socialDiscovery.findUser(handle, service)); + } + catch (error) { + console.log(`Could not find user on this discovery service: ${socialDiscovery.name}`); + } + } + const pubKeyOrFail = await utils_1.firstPromiseFulfilled(tasks); + if (pubKeyOrFail.length > 1) { + throw Error('Could not find public key from services'); + } + const pubKeyFound = pubKeyOrFail[0]; + const peerInfo = await this.findPubKey(pubKeyFound); + return peerInfo; + } + /////////////////////// + // Peers Connections // + /////////////////////// + /** + * Get a secure connection to the peer + * @param peer Public key of an existing peer or address of new peer + */ + connectToPeer(peer) { + var _a; + // Throw error if trying to connect to self + if (peer == this.localPeerInfo.connectedAddr || peer == this.localPeerInfo.publicKey) { + throw Error('Cannot connect to self'); + } + let address; + if (typeof peer == 'string') { + const existingSocket = this.peerConnections.get(peer); + if (existingSocket) { + return existingSocket; + } + const peerAddress = (_a = this.getPeer(peer)) === null || _a === void 0 ? void 0 : _a.connectedAddr; + if (peerAddress) { + address = peerAddress; + } + else { + throw Error('Peer does not exist in peer store'); + } + } + else { + address = peer; + } + const conn = new GitClient_1.default(address, this.keyManager); + if (typeof peer == 'string') { + this.peerConnections.set(peer, conn); + } + return conn; + } + /* ============ HELPERS =============== */ + writeMetadata() { + var _a; + const peerInfo = this.localPeerInfo; + const metadata = Peer_1.peer.PeerInfoMessage.encode({ + addresses: peerInfo.AdressStringList, + connectedAddr: (_a = peerInfo.connectedAddr) === null || _a === void 0 ? void 0 : _a.toString(), + pubKey: peerInfo.publicKey, + }).finish(); + this.fileSystem.writeFileSync(this.metadataPath, metadata); + } + loadMetadata() { + // Check if file exists + if (this.fileSystem.existsSync(this.metadataPath)) { + const metadata = this.fileSystem.readFileSync(this.metadataPath); + const { addresses, connectedAddr, pubKey } = Peer_1.peer.PeerInfoMessage.decode(metadata); + this.localPeerInfo = new PeerInfo_1.default(pubKey, addresses, connectedAddr); + } + } +} +exports.default = PeerManager; + + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const grpc = __importStar(__webpack_require__(6)); +const Git_grpc_pb_1 = __webpack_require__(7); +const Git_pb_1 = __webpack_require__(8); +/** + * Responsible for converting HTTP messages from isomorphic-git into requests and sending them to a specific peer. + */ +class GitClient { + constructor(address, keyManager) { + const pkiInfo = keyManager.PKIInfo; + if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) { + this.credentials = grpc.credentials.createSsl(pkiInfo.caCert, pkiInfo.key, pkiInfo.cert); + } + else { + this.credentials = grpc.credentials.createInsecure(); + } + this.client = new Git_grpc_pb_1.GitServerClient(address.toString(), this.credentials); + } + /** + * The custom http request method to feed into isomorphic-git's [custom http object](https://isomorphic-git.org/docs/en/http) + */ + async request({ url, method, headers, body, onProgress }) { + // eslint-disable-next-line + return new Promise(async (resolve, reject) => { + const u = new URL(url); + // Parse request + if (method == 'GET') { + // Info request + const match = u.pathname.match(/\/(.+)\/info\/refs$/); + if (!match || /\.\./.test(match[1])) { + reject(new Error('Error')); + } + const vaultName = match[1]; + const infoResponse = await this.requestInfo(vaultName); + resolve({ + url: url, + method: method, + statusCode: 200, + statusMessage: 'OK', + body: this.iteratorFromData(infoResponse), + headers: headers, + }); + } + else if (method == 'POST') { + // Info request + const match = u.pathname.match(/\/(.+)\/git-(.+)/); + if (!match || /\.\./.test(match[1])) { + reject(new Error('Error')); + } + const vaultName = match[1]; + const packResponse = await this.requestPack(vaultName, body[0]); + resolve({ + url: url, + method: method, + statusCode: 200, + statusMessage: 'OK', + body: this.iteratorFromData(packResponse), + headers: headers, + }); + } + else { + reject(new Error('Method not supported')); + } + }); + } + // ==== HELPER METHODS ==== // + /** + * Requests remote info from the connected peer for the named vault. + * @param vaultName Name of the desired vault + */ + async requestInfo(vaultName) { + return new Promise((resolve, reject) => { + const request = new Git_pb_1.InfoRequest(); + request.setVaultname(vaultName); + this.client.requestInfo(request, function (err, response) { + if (err) { + reject(err); + } + else { + resolve(Buffer.from(response.getBody_asB64(), 'base64')); + } + }); + }); + } + /** + * Requests a pack from the connected peer for the named vault. + * @param vaultName Name of the desired vault + */ + async requestPack(vaultName, body) { + return new Promise((resolve, reject) => { + const request = new Git_pb_1.PackRequest(); + request.setVaultname(vaultName); + request.setBody(body); + this.client.requestPack(request, function (err, response) { + if (err) { + reject(err); + } + else { + resolve(Buffer.from(response.getBody_asB64(), 'base64')); + } + }); + }); + } + /** + * Converts a buffer into an iterator expected by isomorphic git. + * @param data Data to be turned into an iterator + */ + iteratorFromData(data) { + let ended = false; + return { + next() { + return new Promise((resolve, reject) => { + if (ended) { + return resolve({ done: true }); + } + else { + ended = true; + resolve({ value: data, done: false }); + } + }); + }, + }; + } +} +exports.default = GitClient; + + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path_1 = __importDefault(__webpack_require__(0)); +const readable_stream_1 = __webpack_require__(3); +const uploadPack_1 = __importDefault(__webpack_require__(26)); +const GitSideBand_1 = __importDefault(__webpack_require__(28)); +const packObjects_1 = __importDefault(__webpack_require__(30)); +// Here is the protocol git outlines for sending pack files over http: +// https://git-scm.com/docs/pack-protocol/2.17.0 +// https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt +// This should be consulted in developing our upload pack implementation +// This git backend (as well as HttpDuplex class) is heavily inspired by node-git-server: +// https://github.com/gabrielcsapo/node-git-server +// We need someway to notify other agents about what vaults we have based on some type of authorisation because they don't explicitly know about them +class GitBackend { + constructor(polykeyPath, vaultManager) { + this.polykeyPath = polykeyPath; + this.vaultManager = vaultManager; + } + /** + * Find out whether vault exists. + * @param vaultName Name of vault to check + * @param publicKey Public key of peer trying to access vault + */ + exists(vaultName, publicKey) { + try { + const vault = this.vaultManager.getVault(vaultName); + if (vault) { + return vault.peerCanAccess(publicKey); + } + return false; + } + catch (error) { + return false; + } + } + async handleInfoRequest(vaultName) { + var _a; + // Only handle upload-pack for now + const service = 'upload-pack'; + const connectingPublicKey = ''; + const responseBuffers = []; + if (!this.exists(vaultName, connectingPublicKey)) { + throw Error('Vault does not exist'); + } + else { + responseBuffers.push(Buffer.from(this.createGitPacketLine('# service=git-' + service + '\n'))); + responseBuffers.push(Buffer.from('0000')); + const fileSystem = (_a = this.vaultManager.getVault(vaultName)) === null || _a === void 0 ? void 0 : _a.EncryptedFS; + const buffers = await uploadPack_1.default(fileSystem, path_1.default.join(this.polykeyPath, vaultName), undefined, true); + const buffersToWrite = buffers !== null && buffers !== void 0 ? buffers : []; + responseBuffers.push(...buffersToWrite); + } + return Buffer.concat(responseBuffers); + } + async handlePackRequest(vaultName, body) { + // eslint-disable-next-line + return new Promise(async (resolve, reject) => { + var _a; + const responseBuffers = []; + // Check if vault exists + const connectingPublicKey = ''; + if (!this.exists(vaultName, connectingPublicKey)) { + throw Error('Vault does not exist'); + } + const fileSystem = (_a = this.vaultManager.getVault(vaultName)) === null || _a === void 0 ? void 0 : _a.EncryptedFS; + if (fileSystem) { + if (body.toString().slice(4, 8) == 'want') { + const wantedObjectId = body.toString().slice(9, 49); + const packResult = await packObjects_1.default(fileSystem, path_1.default.join(this.polykeyPath, vaultName), [wantedObjectId], undefined); + // This the 'wait for more data' line as I understand it + responseBuffers.push(Buffer.from('0008NAK\n')); + // This is to get the side band stuff working + const readable = new readable_stream_1.PassThrough(); + const progressStream = new readable_stream_1.PassThrough(); + const sideBand = GitSideBand_1.default.mux('side-band-64', readable, packResult.packstream, progressStream, []); + sideBand.on('data', (data) => { + responseBuffers.push(data); + }); + sideBand.on('end', () => { + resolve(Buffer.concat(responseBuffers)); + }); + sideBand.on('error', (err) => { + reject(err); + }); + // Write progress to the client + progressStream.write(Buffer.from('0014progress is at 50%\n')); + progressStream.end(); + } + } + }); + } + // ============ Helper functions ============ // + createGitPacketLine(line) { + const hexPrefix = (4 + line.length).toString(16); + return Array(4 - hexPrefix.length + 1).join('0') + hexPrefix + line; + } +} +exports.default = GitBackend; + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path_1 = __importDefault(__webpack_require__(0)); +const GitPktLine_1 = __importDefault(__webpack_require__(9)); +const GitRefManager_1 = __importDefault(__webpack_require__(10)); +async function writeRefsAdResponse({ capabilities, refs, symrefs }) { + const stream = []; + // Compose capabilities string + let syms = ''; + for (const [key, value] of Object.entries(symrefs)) { + syms += `symref=${key}:${value} `; + } + let caps = `\x00${[...capabilities].join(' ')} ${syms}agent=git/isomorphic-git@1.4.0`; + // stream.write(GitPktLine.encode(`# service=${service}\n`)) + // stream.write(GitPktLine.flush()) + // Note: In the edge case of a brand new repo, zero refs (and zero capabilities) + // are returned. + for (const [key, value] of Object.entries(refs)) { + stream.push(GitPktLine_1.default.encode(`${value} ${key}${caps}\n`)); + caps = ''; + } + stream.push(GitPktLine_1.default.flush()); + return stream; +} +async function uploadPack(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), advertiseRefs = false) { + try { + if (advertiseRefs) { + // Send a refs advertisement + const capabilities = ['side-band-64k']; + let keys = await GitRefManager_1.default.listRefs(fileSystem, gitdir, 'refs'); + keys = keys.map((ref) => `refs/${ref}`); + const refs = {}; + keys.unshift('HEAD'); // HEAD must be the first in the list + for (const key of keys) { + refs[key] = await GitRefManager_1.default.resolve(fileSystem, gitdir, key); + } + const symrefs = {}; + symrefs['HEAD'] = await GitRefManager_1.default.resolve(fileSystem, gitdir, 'HEAD', 2); + return writeRefsAdResponse({ + capabilities, + refs, + symrefs, + }); + } + } + catch (err) { + err.caller = 'git.uploadPack'; + throw err; + } +} +exports.default = uploadPack; + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +class GitPackedRefs { + constructor(text) { + this.refs = new Map(); + this.parsedConfig = []; + if (text) { + let key; + this.parsedConfig = text + .trim() + .split('\n') + .map((line) => { + if (/^\s*#/.test(line)) { + return { line: line, comment: true }; + } + const i = line.indexOf(' '); + if (line.startsWith('^')) { + // This is a oid for the commit associated with the annotated tag immediately preceding this line. + // Trim off the '^' + const value = line.slice(1); + // The tagname^{} syntax is based on the output of `git show-ref --tags -d` + this.refs.set(key + '^{}', value); + return { line: line, ref: key, peeled: value }; + } + else { + // This is an oid followed by the ref name + const value = line.slice(0, i); + key = line.slice(i + 1); + this.refs.set(key, value); + return { line: line, ref: key, oid: value }; + } + }); + } + return this; + } + static from(text) { + return new GitPackedRefs(text); + } +} +exports.default = GitPackedRefs; + + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/* +If 'side-band' or 'side-band-64k' capabilities have been specified by +the client, the server will send the packfile data multiplexed. + +Each packet starting with the packet-line length of the amount of data +that follows, followed by a single byte specifying the sideband the +following data is coming in on. + +In 'side-band' mode, it will send up to 999 data bytes plus 1 control +code, for a total of up to 1000 bytes in a pkt-line. In 'side-band-64k' +mode it will send up to 65519 data bytes plus 1 control code, for a +total of up to 65520 bytes in a pkt-line. + +The sideband byte will be a '1', '2' or a '3'. Sideband '1' will contain +packfile data, sideband '2' will be used for progress information that the +client will generally print to stderr and sideband '3' is used for error +information. + +If no 'side-band' capability was specified, the server will stream the +entire packfile without multiplexing. +*/ +const buffer_1 = __webpack_require__(29); +const readable_stream_1 = __webpack_require__(3); +const GitPktLine_1 = __importDefault(__webpack_require__(9)); +function splitBuffer(buffer, maxBytes) { + const result = []; + let index = 0; + while (index < buffer.length) { + const buf = buffer.slice(index, index + maxBytes); + result.push(buf); + index += buf.length; + } + result.push(buffer.slice(index)); + return result; +} +class GitSideBand { + static demux(input) { + let read = GitPktLine_1.default.streamReader(input); + // And now for the ridiculous side-band or side-band-64k protocol + let packetlines = new readable_stream_1.PassThrough(); + let packfile = new readable_stream_1.PassThrough(); + let progress = new readable_stream_1.PassThrough(); + // TODO: Use a proper through stream? + const nextBit = async function () { + let line = await read(); + // Skip over flush packets + if (line === null) + return nextBit(); + // A made up convention to signal there's no more to read. + if (line === true) { + packetlines.end(); + progress.end(); + packfile.end(); + return; + } + // Examine first byte to determine which output "stream" to use + switch (line[0]) { + case 1: // pack data + packfile.write(line.slice(1)); + break; + case 2: // progress message + progress.write(line.slice(1)); + break; + case 3: // fatal error message just before stream aborts + // eslint-disable-next-line + const error = line.slice(1); + progress.write(error); + packfile.destroy(new Error(error.toString('utf8'))); + return; + default: + // Not part of the side-band-64k protocol + packetlines.write(line.slice(0)); + } + // Careful not to blow up the stack. + // I think Promises in a tail-call position should be OK. + nextBit(); + }; + nextBit(); + return { + packetlines, + packfile, + progress, + }; + } + static mux(protocol, // 'side-band' or 'side-band-64k' + packetlines, packfile, progress, error) { + const MAX_PACKET_LENGTH = protocol === 'side-band-64k' ? 999 : 65519; + let output = new readable_stream_1.PassThrough(); + packetlines.on('data', (data) => { + if (data === null) { + output.write(GitPktLine_1.default.flush()); + } + else { + output.write(GitPktLine_1.default.encode(data)); + } + }); + let packfileWasEmpty = true; + let packfileEnded = false; + let progressEnded = false; + let errorEnded = true; + let goodbye = buffer_1.Buffer.concat([GitPktLine_1.default.encode(buffer_1.Buffer.from('010A', 'hex')), GitPktLine_1.default.flush()]); + packfile + .on('data', (data) => { + packfileWasEmpty = false; + const buffers = splitBuffer(data, MAX_PACKET_LENGTH); + for (const buffer of buffers) { + output.write(GitPktLine_1.default.encode(buffer_1.Buffer.concat([buffer_1.Buffer.from('01', 'hex'), buffer]))); + } + }) + .on('end', () => { + packfileEnded = true; + if (!packfileWasEmpty) + output.write(goodbye); + if (progressEnded && errorEnded) + output.end(); + }); + progress + .on('data', (data) => { + const buffers = splitBuffer(data, MAX_PACKET_LENGTH); + for (const buffer of buffers) { + output.write(GitPktLine_1.default.encode(buffer_1.Buffer.concat([buffer_1.Buffer.from('02', 'hex'), buffer]))); + } + }) + .on('end', () => { + progressEnded = true; + if (packfileEnded && errorEnded) + output.end(); + }); + // error + // .on('data', data => { + // const buffers = splitBuffer(data, MAX_PACKET_LENGTH) + // for (const buffer of buffers) { + // output.write( + // GitPktLine.encode(Buffer.concat([Buffer.from('03', 'hex'), buffer])) + // ) + // } + // }) + // .on('end', () => { + // errorEnded = true + // if (progressEnded && packfileEnded) output.end() + // }) + return output; + } +} +exports.default = GitSideBand; + + +/***/ }), +/* 29 */ +/***/ (function(module, exports) { + +module.exports = require("buffer"); + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const pako_1 = __importDefault(__webpack_require__(11)); +const path_1 = __importDefault(__webpack_require__(0)); +const log_1 = __importDefault(__webpack_require__(31)); +const GitTree_1 = __importDefault(__webpack_require__(35)); +const sha_js_1 = __importDefault(__webpack_require__(36)); +const GitCommit_1 = __importDefault(__webpack_require__(12)); +const readable_stream_1 = __webpack_require__(3); +const GitObjectManager_1 = __importDefault(__webpack_require__(13)); +const types = { + commit: 0b0010000, + tree: 0b0100000, + blob: 0b0110000, + tag: 0b1000000, + ofs_delta: 0b1100000, + ref_delta: 0b1110000, +}; +/** + * Create a packfile stream + * + * @link https://isomorphic-git.github.io/docs/packObjects.html + */ +async function packObjects(fileSystem, dir, refs, depth, haves) { + const gitdir = path_1.default.join(dir, '.git'); + let oids = new Set(); + let shallows = new Set(); + let unshallows = new Set(); + let acks = []; + haves = haves ? haves : []; + const emitter = undefined; + const since = undefined; + for (const ref of refs) { + try { + let commits = await log_1.default(fileSystem, dir, gitdir, emitter, ref, depth, since); + let oldshallows = []; + for (let i = 0; i < commits.length; i++) { + let commit = commits[i]; + if (haves.includes(commit.oid)) { + acks.push({ + oid: ref, + }); + break; + } + oids.add(commit.oid); + if (i === commits.length - 1) { + if (!oldshallows.includes(commit.oid) && (depth !== undefined || since !== undefined)) { + console.log('make it shallow', commit.oid); + shallows.add(commit.oid); + } + } + else if (oldshallows.includes(commit.oid)) { + console.log('make it unshallow', commit.oid); + unshallows.add(commit.oid); + } + } + } + catch (err) { + console.log(err); + // oh well. + } + } + let objects = await listObjects(fileSystem, dir, gitdir, Array.from(oids)); + let packstream = new readable_stream_1.PassThrough(); + pack(fileSystem, dir, undefined, [...objects], packstream); + return { packstream, shallows, unshallows, acks }; +} +async function listObjects(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), oids) { + let commits = new Set(); + let trees = new Set(); + let blobs = new Set(); + // We don't do the purest simplest recursion, because we can + // avoid reading Blob objects entirely since the Tree objects + // tell us which oids are Blobs and which are Trees. And we + // do not need to recurse through commit parents. + async function walk(oid) { + let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid); + if (type === 'commit') { + commits.add(oid); + let commit = GitCommit_1.default.from(object); + let tree = commit.headers().tree; + await walk(tree); + } + else if (type === 'tree') { + trees.add(oid); + let tree = GitTree_1.default.from(object); + for (let entry of tree) { + if (entry.type === 'blob') { + blobs.add(entry.oid); + } + // only recurse for trees + if (entry.type === 'tree') { + await walk(entry.oid); + } + } + } + } + // Let's go walking! + for (let oid of oids) { + await walk(oid); + } + return [...commits, ...trees, ...blobs]; +} +exports.listObjects = listObjects; +async function pack(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), oids, outputStream) { + let hash = sha_js_1.default('sha1'); + function write(chunk, enc = undefined) { + if (enc) { + outputStream.write(chunk, enc); + } + else { + outputStream.write(chunk); + } + hash.update(chunk, enc); + } + function writeObject(object, stype) { + let lastFour; + let multibyte; + let length; + // Object type is encoded in bits 654 + let type = types[stype]; + if (type === undefined) + throw Error('Unrecognized type: ' + stype); + // The length encoding get complicated. + length = object.length; + // Whether the next byte is part of the variable-length encoded number + // is encoded in bit 7 + multibyte = length > 0b1111 ? 0b10000000 : 0b0; + // Last four bits of length is encoded in bits 3210 + lastFour = length & 0b1111; + // Discard those bits + length = length >>> 4; + // The first byte is then (1-bit multibyte?), (3-bit type), (4-bit least sig 4-bits of length) + let byte = (multibyte | type | lastFour).toString(16); + write(byte, 'hex'); + // Now we keep chopping away at length 7-bits at a time until its zero, + // writing out the bytes in what amounts to little-endian order. + while (multibyte) { + multibyte = length > 0b01111111 ? 0b10000000 : 0b0; + byte = multibyte | (length & 0b01111111); + const unpaddedChunk = byte.toString(16); + const paddedChunk = '0'.repeat(2 - unpaddedChunk.length) + unpaddedChunk; + write(paddedChunk, 'hex'); + length = length >>> 7; + } + // Lastly, we can compress and write the object. + write(Buffer.from(pako_1.default.deflate(object))); + } + write('PACK'); + write('00000002', 'hex'); + // Write a 4 byte (32-bit) int + const unpaddedChunk = oids.length.toString(16); + const paddedChunk = '0'.repeat(8 - unpaddedChunk.length) + unpaddedChunk; + write(paddedChunk, 'hex'); + for (let oid of oids) { + let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid); + writeObject(object, type); + } + // Write SHA1 checksum + let digest = hash.digest(); + outputStream.end(digest); + return outputStream; +} +exports.pack = pack; +exports.default = packObjects; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = __webpack_require__(0); +const GitCommit_1 = __importDefault(__webpack_require__(12)); +const GitObjectManager_1 = __importDefault(__webpack_require__(13)); +const GitRefManager_1 = __importDefault(__webpack_require__(10)); +async function logCommit(fileSystem, gitdir, oid, signing) { + try { + let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid); + if (type !== 'commit') { + throw new Error('expected type to be commit'); + } + const commit = GitCommit_1.default.from(object); + const result = Object.assign({ oid }, commit.parse()); + if (signing) { + result.payload = commit.withoutSignature(); + } + return result; + } + catch (err) { + return { + oid, + error: err, + }; + } +} +exports.logCommit = logCommit; +function compareAge(a, b) { + return a.committer.timestamp - b.committer.timestamp; +} +/** + * Get commit descriptions from the git history + * + * @link https://isomorphic-git.github.io/docs/log.html + */ +async function log(fileSystem, dir, gitdir = path.join(dir, '.git'), ref = 'HEAD', depth, since, // Date +signing = false) { + try { + let sinceTimestamp = since === undefined ? undefined : Math.floor(since.valueOf() / 1000); + // TODO: In the future, we may want to have an API where we return a + // async iterator that emits commits. + let commits = []; + let oid = await GitRefManager_1.default.resolve(fileSystem, gitdir, ref); + let tips = [await logCommit(fileSystem, gitdir, oid, signing)]; + // eslint-disable-next-line + while (true) { + let commit = tips.pop(); + // Stop the loop if we encounter an error + if (commit.error) { + commits.push(commit); + break; + } + // Stop the log if we've hit the age limit + if (sinceTimestamp !== undefined && commit.committer.timestamp <= sinceTimestamp) { + break; + } + commits.push(commit); + // Stop the loop if we have enough commits now. + if (depth !== undefined && commits.length === depth) + break; + // Add the parents of this commit to the queue + // Note: for the case of a commit with no parents, it will concat an empty array, having no net effect. + for (const oid of commit.parent) { + let commit = await logCommit(fileSystem, gitdir, oid, signing); + if (!tips.map((commit) => commit.oid).includes(commit.oid)) { + tips.push(commit); + } + } + // Stop the loop if there are no more commit parents + if (tips.length === 0) + break; + // Process tips in order by age + tips.sort(compareAge); + } + return commits; + } + catch (err) { + err.caller = 'git.log'; + throw err; + } +} +exports.default = log; + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const shasum_1 = __importDefault(__webpack_require__(33)); +class GitObject { + static hash({ type, object }) { + let buffer = Buffer.concat([Buffer.from(`${type} ${object.byteLength.toString()}\0`), Buffer.from(object)]); + let oid = shasum_1.default(buffer); + return oid; + } + static wrap({ type, object }) { + let buffer = Buffer.concat([Buffer.from(`${type} ${object.byteLength.toString()}\0`), object]); + let oid = shasum_1.default(buffer); + return { + oid, + buffer, + }; + } + static unwrap({ oid, buffer }) { + if (oid) { + let sha = shasum_1.default(buffer); + if (sha !== oid) { + throw new Error(`SHA check failed! Expected ${oid}, computed ${sha}`); + } + } + let s = buffer.indexOf(32); // first space + let i = buffer.indexOf(0); // first null value + let type = buffer.slice(0, s).toString('utf8'); // get type of object + let length = buffer.slice(s + 1, i).toString('utf8'); // get type of object + let actualLength = buffer.length - (i + 1); + // verify length + if (parseInt(length) !== actualLength) { + throw new Error(`Length mismatch: expected ${length} bytes but got ${actualLength} instead.`); + } + return { + type, + object: Buffer.from(buffer.slice(i + 1)), + }; + } +} +exports.default = GitObject; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const sha1_1 = __importDefault(__webpack_require__(34)); +// This is modeled after @dominictarr's "shasum" module, +// but without the 'json-stable-stringify' dependency and +// extra type-casting features. +function shasum(buffer) { + return new sha1_1.default().update(buffer).digest('hex'); +} +exports.default = shasum; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports) { + +module.exports = require("sha.js/sha1"); + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +/*:: +type TreeEntry = { + mode: string, + path: string, + oid: string, + type?: string +} +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +function parseBuffer(buffer) { + let _entries = []; + let cursor = 0; + while (cursor < buffer.length) { + let space = buffer.indexOf(32, cursor); + if (space === -1) { + throw new Error(`GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next space character.`); + } + let nullchar = buffer.indexOf(0, cursor); + if (nullchar === -1) { + throw new Error(`GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next null character.`); + } + let mode = buffer.slice(cursor, space).toString('utf8'); + if (mode === '40000') + mode = '040000'; // makes it line up neater in printed output + let type = mode === '040000' ? 'tree' : 'blob'; + let path = buffer.slice(space + 1, nullchar).toString('utf8'); + let oid = buffer.slice(nullchar + 1, nullchar + 21).toString('hex'); + cursor = nullchar + 21; + _entries.push({ mode, path, oid, type }); + } + return _entries; +} +function limitModeToAllowed(mode) { + if (typeof mode === 'number') { + mode = mode.toString(8); + } + // tree + if (mode.match(/^0?4.*/)) + return '40000'; // Directory + if (mode.match(/^1006.*/)) + return '100644'; // Regular non-executable file + if (mode.match(/^1007.*/)) + return '100755'; // Regular executable file + if (mode.match(/^120.*/)) + return '120000'; // Symbolic link + if (mode.match(/^160.*/)) + return '160000'; // Commit (git submodule reference) + throw new Error(`Could not understand file mode: ${mode}`); +} +function nudgeIntoShape(entry) { + if (!entry.oid && entry.sha) { + entry.oid = entry.sha; // Github + } + entry.mode = limitModeToAllowed(entry.mode); // index + if (!entry.type) { + entry.type = 'blob'; // index + } + return entry; +} +class GitTree { + constructor(entries) { + if (Buffer.isBuffer(entries)) { + this._entries = parseBuffer(entries); + } + else if (Array.isArray(entries)) { + this._entries = entries.map(nudgeIntoShape); + } + else { + throw new Error('invalid type passed to GitTree constructor'); + } + } + static from(tree) { + return new GitTree(tree); + } + render() { + return this._entries.map((entry) => `${entry.mode} ${entry.type} ${entry.oid} ${entry.path}`).join('\n'); + } + toObject() { + return Buffer.concat(this._entries.map((entry) => { + let mode = Buffer.from(entry.mode.replace(/^0/, '')); + let space = Buffer.from(' '); + let path = Buffer.from(entry.path); + // let path = Buffer.from(entry.path, { encoding: 'utf8' }) + let nullchar = Buffer.from([0]); + let oid = Buffer.from(entry.oid.match(/../g).map((n) => parseInt(n, 16))); + return Buffer.concat([mode, space, path, nullchar, oid]); + })); + } + entries() { + return this._entries; + } + *[Symbol.iterator]() { + for (let entry of this._entries) { + yield entry; + } + } +} +exports.default = GitTree; + + +/***/ }), +/* 36 */ +/***/ (function(module, exports) { + +module.exports = require("sha.js"); + +/***/ }), +/* 37 */ +/***/ (function(module, exports) { + +module.exports = require("../../proto/js/Peer"); + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Returns a 5 character long random string of lower case letters + */ +function randomString() { + return Math.random() + .toString(36) + .replace(/[^a-z]+/g, '') + .substr(0, 5); +} +exports.randomString = randomString; +/** + * Inverts the provided promise + * @param p Promise to invert + */ +function invertPromise(p) { + return new Promise((res, rej) => p.then(rej, res)); +} +/** + * Gets the first promise fulfiled + * @param ps List of promises + */ +function firstPromiseFulfilled(ps) { + return invertPromise(Promise.all(ps.map(invertPromise))); +} +exports.firstPromiseFulfilled = firstPromiseFulfilled; + + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _a, _b; +Object.defineProperty(exports, "__esModule", { value: true }); +const dgram_1 = __importDefault(__webpack_require__(40)); +const crypto_1 = __importDefault(__webpack_require__(5)); +const PeerInfo_1 = __importDefault(__webpack_require__(14)); +const events_1 = __webpack_require__(41); +const Peer_js_1 = __webpack_require__(42); +const { HandshakeMessage, PeerInfoMessage } = Peer_js_1.peer; +// This module is based heavily on libp2p's mDNS module: +// https://github.com/libp2p/js-libp2p-mdns +// It is supposed to discover peers on the local network +// This module was also generated with the help of: +// https://nrempel.com/using-udp-multicast-with-node-js/ +// +// """ +// In computer networking, the multicast DNS (mDNS) protocol +// resolves hostnames to IP addresses within small networks +// that do not include a local name server +// """ +const UDP_MULTICAST_PORT = parseInt((_a = process.env.UDP_MULTICAST_PORT) !== null && _a !== void 0 ? _a : '5353'); +const UDP_MULTICAST_ADDR = (_b = process.env.UDP_MULTICAST_ADDR) !== null && _b !== void 0 ? _b : '224.0.0.251'; +class MulticastBroadcaster extends events_1.EventEmitter { + constructor(addPeer, localPeerInfo, keyManager) { + super(); + this.peerPubKeyMessages = new Map(); + this.addPeer = addPeer; + this.localPeerInfo = localPeerInfo; + this.keyManager = keyManager; + this.interval = 1e3; + this.queryInterval = null; + // Create socket + this.socket = dgram_1.default.createSocket({ type: 'udp4', reuseAddr: true }); + this.socket.bind(UDP_MULTICAST_PORT); + // Set up listener + this.socket.on('listening', (() => { + this.socket.addMembership(UDP_MULTICAST_ADDR); + const address = this.socket.address(); + }).bind(this)); + // Handle messages + this.socket.on('message', this.handleHandshakeMessages.bind(this)); + // Start the query process + this.queryInterval = this.queryLAN(); + } + /** + * Request a peer contact for the multicast peer discovery to check for + * @param publicKey Public key of the desired peer + */ + async requestPeerContact(publicKey) { + const pubKeyBuf = Buffer.from(publicKey); + const randomMessage = crypto_1.default.randomBytes(16); + // Encrypt message + const encryptedPeerPubKey = await this.keyManager.encryptData(pubKeyBuf, pubKeyBuf); + const encryptedRandomMessage = await this.keyManager.encryptData(randomMessage, pubKeyBuf); + const encryptedLocalPubKey = await this.keyManager.encryptData(Buffer.from(this.keyManager.getPublicKey()), pubKeyBuf); + // Add to peer messages to be sent over multicast + this.peerPubKeyMessages.set(publicKey, { + encryptedLocalPubKey: Buffer.from(encryptedLocalPubKey), + encryptedPeerPubKey: Buffer.from(encryptedPeerPubKey), + rawRandomMessage: randomMessage, + encryptedRandomMessage: Buffer.from(encryptedRandomMessage), + }); + } + // ==== Helper methods ==== // + queryLAN() { + const query = () => { + for (const pubKey of this.peerPubKeyMessages.keys()) { + const peerMessage = this.peerPubKeyMessages.get(pubKey); + if (peerMessage) { + const handshakeMessage = HandshakeMessage.encode({ + targetPubKey: peerMessage.encryptedPeerPubKey, + requestingPubKey: peerMessage.encryptedLocalPubKey, + message: peerMessage.encryptedRandomMessage, + }).finish(); + this.socket.send(handshakeMessage, 0, handshakeMessage.length, UDP_MULTICAST_PORT, UDP_MULTICAST_ADDR); + } + } + }; + // Immediately start a query, then do it every interval. + query(); + return setInterval(query, this.interval); + } + async handleHandshakeMessages(request, rinfo) { + var _a, _b; + try { + const { message, requestingPubKey, responsePeerInfo, targetPubKey } = HandshakeMessage.decode(request); + // Try to decrypt message and pubKey + const decryptedMessage = await this.keyManager.decryptData(Buffer.from(message)); + const decryptedTargetPubKey = await this.keyManager.decryptData(Buffer.from(targetPubKey)); + const decryptedRequestingPubKey = await this.keyManager.decryptData(Buffer.from(requestingPubKey)); + const myPubKey = this.keyManager.getPublicKey(); + if (decryptedRequestingPubKey.toString() == myPubKey) { + // Response + // Make sure decrypted bytes equal raw bytes in memory + const originalMessage = (_a = this.peerPubKeyMessages.get(decryptedTargetPubKey.toString())) === null || _a === void 0 ? void 0 : _a.rawRandomMessage; + if (decryptedMessage.toString() == (originalMessage === null || originalMessage === void 0 ? void 0 : originalMessage.toString())) { + // Validated! + // Add peer info to peerStore + const { addresses, connectedAddr, pubKey } = PeerInfoMessage.decode(responsePeerInfo); + const newPeerInfo = new PeerInfo_1.default(pubKey, addresses, connectedAddr); + if (newPeerInfo) { + this.addPeer(newPeerInfo); + // Remove peerId from requested messages + const pubKey = newPeerInfo.publicKey; + this.peerPubKeyMessages.delete(pubKey); + console.log(`New peer added to the store`); + this.emit('found', newPeerInfo); + } + else { + this.emit('error', 'I got a validated response. But no peerInfo'); + } + } + } + else { + // Requests on target node + // Try decrypting message + // Re-encrypt the data and send it on its way + const encryptedTargetPubKey = await this.keyManager.encryptData(Buffer.from(myPubKey), decryptedRequestingPubKey); + const encryptedMessage = await this.keyManager.encryptData(decryptedMessage, decryptedRequestingPubKey); + const encryptedPubKey = await this.keyManager.encryptData(decryptedRequestingPubKey, decryptedRequestingPubKey); + const encodedLocalPeerInfo = PeerInfoMessage.encode({ + addresses: this.localPeerInfo.AdressStringList, + connectedAddr: (_b = this.localPeerInfo.connectedAddr) === null || _b === void 0 ? void 0 : _b.toString(), + pubKey: this.localPeerInfo.publicKey, + }).finish(); + const handshakeMessage = HandshakeMessage.encode({ + targetPubKey: Buffer.from(encryptedTargetPubKey), + requestingPubKey: Buffer.from(encryptedPubKey), + message: Buffer.from(encryptedMessage), + responsePeerInfo: encodedLocalPeerInfo, + }).finish(); + this.socket.send(handshakeMessage, 0, handshakeMessage.length, UDP_MULTICAST_PORT, UDP_MULTICAST_ADDR); + } + } + catch (err) { + // Couldn't decode message + // We don't want the multicast discovery to error on every message it coudln't decode! + } + } +} +exports.default = MulticastBroadcaster; + + +/***/ }), +/* 40 */ +/***/ (function(module, exports) { + +module.exports = require("dgram"); + +/***/ }), +/* 41 */ +/***/ (function(module, exports) { + +module.exports = require("events"); + +/***/ }), +/* 42 */ +/***/ (function(module, exports) { + +module.exports = require("../../proto/js/Peer.js"); + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os_1 = __importDefault(__webpack_require__(1)); +const path_1 = __importDefault(__webpack_require__(0)); +const isomorphic_git_1 = __importDefault(__webpack_require__(15)); +const Vault_1 = __importDefault(__webpack_require__(44)); +const encryptedfs_1 = __webpack_require__(16); +class VaultManager { + constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager) { + this.polykeyPath = polykeyPath; + this.fileSystem = fileSystem; + this.keyManager = keyManager; + this.metadataPath = path_1.default.join(polykeyPath, '.vaultKeys'); + // Make polykeyPath if it doesn't exist + this.fileSystem.mkdirSync(this.polykeyPath, { recursive: true }); + // Initialize stateful variables + this.vaults = new Map(); + this.vaultKeys = new Map(); + // Read in vault keys + this.loadMetadata(); + // Initialize vaults in memory + for (const [vaultName, vaultKey] of this.vaultKeys.entries()) { + const path = path_1.default.join(this.polykeyPath, vaultName); + if (this.fileSystem.existsSync(path)) { + const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath); + this.vaults.set(vaultName, vault); + } + } + } + /** + * Get a vault from the vault manager + * @param vaultName Name of desired vault + */ + getVault(vaultName) { + if (this.vaults.has(vaultName)) { + const vault = this.vaults.get(vaultName); + return vault; + } + else if (this.vaultKeys.has(vaultName)) { + // vault not in map, create new instance + this.validateVault(vaultName); + const vaultKey = this.vaultKeys.get(vaultName); + const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath); + this.vaults.set(vaultName, vault); + return vault; + } + else { + throw Error('Vault does not exist in memory'); + } + } + /** + * Get a vault from the vault manager + * @param vaultName Unique name of new vault + * @param key Optional key to use for the vault encryption, otherwise it is generated + */ + async createVault(vaultName, key) { + if (this.vaultExists(vaultName)) { + throw Error('Vault already exists!'); + } + try { + const path = path_1.default.join(this.polykeyPath, vaultName); + // Directory not present, create one + this.fileSystem.mkdirSync(path, { recursive: true }); + // Create key if not provided + let vaultKey; + if (!key) { + // Generate new key + vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey()); + } + else { + // Assign key if it is provided + vaultKey = key; + } + this.vaultKeys.set(vaultName, vaultKey); + this.writeMetadata(); + // Create vault + const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath); + // Init repository for vault + const vaultPath = path_1.default.join(this.polykeyPath, vaultName); + const efs = vault.EncryptedFS; + const fileSystem = { promises: efs.promises }; + await isomorphic_git_1.default.init({ + fs: fileSystem, + dir: vaultPath, + }); + // Initial commit + await isomorphic_git_1.default.commit({ + fs: fileSystem, + dir: vaultPath, + author: { + name: vaultName, + }, + message: 'init commit', + }); + // Write packed-refs file because isomorphic git goes searching for it + // and apparently its not autogenerated + efs.writeFileSync(path_1.default.join(vaultPath, '.git', 'packed-refs'), '# pack-refs with: peeled fully-peeled sorted'); + // Set vault + this.vaults.set(vaultName, vault); + return this.getVault(vaultName); + } + catch (err) { + // Delete vault dir and garbage collect + this.destroyVault(vaultName); + throw err; + } + } + /** + * Get a vault from the vault manager + * @param vaultName Name of vault to be cloned + * @param address Address of polykey node that owns vault to be cloned + * @param getSocket Function to get an active connection to provided address + */ + async cloneVault(vaultName, gitClient) { + // Confirm it doesn't exist locally already + if (this.vaultExists(vaultName)) { + throw Error('Vault name already exists locally, try pulling instead'); + } + const vaultUrl = `http://0.0.0.0/${vaultName}`; + // First check if it exists on remote + const info = await isomorphic_git_1.default.getRemoteInfo({ + http: gitClient, + url: vaultUrl, + }); + if (!info.refs) { + throw Error(`Peer does not have vault: '${vaultName}'`); + } + // Create new efs first + // Generate new key + const vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey()); + // Set filesystem + const vfsInstance = new (__webpack_require__(17).VirtualFS)(); + const newEfs = new encryptedfs_1.EncryptedFS(vaultKey, vfsInstance, vfsInstance, this.fileSystem, process); + // Clone vault from address + await isomorphic_git_1.default.clone({ + fs: { promises: newEfs.promises }, + http: gitClient, + dir: path_1.default.join(this.polykeyPath, vaultName), + url: vaultUrl, + ref: 'master', + singleBranch: true, + }); + // Finally return the vault + const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath); + this.vaults.set(vaultName, vault); + return vault; + } + /** + * Determines whether the vault exists + * @param vaultName Name of desired vault + */ + vaultExists(vaultName) { + const path = path_1.default.join(this.polykeyPath, vaultName); + const vaultExists = this.fileSystem.existsSync(path); + return vaultExists; + } + /** + * [WARNING] Destroys a certain vault and all its secrets + * @param vaultName Name of vault to be destroyed + */ + destroyVault(vaultName) { + // this is convenience function for removing all tags + // and triggering garbage collection + // destruction is a better word as we should ensure all traces is removed + const path = path_1.default.join(this.polykeyPath, vaultName); + // Remove directory on file system + if (this.fileSystem.existsSync(path)) { + this.fileSystem.rmdirSync(path, { recursive: true }); + } + // Remove from maps + this.vaults.delete(vaultName); + this.vaultKeys.delete(vaultName); + // Write to metadata file + this.writeMetadata(); + const vaultPathExists = this.fileSystem.existsSync(path); + if (vaultPathExists) { + throw Error('Vault folder could not be destroyed!'); + } + } + /** + * List the names of all vaults in memory + */ + listVaults() { + return Array.from(this.vaults.keys()); + } + /* ============ HELPERS =============== */ + validateVault(vaultName) { + if (!this.vaults.has(vaultName)) { + throw Error('Vault does not exist in memory'); + } + if (!this.vaultKeys.has(vaultName)) { + throw Error('Vault key does not exist in memory'); + } + const vaultPath = path_1.default.join(this.polykeyPath, vaultName); + if (!this.fileSystem.existsSync(vaultPath)) { + throw Error('Vault directory does not exist'); + } + } + async writeMetadata() { + const metadata = JSON.stringify([...this.vaultKeys]); + const encryptedMetadata = await this.keyManager.encryptData(Buffer.from(metadata)); + await this.fileSystem.promises.writeFile(this.metadataPath, encryptedMetadata); + } + async loadMetadata() { + // Check if file exists + if (this.fileSystem.existsSync(this.metadataPath) && this.keyManager.identityLoaded) { + const encryptedMetadata = this.fileSystem.readFileSync(this.metadataPath); + const metadata = (await this.keyManager.decryptData(encryptedMetadata)).toString(); + for (const [key, value] of new Map(JSON.parse(metadata))) { + this.vaultKeys[key] = Buffer.from(value); + } + } + } +} +exports.default = VaultManager; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs_1 = __importDefault(__webpack_require__(2)); +const path_1 = __importDefault(__webpack_require__(0)); +const isomorphic_git_1 = __importDefault(__webpack_require__(15)); +const encryptedfs_1 = __webpack_require__(16); +const async_mutex_1 = __webpack_require__(45); +class Vault { + constructor(name, symKey, baseDir) { + // Concurrency + this.mutex = new async_mutex_1.Mutex(); + // how do we create pub/priv key pair? + // do we use the same gpg pub/priv keypair + this.key = symKey; + // Set filesystem + const vfsInstance = new (__webpack_require__(17).VirtualFS)(); + this.efs = new encryptedfs_1.EncryptedFS(this.key, vfsInstance, vfsInstance, fs_1.default, process); + this.name = name; + this.vaultPath = path_1.default.join(baseDir, name); + // make the vault directory + this.efs.mkdirSync(this.vaultPath, { recursive: true }); + this.secrets = new Map(); + this.loadSecrets(); + // Load metadata + this.metadataPath = path_1.default.join(this.vaultPath, '.vault', 'metadata'); + this.loadMetadata(); + } + /** + * Returns the Encrypted File System used for vault operations + */ + get EncryptedFS() { + return this.efs; + } + /** + * Determines whether a secret exists in the vault + * @param secretName Name of desired secret + */ + secretExists(secretName) { + const secretPath = path_1.default.join(this.vaultPath, secretName); + return this.secrets.has(secretName) && this.efs.existsSync(secretPath); + } + /** + * Adds a secret to the vault + * @param secretName Name of new secret + * @param secret Content of new secret + */ + async addSecret(secretName, secret) { + const release = await this.mutex.acquire(); + try { + // Check if secret already exists + if (this.secrets.has(secretName)) { + throw Error('Secret already exists, try updating it instead.'); + } + const writePath = path_1.default.join(this.vaultPath, secretName); + // Write secret + await this.efs.promises.writeFile(writePath, secret, {}); + // Update secrets map + this.secrets.set(secretName, secret); + // Auto commit message + await this.commitChanges(`Add secret: ${secretName}`, secretName, 'added'); + } + catch (error) { + release(); + throw error; + } + finally { + release(); + } + } + /** + * Updates a secret in the vault + * @param secretName Name of secret to be updated + * @param secret Content of updated secret + */ + async updateSecret(secretName, secret) { + const release = await this.mutex.acquire(); + try { + // Check if secret already exists + if (!this.secrets.has(secretName)) { + throw Error('Secret does not exist, try adding it instead.'); + } + const writePath = path_1.default.join(this.vaultPath, secretName); + // Write secret + await this.efs.promises.writeFile(writePath, secret, {}); + // Update secrets map + this.secrets.set(secretName, secret); + // Auto commit message + await this.commitChanges(`Update secret: ${secretName}`, secretName, 'modified'); + } + catch (error) { + release(); + throw error; + } + finally { + release(); + } + } + /** + * Get a secret from the vault + * @param secretName Name of secret to be retrieved + */ + getSecret(secretName) { + if (this.secrets.has(secretName)) { + const secret = this.secrets.get(secretName); + if (secret) { + return secret; + } + else { + const secretPath = path_1.default.join(this.vaultPath, secretName); + // TODO: this should be async + const secretBuf = this.efs.readFileSync(secretPath, {}); + this.secrets.set(secretName, secretBuf); + return secretBuf; + } + } + throw Error('Secret: ' + secretName + ' does not exist'); + } + /** + * [WARNING] Removes a secret from the vault + * @param secretName Name of secret to be removed + */ + async removeSecret(secretName) { + const release = await this.mutex.acquire(); + try { + if (this.secrets.has(secretName)) { + const successful = this.secrets.delete(secretName); + // Remove from fs + await this.efs.promises.unlink(path_1.default.join(this.vaultPath, secretName)); + // Auto commit message + await this.commitChanges(`Remove secret: ${secretName}`, secretName, 'removed'); + if (successful) { + return; + } + throw Error('Secret: ' + secretName + ' was not removed'); + } + throw Error('Secret: ' + secretName + ' does not exist'); + } + catch (error) { + release(); + throw error; + } + finally { + release(); + } + } + /** + * Lists all the secrets currently in the vault + */ + listSecrets() { + let secrets = Array.from(this.secrets.keys()); + return secrets; + } + tagVault() { } + untagVault() { } + ///////////// + // Sharing // + ///////////// + /** + * Allows a particular public key to access the vault + * @param publicKey Public key to share with + */ + shareVault(publicKey) { + if (this.sharedPubKeys.has(name)) { + throw Error('Vault is already shared with given public key'); + } + this.sharedPubKeys.add(publicKey); + // Write metadata + this.writeMetadata(); + } + /** + * Removes access to the vault for a particular public key + * @param publicKey Public key to unshare with + */ + unshareVault(publicKey) { + if (!this.sharedPubKeys.has(publicKey)) { + throw Error('Vault is not shared with given public key'); + } + this.sharedPubKeys.delete(publicKey); + // Write metadata + this.writeMetadata(); + } + /** + * Determines if a particular public key can access the vault + * @param publicKey Public key to check + */ + peerCanAccess(publicKey) { + // return this.sharedPubKeys.has(publicKey) + return true; + } + /** + * Pulls the vault from a specific address + * @param address Address of polykey node that owns vault to be pulled + * @param getSocket Function to get an active connection to provided address + */ + async pullVault(gitClient) { + const release = await this.mutex.acquire(); + try { + // Strangely enough this is needed for pulls along with ref set to 'HEAD' + // In isogit's documentation, this is just to get the currentBranch name + // But it solves a bug whereby if not used, git.pull complains that it can't + // find the master branch or HEAD + await isomorphic_git_1.default.currentBranch({ + fs: { promises: this.efs.promises }, + dir: this.vaultPath, + fullname: true, + }); + // First pull + await isomorphic_git_1.default.pull({ + fs: { promises: this.efs.promises }, + http: gitClient, + dir: this.vaultPath, + url: 'http://' + '0.0.0.0:0' + '/' + this.name, + ref: 'HEAD', + singleBranch: true, + author: { + name: this.name, + }, + }); + // Load any new secrets + this.loadSecrets(); + } + catch (error) { + release(); + throw error; + } + finally { + release(); + } + } + async getVaultHistory(depth) { + const logs = await isomorphic_git_1.default.log({ + fs: { promises: this.efs.promises }, + dir: this.vaultPath, + depth, + }); + return logs.map((commit) => { + return commit.commit.message; + }); + } + // ============== Helper methods ============== // + writeMetadata() { + // mkdir first + this.efs.mkdirSync(path_1.default.dirname(this.metadataPath), { recursive: true }); + // Create and write metadata + const metadata = { + sharedPubKeys: Array.from(this.sharedPubKeys.keys()), + }; + this.efs.writeFileSync(this.metadataPath, JSON.stringify(metadata)); + } + loadMetadata() { + if (this.efs.existsSync(this.metadataPath)) { + const fileContents = this.efs.readFileSync(this.metadataPath).toString(); + const metadata = JSON.parse(fileContents); + this.sharedPubKeys = new Set(metadata.sharedPubKeys); + } + else { + // Need to create it + this.sharedPubKeys = new Set(); + this.writeMetadata(); + } + } + async commitChanges(message, secretName, action) { + if (action == 'removed') { + await isomorphic_git_1.default.remove({ + fs: { promises: this.efs.promises }, + dir: this.vaultPath, + filepath: secretName, + }); + } + else { + await isomorphic_git_1.default.add({ + fs: { promises: this.efs.promises }, + dir: this.vaultPath, + filepath: secretName, + }); + } + return await isomorphic_git_1.default.commit({ + fs: { promises: this.efs.promises }, + dir: this.vaultPath, + author: { + name: this.name, + }, + message: message, + }); + } + loadSecrets() { + const secrets = fs_1.default.readdirSync(this.vaultPath, undefined); + // Remove all secrets first + this.secrets.clear(); + // Load secrets + for (const secret of secrets.filter((s) => s[0] != '.')) { + this.secrets.set(secret, null); + } + } +} +exports.default = Vault; + + +/***/ }), +/* 45 */ +/***/ (function(module, exports) { + +module.exports = require("async-mutex"); + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os_1 = __importDefault(__webpack_require__(1)); +const fs_1 = __importDefault(__webpack_require__(2)); +const net_1 = __importDefault(__webpack_require__(47)); +const path_1 = __importDefault(__webpack_require__(0)); +const process_1 = __importDefault(__webpack_require__(48)); +const child_process_1 = __webpack_require__(49); +const Polykey_1 = __importStar(__webpack_require__(4)); +const configstore_1 = __importDefault(__webpack_require__(50)); +const PolykeyClient_1 = __importDefault(__webpack_require__(18)); +const Agent_1 = __webpack_require__(19); +const { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage, } = Agent_1.agent; +class PolykeyAgent { + constructor() { + this.persistentStore = new configstore_1.default('polykey'); + // For storing the state of each polykey node + // Keys are the paths to the polykey node, e.g. '~/.polykey' + this.polykeyMap = new Map(); + this.socketPath = PolykeyAgent.SocketPath; + // Make sure the socket file doesn't already exist (agent is already running) + if (fs_1.default.existsSync(this.socketPath)) { + fs_1.default.unlinkSync(this.socketPath); + } + // Make the socket path if it doesn't exist + if (!fs_1.default.existsSync(path_1.default.dirname(this.socketPath))) { + fs_1.default.promises.mkdir(path_1.default.dirname(this.socketPath)); + } + // Load polykeys + const nodePaths = this.persistentStore.get('nodePaths'); + if (nodePaths === null || nodePaths === void 0 ? void 0 : nodePaths.values) { + for (const path of nodePaths) { + if (fs_1.default.existsSync(path)) { + this.polykeyMap.set(path, new Polykey_1.default(path, fs_1.default)); + } + else { + this.removeFromNodePaths(path); + } + } + } + else { + this.persistentStore.set('nodePaths', []); + } + // Start the server + this.server = net_1.default.createServer().listen(this.socketPath); + this.server.on('connection', (socket) => { + this.handleClientCommunication(socket); + }); + } + get AllNodePaths() { + return Array.from(this.polykeyMap.keys()).filter((nodePath) => { + try { + this.getPolykey(nodePath); + return true; + } + catch (_a) { + return false; + } + }); + } + get UnlockedNodePaths() { + return this.AllNodePaths.filter((nodePath) => { + try { + return this.getPolykey(nodePath).keyManager.identityLoaded; + } + catch (_a) { + return false; + } + }); + } + stop() { + this.server.close(); + } + addToNodePaths(nodePath, pk) { + this.polykeyMap.set(nodePath, pk); + const nodePathSet = new Set(this.persistentStore.get('nodePaths')); + nodePathSet.add(nodePath); + this.persistentStore.set('nodePaths', Array.from(nodePathSet.values())); + } + removeFromNodePaths(nodePath) { + this.polykeyMap.delete(nodePath); + const nodePathSet = new Set(this.persistentStore.get('nodePaths')); + nodePathSet.delete(nodePath); + this.persistentStore.set('nodePaths', Array.from(nodePathSet.values())); + } + handleClientCommunication(socket) { + socket.on('data', async (encodedMessage) => { + var _a; + try { + const { type, nodePath, subMessage } = AgentMessage.decode(encodedMessage); + let response = undefined; + switch (type) { + case Type.STATUS: + response = Buffer.from('online'); + break; + case Type.STOP_AGENT: + this.stop(); + process_1.default.exit(); + // eslint-disable-next-line + case Type.REGISTER_NODE: + response = await this.registerNode(nodePath, subMessage); + break; + case Type.NEW_NODE: + response = await this.newNode(nodePath, subMessage); + break; + case Type.LIST_NODES: + response = this.listNodes(subMessage); + break; + case Type.DERIVE_KEY: + response = await this.deriveKey(nodePath, subMessage); + break; + case Type.SIGN_FILE: + response = await this.signFile(nodePath, subMessage); + break; + case Type.VERIFY_FILE: + response = await this.verifyFile(nodePath, subMessage); + break; + case Type.LIST_VAULTS: + response = await this.listVaults(nodePath); + break; + case Type.NEW_VAULT: + response = await this.newVault(nodePath, subMessage); + break; + case Type.DESTROY_VAULT: + response = await this.destroyVault(nodePath, subMessage); + break; + case Type.LIST_SECRETS: + response = await this.listSecrets(nodePath, subMessage); + break; + case Type.CREATE_SECRET: + response = await this.createSecret(nodePath, subMessage); + break; + case Type.DESTROY_SECRET: + response = await this.destroySecret(nodePath, subMessage); + break; + case Type.GET_SECRET: + response = await this.getSecret(nodePath, subMessage); + break; + default: + throw Error(`message type not supported: ${type}`); + } + if (response) { + const encodedResponse = AgentMessage.encode({ + type: type, + isResponse: true, + nodePath: nodePath, + subMessage: response, + }).finish(); + socket.write(encodedResponse); + } + else { + throw Error('something went wrong'); + } + } + catch (err) { + const errorResponse = AgentMessage.encode({ + type: Type.ERROR, + isResponse: true, + nodePath: undefined, + subMessage: ErrorMessage.encode({ error: (_a = err.message) !== null && _a !== void 0 ? _a : err }).finish(), + }).finish(); + socket.write(errorResponse); + } + // Close connection + socket.end(); + }); + } + // Register an existing polykey agent + async registerNode(nodePath, request) { + const { passphrase } = RegisterNodeRequestMessage.decode(request); + let pk = this.polykeyMap.get(nodePath); + if (pk) { + if (pk.keyManager.identityLoaded) { + throw Error(`node path is already loaded and unlocked: '${nodePath}'`); + } + await pk.keyManager.unlockIdentity(passphrase); + } + else { + const km = new Polykey_1.KeyManager(nodePath, fs_1.default); + await km.unlockIdentity(passphrase); + // Create polykey class + pk = new Polykey_1.default(nodePath, fs_1.default, km); + } + // Set polykey class + this.addToNodePaths(nodePath, pk); + // Encode and send response + const response = NewNodeResponseMessage.encode({ + successful: pk.keyManager.identityLoaded && this.polykeyMap.has(nodePath), + }).finish(); + return response; + } + // Create a new polykey agent + async newNode(nodePath, request) { + // Throw if path already exists + if (this.polykeyMap.has(nodePath) && fs_1.default.existsSync(nodePath)) { + throw Error(`node path '${nodePath}' is already loaded`); + } + else if (fs_1.default.existsSync(nodePath)) { + throw Error(`node path already exists: '${nodePath}'`); + } + const { name, email, passphrase, nbits } = NewNodeRequestMessage.decode(request); + const km = new Polykey_1.KeyManager(nodePath, fs_1.default); + await km.generateKeyPair(name, email, passphrase, nbits == 0 ? undefined : nbits, true, (info) => { + // socket.write(JSON.stringify(info)) + }); + // Create and set polykey class + const pk = new Polykey_1.default(nodePath, fs_1.default, km); + this.addToNodePaths(nodePath, pk); + // Encode and send response + const response = NewNodeResponseMessage.encode({ + successful: km.identityLoaded && this.polykeyMap.has(nodePath), + }).finish(); + return response; + } + // Create a new polykey agent + listNodes(request) { + const { unlockedOnly } = ListNodesRequestMessage.decode(request); + if (unlockedOnly) { + return ListNodesResponseMessage.encode({ nodes: this.UnlockedNodePaths }).finish(); + } + else { + return ListNodesResponseMessage.encode({ nodes: this.AllNodePaths }).finish(); + } + } + getPolykey(nodePath) { + var _a; + if (this.polykeyMap.has(nodePath)) { + return this.polykeyMap.get(nodePath); + } + else if (fs_1.default.existsSync(nodePath)) { + throw Error(`polykey node has not been loaded yet: '${nodePath}'`); + } + else { + const nodePathList = new Set((_a = this.persistentStore.get('nodePaths')) !== null && _a !== void 0 ? _a : []); + nodePathList.delete(nodePath); + this.persistentStore.set('nodePaths', Array.from(nodePathList.values())); + throw Error(`node path does not exist: '${nodePath}'`); + } + } + ///////////////////////// + // KeyManager commands // + ///////////////////////// + async deriveKey(nodePath, request) { + const { keyName, passphrase } = DeriveKeyRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + await pk.keyManager.generateKey(keyName, passphrase); + return DeriveKeyResponseMessage.encode({ successful: true }).finish(); + } + ///////////////////// + // Crypto commands // + ///////////////////// + async signFile(nodePath, request) { + const { filePath, privateKeyPath, passphrase } = SignFileRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const signaturePath = await pk.keyManager.signFile(filePath, privateKeyPath, passphrase); + return SignFileResponseMessage.encode({ signaturePath }).finish(); + } + async verifyFile(nodePath, request) { + const { filePath, signaturePath } = VerifyFileRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const verified = await pk.keyManager.verifyFile(filePath, signaturePath); + return VerifyFileResponseMessage.encode({ verified }).finish(); + } + ////////////////////// + // Vault Operations // + ////////////////////// + async listVaults(nodePath) { + const pk = this.getPolykey(nodePath); + const vaultNames = pk.vaultManager.listVaults(); + return ListVaultsResponseMessage.encode({ vaultNames }).finish(); + } + async newVault(nodePath, request) { + const { vaultName } = NewVaultRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + await pk.vaultManager.createVault(vaultName); + return NewVaultResponseMessage.encode({ successful: true }).finish(); + } + async destroyVault(nodePath, request) { + const { vaultName } = DestroyVaultRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + pk.vaultManager.destroyVault(vaultName); + return DestroyVaultResponseMessage.encode({ successful: true }).finish(); + } + /////////////////////// + // Secret Operations // + /////////////////////// + async listSecrets(nodePath, request) { + const { vaultName } = ListSecretsRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const vault = pk.vaultManager.getVault(vaultName); + const secretNames = vault.listSecrets(); + return ListSecretsResponseMessage.encode({ secretNames }).finish(); + } + async createSecret(nodePath, request) { + const { vaultName, secretName, secretPath, secretContent } = CreateSecretRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const vault = pk.vaultManager.getVault(vaultName); + let secretBuffer; + if (secretPath) { + secretBuffer = await fs_1.default.promises.readFile(secretPath); + } + else { + secretBuffer = Buffer.from(secretContent); + } + await vault.addSecret(secretName, secretBuffer); + return CreateSecretResponseMessage.encode({ successful: true }).finish(); + } + async destroySecret(nodePath, request) { + const { vaultName, secretName } = DestroySecretRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const vault = pk.vaultManager.getVault(vaultName); + await vault.removeSecret(secretName); + return DestroySecretResponseMessage.encode({ successful: true }).finish(); + } + async getSecret(nodePath, request) { + const { vaultName, secretName } = GetSecretRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const vault = pk.vaultManager.getVault(vaultName); + const secret = Buffer.from(vault.getSecret(secretName)); + return GetSecretResponseMessage.encode({ secret: secret }).finish(); + } + /////////////////////// + // Client Connection // + /////////////////////// + static connectToAgent(getStream) { + const defaultStream = () => { + const socket = net_1.default.createConnection(PolykeyAgent.SocketPath); + return socket; + }; + const client = new PolykeyClient_1.default(getStream !== null && getStream !== void 0 ? getStream : defaultStream); + return client; + } + // ===== Helper methods===== // + static get SocketPath() { + const platform = os_1.default.platform(); + const userInfo = os_1.default.userInfo(); + if (platform == 'win32') { + return path_1.default.join('\\\\?\\pipe', process_1.default.cwd(), 'polykey-agent'); + } + else { + return `/run/user/${userInfo.uid}/polykey/S.polykey-agent`; + } + } + static get LogPath() { + const platform = os_1.default.platform(); + const userInfo = os_1.default.userInfo(); + if (platform == 'win32') { + return path_1.default.join(os_1.default.tmpdir(), 'polykey', 'log'); + } + else { + return `/run/user/${userInfo.uid}/polykey/log`; + } + } + static async startAgent(daemon = false) { + return new Promise((resolve, reject) => { + try { + let options = { + uid: process_1.default.getuid(), + detached: daemon, + }; + if (daemon) { + fs_1.default.rmdirSync(PolykeyAgent.LogPath, { recursive: true }); + fs_1.default.mkdirSync(PolykeyAgent.LogPath, { recursive: true }); + options.stdio = [ + 'ipc', + fs_1.default.openSync(path_1.default.join(PolykeyAgent.LogPath, 'output.log'), 'a'), + fs_1.default.openSync(path_1.default.join(PolykeyAgent.LogPath, 'error.log'), 'a'), + ]; + } + const agentProcess = child_process_1.fork(PolykeyAgent.DAEMON_SCRIPT_PATH, undefined, options); + const pid = agentProcess.pid; + agentProcess.unref(); + resolve(pid); + } + catch (err) { + reject(err); + } + }); + } +} +////////////////////// +// Agent Operations // +////////////////////// +PolykeyAgent.DAEMON_SCRIPT_PATH = path_1.default.join(__dirname, 'internal', 'daemon-script.js'); +exports.default = PolykeyAgent; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports) { + +module.exports = require("net"); + +/***/ }), +/* 48 */ +/***/ (function(module, exports) { + +module.exports = require("process"); + +/***/ }), +/* 49 */ +/***/ (function(module, exports) { + +module.exports = require("child_process"); + +/***/ }), +/* 50 */ +/***/ (function(module, exports) { + +module.exports = require("configstore"); + +/***/ }) +/******/ ]); +}); //# sourceMappingURL=polykey.js.map \ No newline at end of file diff --git a/dist/lib/polykey.js.map b/dist/lib/polykey.js.map index 08e801f077..abcc11ce50 100644 --- a/dist/lib/polykey.js.map +++ b/dist/lib/polykey.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://polykey/webpack/universalModuleDefinition","webpack://polykey/webpack/bootstrap","webpack://polykey/external \"path\"","webpack://polykey/external \"os\"","webpack://polykey/external \"fs\"","webpack://polykey/external \"readable-stream\"","webpack://polykey/./src/lib/Polykey.ts","webpack://polykey/external \"crypto\"","webpack://polykey/external \"@grpc/grpc-js\"","webpack://polykey/proto/compiled/Git_grpc_pb\"","webpack://polykey/proto/compiled/Git_pb\"","webpack://polykey/./src/lib/git/upload-pack/GitPktLine.ts","webpack://polykey/./src/lib/git/upload-pack/GitRefManager.ts","webpack://polykey/external \"pako\"","webpack://polykey/./src/lib/git/pack-objects/GitCommit.ts","webpack://polykey/./src/lib/git/pack-objects/GitObjectManager.ts","webpack://polykey/./src/lib/peers/PeerInfo.ts","webpack://polykey/external \"isomorphic-git\"","webpack://polykey/external \"encryptedfs\"","webpack://polykey/external \"virtualfs\"","webpack://polykey/./src/lib/agent/PolykeyClient.ts","webpack://polykey/proto/js/Agent\"","webpack://polykey/./src/lib/keys/KeyManager.ts","webpack://polykey/external \"kbpgp\"","webpack://polykey/external \"util\"","webpack://polykey/./src/lib/peers/PeerManager.ts","webpack://polykey/./src/lib/git/GitClient.ts","webpack://polykey/./src/lib/git/GitBackend.ts","webpack://polykey/./src/lib/git/upload-pack/uploadPack.ts","webpack://polykey/./src/lib/git/upload-pack/GitPackedRefs.ts","webpack://polykey/./src/lib/git/side-band/GitSideBand.ts","webpack://polykey/external \"buffer\"","webpack://polykey/./src/lib/git/pack-objects/packObjects.ts","webpack://polykey/./src/lib/git/pack-objects/log.ts","webpack://polykey/./src/lib/git/pack-objects/GitObject.ts","webpack://polykey/./src/lib/git/pack-objects/shasum.ts","webpack://polykey/external \"sha.js/sha1\"","webpack://polykey/./src/lib/git/pack-objects/GitTree.ts","webpack://polykey/external \"sha.js\"","webpack://polykey/proto/js/Peer\"","webpack://polykey/./src/lib/utils.ts","webpack://polykey/./src/lib/peers/MulticastBroadcaster.ts","webpack://polykey/external \"dgram\"","webpack://polykey/external \"events\"","webpack://polykey/proto/js/Peer.js\"","webpack://polykey/./src/lib/vaults/VaultManager.ts","webpack://polykey/./src/lib/vaults/Vault.ts","webpack://polykey/./src/lib/agent/PolykeyAgent.ts","webpack://polykey/external \"net\"","webpack://polykey/external \"process\"","webpack://polykey/external \"child_process\"","webpack://polykey/external \"configstore\""],"names":["root","factory","exports","module","define","amd","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","require","__importDefault","mod","os_1","KeyManager_1","KeyManager","default","PeerManager_1","PeerManager","VaultManager_1","VaultManager","PolykeyAgent_1","PolykeyAgent","PolykeyClient_1","PolykeyClient","polykeyPath","homedir","fileSystem","keyManager","vaultManager","peerManager","Buffer","from","line","hexlength","b","toString","repeat","length","padHex","concat","stream","async","slice","parseInt","buffer","err","console","log","path_1","GitPackedRefs_1","compareRefNames","a","_a","replace","_b","tmp","endsWith","GIT_FILES","GitRefManager","gitdir","text","readFileSync","encoding","refs","filepath","packedMap","packedRefs","files","recursiveDirectoryWalk","dir","Promise","resolve","reject","results","promises","readdir","then","list","pending","forEach","file","stat","isDirectory","res","push","catch","map","x","keys","startsWith","includes","sort","ref","depth","undefined","test","allpaths","refpaths","filter","sha","trim","Error","negateExceptForZero","formatTimezoneOffset","minutes","sign","Math","is","abs","hours","floor","strHours","String","strMinutes","parseTimezoneOffset","offset","match","Number","parseAuthor","author","email","timestamp","timezoneOffset","normalize","str","indent","split","join","GitCommit","commit","_commit","isBuffer","render","payload","signature","headers","justHeaders","message","justMessage","parseHeaders","assign","indexOf","hs","h","obj","parent","Array","isArray","committer","tree","gpgsig","renderHeaders","fs_1","pako_1","GitObject_1","PackfileCache","Map","GitObjectManager","oid","format","source","getExternalRefDelta","read","readdirSync","filename","offsets","has","pack","load","result","inflate","type","unwrap","Address","ip","port","addressString","components","addressInfo","address","pubKey","addresses","connectedAddr","publicKey","Set","addr","parse","add","values","Agent_1","AgentMessage","CreateSecretRequestMessage","CreateSecretResponseMessage","DeriveKeyRequestMessage","DeriveKeyResponseMessage","DestroySecretRequestMessage","DestroySecretResponseMessage","DestroyVaultRequestMessage","DestroyVaultResponseMessage","ErrorMessage","GetSecretRequestMessage","GetSecretResponseMessage","ListNodesRequestMessage","ListNodesResponseMessage","ListSecretsRequestMessage","ListSecretsResponseMessage","ListVaultsRequestMessage","ListVaultsResponseMessage","NewNodeRequestMessage","NewNodeResponseMessage","NewVaultRequestMessage","NewVaultResponseMessage","RegisterNodeRequestMessage","RegisterNodeResponseMessage","SignFileRequestMessage","SignFileResponseMessage","Type","VerifyFileRequestMessage","VerifyFileResponseMessage","agent","getStream","request","responseList","on","data","write","end","nodePath","agentMessage","encode","isResponse","subMessage","finish","sendRequestToAgent","agentMessageList","response","decode","ERROR","error","path","passphrase","registerNodeRequest","encodedResponse","handleAgentCommunication","REGISTER_NODE","successful","nbits","newNodeRequest","NEW_NODE","unlockedOnly","LIST_NODES","nodes","keyName","DERIVE_KEY","filePath","privateKeyPath","SIGN_FILE","signaturePath","VERIFY_FILE","verified","LIST_VAULTS","vaultNames","vaultName","NEW_VAULT","DESTROY_VAULT","LIST_SECRETS","secretNames","secretName","secretPath","CREATE_SECRET","DESTROY_SECRET","GET_SECRET","secret","STATUS","STOP_AGENT","getAgentStatus","kbpgp_1","crypto_1","util_1","polyKeyPath","useWebWorkers","workerPool","primaryKeyPair","private","public","metadata","publicKeyPath","pkiKeyPath","pkiCertPath","caCertPath","pkiInfo","cert","caCert","derivedKeys","keypairPath","existsSync","mkdirSync","recursive","metadataPath","loadMetadata","loadKeyPair","loadPKIInfo","replacePrimary","progressCallback","flags","openpgp","params","asp","ASP","progress_hook","userid","primary","certify_keys","sign_data","auth","encrypt_comm","encrypt_storage","expire_in","subkeys","identity","promisify","generate","export_pgp_public","keypair","export_pgp_private","primaryIdentity","writeFile","writeMetadata","privateKey","loadPrivateKey","loadPublicKey","keyBuffer","getPublicKey","getPrivateKey","import_from_armored_pgp","armored","merge_pgp_private","is_pgp_locked","unlock_pgp","writeFileSync","salt","randomBytes","pbkdf2Sync","pbkdf2","readFile","dest","createPath","dirname","mkdir","keyPassphrase","resolvedIdentity","getIdentityFromPrivateKey","queue","workerCrypto","signData","msg","sign_with","result_string","box","signedBuffer","signedPath","ring","keyring","KeyRing","getIdentityFromPublicKey","add_key_manager","verifyData","keyfetch","dataSigner","unbox","get_data_signer","get_key_manager","get_pgp_fingerprint","fileBuffer","signatureBuffer","encryptData","encrypt_for","decryptData","literals","writeToFile","storagePath","JSON","stringify","__importStar","k","grpc","GitClient_1","GitBackend_1","Peer_1","utils_1","PeerInfo_1","MulticastBroadcaster_1","Git_grpc_pb_1","Git_pb_1","keybaseDiscovery","findUser","handle","service","url","fetch","json","them","public_keys","bundle","peerInfo","socialDiscoveryServices","localPeerInfo","serverStarted","hasPublicKey","peerStore","multicastBroadcaster","addPeer","peerConnections","gitBackend","server","Server","addService","GitServerService","requestInfo","requestPack","PKIInfo","credentials","ServerCredentials","createInsecure","bindAsync","process","env","PK_PORT","boundPort","start","connect","callback","getVaultname","infoReply","InfoReply","setVaultname","setBody","handleInfoRequest","packRequest","body","getBody_asB64","reply","PackReply","handlePackRequest","set","requestPeerContact","timedOutPubKey","tasks","socialDiscovery","pubKeyOrFail","firstPromiseFulfilled","pubKeyFound","findPubKey","peer","existingSocket","peerAddress","getPeer","conn","PeerInfoMessage","AdressStringList","client","GitServerClient","method","onProgress","u","URL","pathname","infoResponse","statusCode","statusMessage","iteratorFromData","packResponse","InfoRequest","PackRequest","ended","next","done","readable_stream_1","uploadPack_1","GitSideBand_1","packObjects_1","vault","getVault","peerCanAccess","responseBuffers","exists","createGitPacketLine","EncryptedFS","buffers","buffersToWrite","wantedObjectId","packResult","readable","PassThrough","progressStream","sideBand","mux","packstream","hexPrefix","GitPktLine_1","GitRefManager_1","advertiseRefs","capabilities","listRefs","unshift","symrefs","syms","entries","caps","flush","writeRefsAdResponse","caller","GitPackedRefs","parsedConfig","comment","peeled","buffer_1","splitBuffer","maxBytes","index","buf","input","streamReader","packetlines","packfile","progress","nextBit","destroy","protocol","MAX_PACKET_LENGTH","output","packfileWasEmpty","packfileEnded","progressEnded","goodbye","log_1","GitTree_1","sha_js_1","GitCommit_1","GitObjectManager_1","types","blob","tag","ofs_delta","ref_delta","listObjects","oids","commits","trees","blobs","walk","entry","outputStream","hash","chunk","enc","update","writeObject","stype","lastFour","multibyte","byte","unpaddedChunk","deflate","digest","haves","shallows","unshallows","acks","oldshallows","objects","logCommit","signing","withoutSignature","compareAge","since","sinceTimestamp","valueOf","tips","pop","shasum_1","byteLength","actualLength","sha1_1","nudgeIntoShape","limitModeToAllowed","GitTree","_entries","cursor","space","nullchar","parseBuffer","iterator","invertPromise","rej","randomString","random","substr","ps","all","dgram_1","events_1","Peer_js_1","HandshakeMessage","UDP_MULTICAST_PORT","UDP_MULTICAST_ADDR","MulticastBroadcaster","EventEmitter","super","peerPubKeyMessages","interval","queryInterval","socket","createSocket","reuseAddr","addMembership","handleHandshakeMessages","queryLAN","pubKeyBuf","randomMessage","encryptedPeerPubKey","encryptedRandomMessage","encryptedLocalPubKey","rawRandomMessage","query","peerMessage","handshakeMessage","targetPubKey","requestingPubKey","send","setInterval","rinfo","responsePeerInfo","decryptedMessage","decryptedTargetPubKey","decryptedRequestingPubKey","myPubKey","originalMessage","newPeerInfo","delete","emit","encryptedTargetPubKey","encryptedMessage","encryptedPubKey","encodedLocalPeerInfo","isomorphic_git_1","Vault_1","encryptedfs_1","vaults","vaultKeys","vaultKey","validateVault","vaultExists","generateKey","initRepository","destroyVault","gitClient","vaultUrl","getRemoteInfo","http","vfsInstance","VirtualFS","newEfs","clone","fs","singleBranch","rmdirSync","vaultPath","encryptedMetadata","identityLoaded","symKey","baseDir","keyLen","efs","secrets","loadSecrets","writePath","commitChanges","secretBuf","unlink","sharedPubKeys","currentBranch","fullname","pull","init","fileContents","action","remove","net_1","process_1","child_process_1","Polykey_1","configstore_1","persistentStore","polykeyMap","socketPath","SocketPath","unlinkSync","nodePaths","removeFromNodePaths","createServer","listen","handleClientCommunication","getPolykey","AllNodePaths","close","pk","nodePathSet","encodedMessage","stop","exit","registerNode","newNode","listNodes","deriveKey","signFile","verifyFile","listVaults","newVault","listSecrets","createSecret","destroySecret","getSecret","errorResponse","unlockIdentity","km","addToNodePaths","generateKeyPair","info","UnlockedNodePaths","nodePathList","createVault","addSecret","removeSecret","passThrough","createConnection","pipe","platform","userInfo","cwd","uid","tmpdir","daemon","options","getuid","detached","LogPath","stdio","openSync","agentProcess","fork","DAEMON_SCRI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AAS,GAC7B,OAAO,IAAIhqB,QAAQ,CAACC,EAASC,KACzB,IACI,IAAI+pB,EAAU,CACVH,IAAKnD,EAAUlqB,QAAQytB,SACvBC,SAAUH,GAEVA,IACA9kB,EAAKzI,QAAQ2oB,UAAUroB,EAAaqtB,QAAS,CAAEjc,WAAW,IAC1DjJ,EAAKzI,QAAQyR,UAAUnR,EAAaqtB,QAAS,CAAEjc,WAAW,IAC1D8b,EAAQI,MAAQ,CACZ,MACAnlB,EAAKzI,QAAQ6tB,SAAS5rB,EAAOjC,QAAQgH,KAAK1G,EAAaqtB,QAAS,cAAe,KAC/EllB,EAAKzI,QAAQ6tB,SAAS5rB,EAAOjC,QAAQgH,KAAK1G,EAAaqtB,QAAS,aAAc,KAAM,IAG5F,MAAMG,EAAe3D,EAAgB4D,KAAKztB,EAAa0tB,wBAAoBjpB,EAAWyoB,GAChFS,EAAMH,EAAaG,IACzBH,EAAaI,QACb1qB,EAAQyqB,GAEZ,MAAOnsB,GACH2B,EAAO3B,OAQvBxB,EAAa0tB,mBAAqB/rB,EAAOjC,QAAQgH,KAAKmnB,UAAW,WAAY,oBAC7EjxB,EAAQ8C,QAAUM,G,cC/XlBnD,EAAOD,QAAUwC,QAAQ,Q,cCAzBvC,EAAOD,QAAUwC,QAAQ,Y,cCAzBvC,EAAOD,QAAUwC,QAAQ,kB,cCAzBvC,EAAOD,QAAUwC,QAAQ","file":"polykey.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"polykey\"] = factory();\n\telse\n\t\troot[\"polykey\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 4);\n","module.exports = require(\"path\");","module.exports = require(\"os\");","module.exports = require(\"fs\");","module.exports = require(\"readable-stream\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst KeyManager_1 = __importDefault(require(\"./keys/KeyManager\"));\nexports.KeyManager = KeyManager_1.default;\nconst PeerManager_1 = __importDefault(require(\"./peers/PeerManager\"));\nexports.PeerManager = PeerManager_1.default;\nconst VaultManager_1 = __importDefault(require(\"./vaults/VaultManager\"));\nexports.VaultManager = VaultManager_1.default;\nconst PolykeyAgent_1 = __importDefault(require(\"./agent/PolykeyAgent\"));\nexports.PolykeyAgent = PolykeyAgent_1.default;\nconst PolykeyClient_1 = __importDefault(require(\"./agent/PolykeyClient\"));\nexports.PolykeyClient = PolykeyClient_1.default;\nclass Polykey {\n constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager, vaultManager, peerManager) {\n this.polykeyPath = polykeyPath;\n // Set key manager\n this.keyManager = keyManager !== null && keyManager !== void 0 ? keyManager : new KeyManager_1.default(this.polykeyPath, fileSystem);\n // Set or Initialize vaultManager\n this.vaultManager = vaultManager !== null && vaultManager !== void 0 ? vaultManager : new VaultManager_1.default(this.polykeyPath, fileSystem, this.keyManager);\n // Initialize peer store and peer discovery classes\n this.peerManager = peerManager !== null && peerManager !== void 0 ? peerManager : new PeerManager_1.default(this.polykeyPath, fileSystem, this.keyManager, this.vaultManager);\n }\n}\nexports.default = Polykey;\n","module.exports = require(\"crypto\");","module.exports = require(\"@grpc/grpc-js\");","module.exports = require(\"../../proto/compiled/Git_grpc_pb\");","module.exports = require(\"../../proto/compiled/Git_pb\");","\"use strict\";\n/**\npkt-line Format\n---------------\n\nMuch (but not all) of the payload is described around pkt-lines.\n\nA pkt-line is a variable length binary string. The first four bytes\nof the line, the pkt-len, indicates the total length of the line,\nin hexadecimal. The pkt-len includes the 4 bytes used to contain\nthe length's hexadecimal representation.\n\nA pkt-line MAY contain binary data, so implementors MUST ensure\npkt-line parsing/formatting routines are 8-bit clean.\n\nA non-binary line SHOULD BE terminated by an LF, which if present\nMUST be included in the total length. Receivers MUST treat pkt-lines\nwith non-binary data the same whether or not they contain the trailing\nLF (stripping the LF if present, and not complaining when it is\nmissing).\n\nThe maximum length of a pkt-line's data component is 65516 bytes.\nImplementations MUST NOT send pkt-line whose length exceeds 65520\n(65516 bytes of payload + 4 bytes of length data).\n\nImplementations SHOULD NOT send an empty pkt-line (\"0004\").\n\nA pkt-line with a length field of 0 (\"0000\"), called a flush-pkt,\nis a special case and MUST be handled differently than an empty\npkt-line (\"0004\").\n\n----\n pkt-line = data-pkt / flush-pkt\n\n data-pkt = pkt-len pkt-payload\n pkt-len = 4*(HEXDIG)\n pkt-payload = (pkt-len - 4)*(OCTET)\n\n flush-pkt = \"0000\"\n----\n\nExamples (as C-style strings):\n\n----\n pkt-line actual value\n ---------------------------------\n \"0006a\\n\" \"a\\n\"\n \"0005a\" \"a\"\n \"000bfoobar\\n\" \"foobar\\n\"\n \"0004\" \"\"\n----\n*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction padHex(b, n) {\n const s = n.toString(16);\n return '0'.repeat(b - s.length) + s;\n}\n// I'm really using this more as a namespace.\n// There's not a lot of \"state\" in a pkt-line\nclass GitPktLine {\n static flush() {\n return Buffer.from('0000', 'utf8');\n }\n static encode(line) {\n if (typeof line === 'string') {\n line = Buffer.from(line);\n }\n const length = line.length + 4;\n const hexlength = padHex(4, length);\n return Buffer.concat([Buffer.from(hexlength, 'utf8'), line]);\n }\n static streamReader(stream) {\n return async function read() {\n try {\n let length = await stream.slice(4);\n if (length === null)\n return true;\n length = parseInt(length.toString('utf8'), 16);\n if (length === 0)\n return null;\n let buffer = await stream.slice(length - 4);\n if (buffer === null)\n return true;\n return buffer;\n }\n catch (err) {\n console.log('error', err);\n return true;\n }\n };\n }\n}\nexports.default = GitPktLine;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// This is a convenience wrapper for reading and writing files in the 'refs' directory.\nconst path_1 = __importDefault(require(\"path\"));\nconst GitPackedRefs_1 = __importDefault(require(\"./GitPackedRefs\"));\n// @see https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions\nconst refpaths = ref => [\n `${ref}`,\n `refs/${ref}`,\n `refs/tags/${ref}`,\n `refs/heads/${ref}`,\n `refs/remotes/${ref}`,\n `refs/remotes/${ref}/HEAD`,\n];\nfunction compareRefNames(a, b) {\n // https://stackoverflow.com/a/40355107/2168416\n const _a = a.replace(/\\^\\{\\}$/, '');\n const _b = b.replace(/\\^\\{\\}$/, '');\n const tmp = -(_a < _b) || +(_a > _b);\n if (tmp === 0) {\n return a.endsWith('^{}') ? 1 : -1;\n }\n return tmp;\n}\n// @see https://git-scm.com/docs/gitrepository-layout\nconst GIT_FILES = ['config', 'description', 'index', 'shallow', 'commondir'];\n// This function is used to get all the files in the refs folder for listRefs function\nasync function recursiveDirectoryWalk(dir, fileSystem) {\n return new Promise((resolve, reject) => {\n let results = [];\n fileSystem.promises.readdir(dir).then(async (list) => {\n var pending = list.length;\n if (!pending)\n return resolve(results);\n list.forEach(async function (file) {\n file = path_1.default.resolve(dir, file);\n fileSystem.promises.stat(file).then(async (stat) => {\n if (stat && stat.isDirectory()) {\n const res = await recursiveDirectoryWalk(file, fileSystem);\n results = results.concat(res);\n if (!--pending)\n resolve(results);\n }\n else {\n results.push(file);\n if (!--pending)\n resolve(results);\n }\n });\n });\n }).catch((err) => {\n if (err)\n return reject(err);\n });\n });\n}\n;\nclass GitRefManager {\n static async packedRefs(fileSystem, gitdir) {\n const text = fileSystem.readFileSync(`${gitdir}/packed-refs`, { encoding: 'utf8' });\n const packed = GitPackedRefs_1.default.from(text);\n return packed.refs;\n }\n // List all the refs that match the `filepath` prefix\n static async listRefs(fileSystem, gitdir, filepath) {\n const packedMap = GitRefManager.packedRefs(fileSystem, gitdir);\n let files = [];\n try {\n files = await recursiveDirectoryWalk(`${gitdir}/${filepath}`, fileSystem);\n files = files.map(x => x.replace(`${gitdir}/${filepath}/`, ''));\n }\n catch (err) {\n files = [];\n }\n for (let key of (await packedMap).keys()) {\n // filter by prefix\n if (key.startsWith(filepath)) {\n // remove prefix\n key = key.replace(filepath + '/', '');\n // Don't include duplicates; the loose files have precedence anyway\n if (!files.includes(key)) {\n files.push(key);\n }\n }\n }\n // since we just appended things onto an array, we need to sort them now\n files.sort(compareRefNames);\n return files;\n }\n static async resolve(fileSystem, gitdir, ref, depth) {\n if (depth !== undefined) {\n depth--;\n if (depth === -1) {\n return ref;\n }\n }\n // Is it a ref pointer?\n if (ref.startsWith('ref: ')) {\n ref = ref.slice('ref: '.length);\n return GitRefManager.resolve(fileSystem, gitdir, ref, depth);\n }\n // Is it a complete and valid SHA?\n if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) {\n return ref;\n }\n // We need to alternate between the file system and the packed-refs\n const packedMap = await GitRefManager.packedRefs(fileSystem, gitdir);\n // Look in all the proper paths, in this order\n const allpaths = refpaths(ref).filter(p => !GIT_FILES.includes(p)); // exclude git system files (#709)\n for (const ref of allpaths) {\n const sha = (fileSystem.readFileSync(`${gitdir}/${ref}`, { encoding: 'utf8' }).toString()) || packedMap.get(ref);\n if (sha) {\n return GitRefManager.resolve(fileSystem, gitdir, sha.trim(), depth);\n }\n }\n // Do we give up?\n throw (Error('RefNotFound'));\n }\n}\nexports.default = GitRefManager;\n","module.exports = require(\"pako\");","\"use strict\";\n// The amount of work that went into crafting these cases to handle\n// -0 (just so we don't lose that information when parsing and reconstructing)\n// but can also default to +0 was extraordinary.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction simpleSign(n) {\n return Math.sign(n) || (Object.is(n, -0) ? -1 : 1);\n}\nfunction negateExceptForZero(n) {\n return n === 0 ? n : -n;\n}\nfunction formatTimezoneOffset(minutes) {\n let sign = simpleSign(negateExceptForZero(minutes));\n minutes = Math.abs(minutes);\n let hours = Math.floor(minutes / 60);\n minutes -= hours * 60;\n let strHours = String(hours);\n let strMinutes = String(minutes);\n if (strHours.length < 2)\n strHours = '0' + strHours;\n if (strMinutes.length < 2)\n strMinutes = '0' + strMinutes;\n return (sign === -1 ? '-' : '+') + strHours + strMinutes;\n}\nfunction parseTimezoneOffset(offset) {\n let [, sign, hours, minutes] = offset.match(/(\\+|-)(\\d\\d)(\\d\\d)/);\n minutes = (sign === '+' ? 1 : -1) * (Number(hours) * 60 + Number(minutes));\n return negateExceptForZero(minutes);\n}\nfunction parseAuthor(author) {\n let [, name, email, timestamp, offset] = author.match(/^(.*) <(.*)> (.*) (.*)$/);\n return {\n name: name,\n email: email,\n timestamp: Number(timestamp),\n timezoneOffset: parseTimezoneOffset(offset)\n };\n}\nfunction normalize(str) {\n // remove all \n str = str.replace(/\\r/g, '');\n // no extra newlines up front\n str = str.replace(/^\\n+/, '');\n // and a single newline at the end\n str = str.replace(/\\n+$/, '') + '\\n';\n return str;\n}\nfunction indent(str) {\n return (str\n .trim()\n .split('\\n')\n .map(x => ' ' + x)\n .join('\\n') + '\\n');\n}\nfunction outdent(str) {\n return str\n .split('\\n')\n .map(x => x.replace(/^ /, ''))\n .join('\\n');\n}\n// TODO: Make all functions have static async signature?\nclass GitCommit {\n constructor(commit) {\n if (typeof commit === 'string') {\n this._commit = commit;\n }\n else if (Buffer.isBuffer(commit)) {\n this._commit = commit.toString('utf8');\n }\n else if (typeof commit === 'object') {\n this._commit = GitCommit.render(commit);\n }\n else {\n throw (new Error('invalid type passed to GitCommit constructor'));\n }\n }\n static fromPayloadSignature({ payload, signature }) {\n let headers = GitCommit.justHeaders(payload);\n let message = GitCommit.justMessage(payload);\n let commit = normalize(headers + '\\ngpgsig' + indent(signature) + '\\n' + message);\n return new GitCommit(commit);\n }\n static from(commit) {\n return new GitCommit(commit);\n }\n toObject() {\n return Buffer.from(this._commit, 'utf8');\n }\n // Todo: allow setting the headers and message\n headers() {\n return this.parseHeaders();\n }\n // Todo: allow setting the headers and message\n message() {\n return GitCommit.justMessage(this._commit);\n }\n parse() {\n return Object.assign({ message: this.message() }, this.headers());\n }\n static justMessage(commit) {\n return normalize(commit.slice(commit.indexOf('\\n\\n') + 2));\n }\n static justHeaders(commit) {\n return commit.slice(0, commit.indexOf('\\n\\n'));\n }\n parseHeaders() {\n let headers = GitCommit.justHeaders(this._commit).split('\\n');\n let hs = [];\n for (let h of headers) {\n if (h[0] === ' ') {\n // combine with previous header (without space indent)\n hs[hs.length - 1] += '\\n' + h.slice(1);\n }\n else {\n hs.push(h);\n }\n }\n let obj = {\n parent: []\n };\n for (let h of hs) {\n let key = h.slice(0, h.indexOf(' '));\n let value = h.slice(h.indexOf(' ') + 1);\n if (Array.isArray(obj[key])) {\n obj[key].push(value);\n }\n else {\n obj[key] = value;\n }\n }\n if (obj.author) {\n obj.author = parseAuthor(obj.author);\n }\n if (obj.committer) {\n obj.committer = parseAuthor(obj.committer);\n }\n return obj;\n }\n static renderHeaders(obj) {\n let headers = '';\n if (obj.tree) {\n headers += `tree ${obj.tree}\\n`;\n }\n else {\n headers += `tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\\n`; // the null tree\n }\n if (obj.parent) {\n if (obj.parent.length === undefined) {\n throw (new Error(`commit 'parent' property should be an array`));\n }\n for (let p of obj.parent) {\n headers += `parent ${p}\\n`;\n }\n }\n let author = obj.author;\n headers += `author ${author.name} <${author.email}> ${author.timestamp} ${formatTimezoneOffset(author.timezoneOffset)}\\n`;\n let committer = obj.committer || obj.author;\n headers += `committer ${committer.name} <${committer.email}> ${committer.timestamp} ${formatTimezoneOffset(committer.timezoneOffset)}\\n`;\n if (obj.gpgsig) {\n headers += 'gpgsig' + indent(obj.gpgsig);\n }\n return headers;\n }\n static render(obj) {\n return GitCommit.renderHeaders(obj) + '\\n' + normalize(obj.message);\n }\n render() {\n return this._commit;\n }\n withoutSignature() {\n let commit = normalize(this._commit);\n if (commit.indexOf('\\ngpgsig') === -1)\n return commit;\n let headers = commit.slice(0, commit.indexOf('\\ngpgsig'));\n let message = commit.slice(commit.indexOf('-----END PGP SIGNATURE-----\\n') +\n '-----END PGP SIGNATURE-----\\n'.length);\n return normalize(headers + '\\n' + message);\n }\n isolateSignature() {\n let signature = this._commit.slice(this._commit.indexOf('-----BEGIN PGP SIGNATURE-----'), this._commit.indexOf('-----END PGP SIGNATURE-----') +\n '-----END PGP SIGNATURE-----'.length);\n return outdent(signature);\n }\n}\nexports.default = GitCommit;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = __importDefault(require(\"fs\"));\nconst pako_1 = __importDefault(require(\"pako\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst GitObject_1 = __importDefault(require(\"./GitObject\"));\nconst PackfileCache = new Map();\nclass GitObjectManager {\n static async read(fileSystem, gitdir, oid, format = 'content') {\n // Look for it in the loose object directory.\n let file = fileSystem.readFileSync(`${gitdir}/objects/${oid.slice(0, 2)}/${oid.slice(2)}`);\n let source = `./objects/${oid.slice(0, 2)}/${oid.slice(2)}`;\n // Check to see if it's in a packfile.\n if (!file) {\n // Curry the current read method so that the packfile un-deltification\n // process can acquire external ref-deltas.\n const getExternalRefDelta = oid => GitObjectManager.read(fileSystem, gitdir, oid);\n // Iterate through all the .pack files\n let list = fs_1.default.readdirSync(path_1.default.join(gitdir, '/objects/pack'));\n list = list.filter(x => x.endsWith('.pack'));\n for (let filename of list) {\n // Try to get the packfile from the in-memory cache\n let p = PackfileCache.get(filename);\n // If the packfile DOES have the oid we're looking for...\n if (p.offsets.has(oid)) {\n // Make sure the packfile is loaded in memory\n if (!p.pack) {\n const pack = fileSystem.readFileSync(`${gitdir}/objects/pack/${filename}`);\n await p.load({ pack });\n }\n // Get the resolved git object from the packfile\n let result = await p.read({ oid, getExternalRefDelta });\n result.source = `./objects/pack/${filename}`;\n return result;\n }\n }\n }\n // Check to see if it's in shallow commits.\n if (!file) {\n let text = fileSystem.readFileSync(`${gitdir}/shallow`, { encoding: 'utf8' });\n if (text !== null && text.includes(oid)) {\n throw (new Error(`ReadShallowObjectFail: ${oid}`));\n }\n }\n // Finally\n if (!file) {\n throw (new Error(`ReadObjectFail: ${oid}`));\n }\n if (format === 'deflated') {\n return { format: 'deflated', object: file, source };\n }\n let buffer = Buffer.from(pako_1.default.inflate(file));\n if (format === 'wrapped') {\n return { format: 'wrapped', object: buffer, source };\n }\n let { type, object } = GitObject_1.default.unwrap({ oid, buffer });\n if (format === 'content')\n return { type, format: 'content', object, source };\n }\n}\nexports.default = GitObjectManager;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass Address {\n constructor(ip, port) {\n this.ip = ip;\n this.port = port;\n }\n /**\n * Create an address object from a address string\n * @param addressString Address string in the format of `${this.ip}:${this.port}`\n */\n static parse(addressString) {\n const components = addressString.split(':');\n const ip = components[0];\n const port = components[1];\n return new Address(ip, port);\n }\n /**\n * Create an address object from a net.AddressInfo\n * @param addressInfo AddressInfo of desired address\n */\n static fromAddressInfo(addressInfo) {\n const ip = (addressInfo.address == '::') ? 'localhost' : addressInfo.address;\n return new Address(ip, addressInfo.port.toString());\n }\n /**\n * Convert address into string of format `${this.ip}:${this.port}`\n */\n toString() {\n return `${this.ip}:${this.port}`;\n }\n}\nexports.Address = Address;\nAddress.prototype.toString = function () {\n return `${this.ip}:${this.port}`;\n};\nclass PeerInfo {\n constructor(pubKey, addresses = [], connectedAddr) {\n this.publicKey = pubKey;\n this.addresses = new Set(addresses.map((addr) => {\n return Address.parse(addr);\n }));\n this.connectedAddr = (connectedAddr) ? Address.parse(connectedAddr) : undefined;\n }\n /**\n * Sets the main server address for the peer\n * @param address Main server address for peer\n */\n connect(address) {\n if (!this.addresses.has(address)) {\n this.addresses.add(address);\n }\n this.connectedAddr = address;\n }\n /**\n * Clears the main server address for the peer\n */\n disconnect() {\n this.connectedAddr = undefined;\n }\n get AdressStringList() {\n return Array.from(this.addresses.values()).map((addr) => {\n return addr.toString();\n });\n }\n}\nexports.default = PeerInfo;\n","module.exports = require(\"isomorphic-git\");","module.exports = require(\"encryptedfs\");","module.exports = require(\"virtualfs\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Agent_1 = require(\"../../../proto/js/Agent\");\nconst { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage } = Agent_1.agent;\nclass PolykeyClient {\n constructor(getStream) {\n this.getStream = getStream;\n }\n async sendRequestToAgent(request) {\n const stream = this.getStream();\n const responseList = await new Promise((resolve, reject) => {\n try {\n const responseList = [];\n stream.on('data', (data) => {\n responseList.push(data);\n });\n stream.on('error', (err) => {\n reject(err);\n });\n stream.on('end', () => {\n resolve(responseList);\n });\n stream.write(request);\n }\n catch (err) {\n reject(err);\n }\n });\n stream.end();\n return responseList;\n }\n async handleAgentCommunication(type, nodePath, request) {\n // Encode message and sent\n const agentMessage = AgentMessage.encode({ type: type, isResponse: false, nodePath: nodePath, subMessage: request }).finish();\n const responseList = await this.sendRequestToAgent(agentMessage);\n const agentMessageList = [];\n for (const response of responseList) {\n const { subMessage, type } = AgentMessage.decode(response);\n if (type == Type.ERROR) {\n const { error } = ErrorMessage.decode(subMessage);\n const reason = new Error(error);\n throw reason;\n }\n else {\n agentMessageList.push(AgentMessage.decode(response));\n }\n }\n return agentMessageList;\n }\n async registerNode(path, passphrase) {\n const registerNodeRequest = RegisterNodeRequestMessage.encode({ passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.REGISTER_NODE, path, registerNodeRequest);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = RegisterNodeResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async newNode(path, name, email, passphrase, nbits) {\n const newNodeRequest = NewNodeRequestMessage.encode({ name, email, passphrase, nbits }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.NEW_NODE, path, newNodeRequest);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = NewNodeResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async listNodes(unlockedOnly = true) {\n const newNodeRequest = ListNodesRequestMessage.encode({ unlockedOnly }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_NODES, undefined, newNodeRequest);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { nodes } = ListNodesResponseMessage.decode(encodedResponse[0].subMessage);\n return nodes;\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async deriveKey(nodePath, keyName, passphrase) {\n const request = DeriveKeyRequestMessage.encode({ keyName, passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DERIVE_KEY, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = DeriveKeyResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async signFile(nodePath, filePath, privateKeyPath, passphrase) {\n const request = SignFileRequestMessage.encode({ filePath, privateKeyPath, passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.SIGN_FILE, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { signaturePath } = SignFileResponseMessage.decode(encodedResponse[0].subMessage);\n return signaturePath;\n }\n async verifyFile(nodePath, filePath, signaturePath) {\n const request = VerifyFileRequestMessage.encode({ filePath, signaturePath }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.VERIFY_FILE, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { verified } = VerifyFileResponseMessage.decode(encodedResponse[0].subMessage);\n return verified;\n }\n //////////////////////\n // Vault Operations //\n //////////////////////\n async listVaults(nodePath) {\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_VAULTS, nodePath);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { vaultNames } = ListVaultsResponseMessage.decode(encodedResponse[0].subMessage);\n return vaultNames;\n }\n async newVault(nodePath, vaultName) {\n const request = NewVaultRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.NEW_VAULT, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = NewVaultResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async destroyVault(nodePath, vaultName) {\n const request = DestroyVaultRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_VAULT, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = DestroyVaultResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n ///////////////////////\n // Secret Operations //\n ///////////////////////\n async listSecrets(nodePath, vaultName) {\n const request = ListSecretsRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_SECRETS, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { secretNames } = ListSecretsResponseMessage.decode(encodedResponse[0].subMessage);\n return secretNames;\n }\n async createSecret(nodePath, vaultName, secretName, secretPath) {\n const request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretPath }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.CREATE_SECRET, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = CreateSecretResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async destroySecret(nodePath, vaultName, secretName) {\n const request = DestroySecretRequestMessage.encode({ vaultName, secretName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_SECRET, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { successful } = DestroySecretResponseMessage.decode(encodedResponse[0].subMessage);\n return successful;\n }\n async getSecret(nodePath, vaultName, secretName) {\n const request = GetSecretRequestMessage.encode({ vaultName, secretName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.GET_SECRET, nodePath, request);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const { secret } = GetSecretResponseMessage.decode(encodedResponse[0].subMessage);\n return Buffer.from(secret);\n }\n ///////////////////\n // Agent control //\n ///////////////////\n async getAgentStatus() {\n try {\n const encodedResponse = await this.handleAgentCommunication(Type.STATUS);\n if (encodedResponse.length == 0) {\n throw Error('agent did not respond');\n }\n const status = encodedResponse[0].subMessage.toString();\n return status;\n }\n catch (err) {\n return 'stopped';\n }\n }\n async stopAgent() {\n try {\n // Tell it to start shutting and wait for response\n await this.handleAgentCommunication(Type.STOP_AGENT);\n return true;\n }\n catch (err) {\n return (await this.getAgentStatus() != 'online');\n }\n }\n}\nexports.default = PolykeyClient;\n","module.exports = require(\"../../proto/js/Agent\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst fs_1 = __importDefault(require(\"fs\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst kbpgp_1 = __importDefault(require(\"kbpgp\"));\nconst crypto_1 = __importDefault(require(\"crypto\"));\nconst util_1 = require(\"util\");\nclass KeyManager {\n constructor(polyKeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, useWebWorkers = false, workerPool) {\n this.primaryKeyPair = { private: null, public: null };\n this.metadata = {\n privateKeyPath: null,\n publicKeyPath: null,\n pkiKeyPath: null,\n pkiCertPath: null,\n caCertPath: null,\n };\n /////////\n // PKI //\n /////////\n this.pkiInfo = { key: null, cert: null, caCert: null };\n this.useWebWorkers = useWebWorkers;\n this.workerPool = workerPool;\n this.derivedKeys = new Map();\n this.fileSystem = fileSystem;\n // Load key manager metadata\n this.polykeyPath = polyKeyPath;\n this.keypairPath = path_1.default.join(polyKeyPath, '.keypair');\n if (!this.fileSystem.existsSync(this.keypairPath)) {\n this.fileSystem.mkdirSync(this.keypairPath, { recursive: true });\n }\n this.metadataPath = path_1.default.join(this.keypairPath, 'metadata');\n this.loadMetadata();\n // Load keys if they were provided\n if (this.metadata.privateKeyPath && this.metadata.publicKeyPath) {\n // Load files into memory\n this.loadKeyPair(this.metadata.publicKeyPath, this.metadata.privateKeyPath);\n }\n /////////\n // PKI //\n /////////\n // Load pki keys and certs\n if (this.metadata.pkiKeyPath) {\n this.pkiInfo.key = fs_1.default.readFileSync(this.metadata.pkiKeyPath);\n }\n if (this.metadata.pkiCertPath) {\n this.pkiInfo.cert = fs_1.default.readFileSync(this.metadata.pkiCertPath);\n }\n if (this.metadata.caCertPath) {\n this.pkiInfo.caCert = fs_1.default.readFileSync(this.metadata.caCertPath);\n }\n this.loadPKIInfo(this.pkiInfo.key, this.pkiInfo.cert, this.pkiInfo.caCert, true);\n }\n get identityLoaded() {\n return (this.primaryIdentity) ? true : false;\n }\n /**\n * Generates a new assymetric key pair (publicKey and privateKey).\n * @param name Name of keypair owner\n * @param email Email of keypair owner\n * @param passphrase Passphrase to lock the keypair\n * @param nbits Size of the new keypair\n * @param replacePrimary If true, the generated keypair becomes the new primary identity of the key manager\n * @param progressCallback A progress hook for keypair generation\n */\n async generateKeyPair(name, email, passphrase, nbits = 4096, replacePrimary = false, progressCallback) {\n // kbpgp doesn't seem to work for small nbits so set a minimum of 1024\n if (nbits < 1024) {\n throw new Error('nbits must be greater than 1024 for keypair generation');\n }\n // Define options\n const flags = kbpgp_1.default[\"const\"].openpgp;\n const params = {\n asp: (progressCallback) ? new kbpgp_1.default.ASP({ progress_hook: progressCallback }) : undefined,\n userid: `${name} <${email}>`,\n primary: {\n nbits: nbits,\n flags: flags.certify_keys | flags.sign_data | flags.auth | flags.encrypt_comm | flags.encrypt_storage,\n expire_in: 0 // never expire\n },\n subkeys: []\n };\n const identity = await util_1.promisify(kbpgp_1.default.KeyManager.generate)(params);\n await util_1.promisify(identity.sign.bind(identity))({});\n // Export pub key first\n const publicKey = await util_1.promisify(identity.export_pgp_public.bind(identity))({});\n // Finally export priv key\n const privateKey = await util_1.promisify(identity.export_pgp_private.bind(identity))({ passphrase: passphrase });\n // Resolve to parent promise\n const keypair = { private: privateKey, public: publicKey };\n if (replacePrimary) {\n // Set the new keypair\n this.primaryKeyPair = keypair;\n // Set the new identity\n this.primaryIdentity = identity;\n // Overwrite in memory\n const privateKeyPath = path_1.default.join(this.keypairPath, 'private_key');\n const publicKeyPath = path_1.default.join(this.keypairPath, 'public_key');\n await this.fileSystem.promises.writeFile(privateKeyPath, keypair.private);\n await this.fileSystem.promises.writeFile(publicKeyPath, keypair.public);\n // Set metadata\n this.metadata.privateKeyPath = privateKeyPath;\n this.metadata.publicKeyPath = publicKeyPath;\n this.writeMetadata();\n }\n return keypair;\n }\n /**\n * Get the primary keypair\n */\n getKeyPair() {\n return this.primaryKeyPair;\n }\n /**\n * Determines whether public key is loaded or not\n */\n hasPublicKey() {\n return (this.primaryKeyPair.public) ? true : false;\n }\n /**\n * Get the public key of the primary keypair\n */\n getPublicKey() {\n if (!this.primaryKeyPair.public) {\n throw new Error('Public key does not exist in memory');\n }\n return this.primaryKeyPair.public;\n }\n /**\n * Get the private key of the primary keypair\n */\n getPrivateKey() {\n if (!this.primaryKeyPair.private) {\n throw new Error('Private key does not exist in memory');\n }\n return this.primaryKeyPair.private;\n }\n /**\n * Loads the keypair into the key manager as the primary identity\n * @param publicKey Public Key\n * @param privateKey Private Key\n */\n loadKeyPair(publicKey, privateKey) {\n this.loadPrivateKey(privateKey);\n this.loadPublicKey(publicKey);\n }\n /**\n * Loads the private key into the primary keypair\n * @param privateKey Private Key\n */\n loadPrivateKey(privateKey) {\n let keyBuffer;\n if (typeof privateKey === 'string') {\n keyBuffer = this.fileSystem.readFileSync(privateKey);\n this.metadata.privateKeyPath = privateKey;\n this.writeMetadata();\n }\n else {\n keyBuffer = privateKey;\n }\n this.primaryKeyPair.private = keyBuffer.toString();\n }\n /**\n * Loads the public key into the primary keypair\n * @param publicKey Public Key\n */\n loadPublicKey(publicKey) {\n let keyBuffer;\n if (typeof publicKey === 'string') {\n keyBuffer = this.fileSystem.readFileSync(publicKey);\n this.metadata.publicKeyPath = publicKey;\n this.writeMetadata();\n }\n else {\n keyBuffer = publicKey;\n }\n this.primaryKeyPair.public = keyBuffer.toString();\n }\n /**\n * Loads the primary identity into the key manager from the existing keypair\n * @param passphrase Passphrase to unlock the private key\n */\n async unlockIdentity(passphrase) {\n const publicKey = this.getPublicKey();\n const privateKey = this.getPrivateKey();\n const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: publicKey });\n await util_1.promisify(identity.merge_pgp_private.bind(identity))({ armored: privateKey });\n if (identity.is_pgp_locked.bind(identity)()) {\n await util_1.promisify(identity.unlock_pgp.bind(identity))({ passphrase: passphrase });\n }\n this.primaryIdentity = identity;\n }\n /**\n * Export the primary private key to a specified location\n * @param path Destination path\n */\n exportPrivateKey(path) {\n this.fileSystem.writeFileSync(path, this.primaryKeyPair.private);\n this.metadata.privateKeyPath = path;\n this.writeMetadata();\n }\n /**\n * Export the primary public key to a specified location\n * @param path Destination path\n */\n exportPublicKey(path) {\n this.fileSystem.writeFileSync(path, this.primaryKeyPair.public);\n this.metadata.publicKeyPath = path;\n this.writeMetadata();\n }\n /**\n * Synchronously generates a new symmetric key and stores it in the key manager\n * @param name Unique name of the generated key\n * @param passphrase Passphrase to derive the key from\n */\n generateKeySync(name, passphrase) {\n const salt = crypto_1.default.randomBytes(32);\n this.derivedKeys[name] = crypto_1.default.pbkdf2Sync(passphrase, salt, 10000, 256 / 8, 'sha256');\n return this.derivedKeys[name];\n }\n /**\n * Asynchronously Generates a new symmetric key and stores it in the key manager\n * @param name Unique name of the generated key\n * @param passphrase Passphrase to derive the key from\n */\n async generateKey(name, passphrase) {\n const salt = crypto_1.default.randomBytes(32);\n this.derivedKeys[name] = await util_1.promisify(crypto_1.default.pbkdf2)(passphrase, salt, 10000, 256 / 8, 'sha256');\n return this.derivedKeys[name];\n }\n /**\n * Synchronously imports an existing key from file or Buffer\n * @param name Unique name of the imported key\n * @param key Key to be imported\n */\n importKeySync(name, key) {\n if (typeof key === 'string') {\n this.derivedKeys[name] = this.fileSystem.readFileSync(key);\n }\n else {\n this.derivedKeys[name] = key;\n }\n }\n /**\n * Asynchronously imports an existing key from file or Buffer\n * @param name Unique name of the imported key\n * @param key Key to be imported\n */\n async importKey(name, key) {\n if (typeof key === 'string') {\n this.derivedKeys[name] = await this.fileSystem.promises.readFile(key);\n }\n else {\n this.derivedKeys[name] = key;\n }\n }\n /**\n * Synchronously exports an existing key from file or Buffer\n * @param name Name of the key to be exported\n * @param dest Destination path\n * @param createPath If set to true, the path is recursively created\n */\n exportKeySync(name, dest, createPath) {\n if (!this.derivedKeys.has(name)) {\n throw Error(`There is no key loaded for name: ${name}`);\n }\n if (createPath) {\n this.fileSystem.mkdirSync(path_1.default.dirname(dest), { recursive: true });\n }\n this.fileSystem.writeFileSync(dest, this.derivedKeys[name]);\n }\n /**\n * Asynchronously exports an existing key from file or Buffer\n * @param name Name of the key to be exported\n * @param dest Destination path\n * @param createPath If set to true, the path is recursively created\n */\n async exportKey(name, dest, createPath) {\n if (!this.derivedKeys.has(name)) {\n throw Error(`There is no key loaded for name: ${name}`);\n }\n if (createPath) {\n await this.fileSystem.promises.mkdir(path_1.default.dirname(dest), { recursive: true });\n }\n await this.fileSystem.promises.writeFile(dest, this.derivedKeys[name]);\n }\n /**\n * Loads an identity from the given public key\n * @param publicKey Buffer containing the public key\n */\n async getIdentityFromPublicKey(publicKey) {\n const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: publicKey });\n return identity;\n }\n /**\n * Loads an identity from the given private key\n * @param publicKey Buffer containing the public key\n */\n async getIdentityFromPrivateKey(privateKey, passphrase) {\n const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: privateKey });\n if (identity.is_pgp_locked()) {\n await util_1.promisify(identity.unlock_pgp)({ passphrase: passphrase });\n }\n return identity;\n }\n /**\n * Signs the given data with the provided key or the primary key if none is specified\n * @param data Buffer or file containing the data to be signed\n * @param privateKey Buffer containing the key to sign with. Defaults to primary private key if no key is given.\n * @param keyPassphrase Required if privateKey is provided.\n */\n async signData(data, privateKey, keyPassphrase) {\n let resolvedIdentity;\n if (privateKey) {\n if (!keyPassphrase) {\n throw new Error('passphrase for private key was not provided');\n }\n resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase);\n }\n else if (this.primaryIdentity) {\n resolvedIdentity = this.primaryIdentity;\n }\n else {\n throw new Error('key pair is not loaded');\n }\n if (this.useWebWorkers && this.workerPool) {\n const workerResponse = await this.workerPool.queue(async (workerCrypto) => {\n return await workerCrypto.signData(data, resolvedIdentity);\n });\n return workerResponse;\n }\n else {\n const params = {\n msg: data.toString(),\n sign_with: resolvedIdentity\n };\n const result_string = await util_1.promisify(kbpgp_1.default.box)(params);\n return Buffer.from(result_string);\n }\n }\n /**\n * Signs the given file with the provided key or the primary key if none is specified\n * @param filePath Path to file containing the data to be signed\n * @param privateKey The key to sign with. Defaults to primary public key if no key is given.\n * @param keyPassphrase Required if privateKey is provided.\n */\n async signFile(filePath, privateKey, keyPassphrase) {\n // Get key if provided\n let keyBuffer;\n if (privateKey) {\n if (typeof privateKey === 'string') { // Path\n // Read in from fs\n keyBuffer = this.fileSystem.readFileSync(privateKey);\n }\n else { // Buffer\n keyBuffer = privateKey;\n }\n }\n // Read file into buffer\n const buffer = this.fileSystem.readFileSync(filePath);\n // Sign the buffer\n const signedBuffer = await this.signData(buffer, keyBuffer, keyPassphrase);\n // Write buffer to signed file\n const signedPath = `${filePath}.sig`;\n this.fileSystem.writeFileSync(signedPath, signedBuffer);\n return signedPath;\n }\n /**\n * Verifies the given data with the provided key or the primary key if none is specified\n * @param data Buffer or file containing the data to be verified\n * @param signature The PGP signature\n * @param publicKey Buffer containing the key to verify with. Defaults to primary public key if no key is given.\n */\n async verifyData(data, signature, publicKey) {\n const ring = new kbpgp_1.default.keyring.KeyRing;\n let resolvedIdentity;\n if (publicKey) {\n resolvedIdentity = await this.getIdentityFromPublicKey(publicKey);\n }\n else if (this.primaryIdentity) {\n resolvedIdentity = this.primaryIdentity;\n }\n else {\n throw new Error('key pair is not loaded');\n }\n ring.add_key_manager(resolvedIdentity);\n if (this.useWebWorkers && this.workerPool) {\n const workerResponse = await this.workerPool.queue(async (workerCrypto) => {\n return await workerCrypto.verifyData(data, signature, resolvedIdentity);\n });\n return workerResponse;\n }\n else {\n const params = {\n armored: signature,\n data: data,\n keyfetch: ring\n };\n const literals = await util_1.promisify(kbpgp_1.default.unbox)(params);\n // Get the identity that signed the data if any\n let dataSigner = literals[0].get_data_signer();\n // Retrieve the key manager associated with that data signer\n let keyManager;\n if (dataSigner) {\n keyManager = dataSigner.get_key_manager();\n }\n // If we know the pgp finger print then we say the data is verified.\n // Otherwise it is unverified.\n if (keyManager) {\n if (keyManager.get_pgp_fingerprint()) {\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return false;\n }\n }\n }\n /**\n * Verifies the given file with the provided key or the primary key if none is specified\n * @param filePath Path to file containing the data to be verified\n * @param signaturePath The path to the file containing the PGP signature\n * @param publicKey Buffer containing the key to verify with. Defaults to primary public key if no key is given.\n */\n async verifyFile(filePath, signaturePath, publicKey) {\n // Get key if provided\n let keyBuffer;\n if (publicKey) {\n if (typeof publicKey === 'string') { // Path\n // Read in from fs\n keyBuffer = this.fileSystem.readFileSync(publicKey);\n }\n else { // Buffer\n keyBuffer = publicKey;\n }\n }\n // Read in file buffer and signature\n const fileBuffer = this.fileSystem.readFileSync(filePath);\n const signatureBuffer = this.fileSystem.readFileSync(signaturePath);\n const isVerified = await this.verifyData(fileBuffer, signatureBuffer, keyBuffer);\n return isVerified;\n }\n /**\n * Encrypts the given data for a specific public key\n * @param data The data to be encrypted\n * @param publicKey The key to encrypt for\n */\n async encryptData(data, publicKey) {\n let resolvedIdentity;\n if (publicKey) {\n resolvedIdentity = await this.getIdentityFromPublicKey(publicKey);\n }\n else if (this.primaryIdentity) {\n resolvedIdentity = this.primaryIdentity;\n }\n else {\n throw new Error(`Identity could not be resolved for encrypting`);\n }\n if (this.useWebWorkers && this.workerPool) {\n const workerResponse = await this.workerPool.queue(async (workerCrypto) => {\n return await workerCrypto.encryptData(data, resolvedIdentity);\n });\n return workerResponse;\n }\n else {\n const params = {\n msg: data,\n encrypt_for: resolvedIdentity\n };\n const result_string = await util_1.promisify(kbpgp_1.default.box)(params);\n return result_string;\n }\n }\n /**\n * Decrypts the given data with the provided key or the primary key if none is given\n * @param data The data to be decrypted\n * @param privateKey The key to decrypt with. Defaults to primary private key if no key is given.\n * @param keyPassphrase Required if privateKey is provided.\n */\n async decryptData(data, privateKey, keyPassphrase) {\n var ring = new kbpgp_1.default.keyring.KeyRing;\n let resolvedIdentity;\n if (privateKey) {\n if (keyPassphrase) {\n resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase);\n }\n else {\n throw new Error('A key passphrase must be supplied if a privateKey is specified');\n }\n }\n else if (this.primaryIdentity) {\n resolvedIdentity = this.primaryIdentity;\n }\n else {\n throw Error('no identity available for decrypting');\n }\n if (this.useWebWorkers && this.workerPool) {\n const workerResponse = await this.workerPool.queue(async (workerCrypto) => {\n return await workerCrypto.decryptData(data, resolvedIdentity);\n });\n return workerResponse;\n }\n else {\n ring.add_key_manager(resolvedIdentity);\n const params = {\n armored: data.toString(),\n keyfetch: ring\n };\n const literals = await util_1.promisify(kbpgp_1.default.unbox)(params);\n const decryptedData = Buffer.from(literals[0].toString());\n return decryptedData;\n }\n }\n /////////\n // PKI //\n /////////\n get PKIInfo() {\n return this.pkiInfo;\n }\n loadPKIInfo(key, cert, caCert, writeToFile = false) {\n if (key) {\n this.pkiInfo.key = key;\n }\n if (cert) {\n this.pkiInfo.cert = cert;\n }\n if (caCert) {\n this.pkiInfo.caCert = caCert;\n }\n if (writeToFile) {\n // Store in the metadata path folder\n const storagePath = path_1.default.dirname(this.metadataPath);\n if (key) {\n this.metadata.pkiKeyPath = path_1.default.join(storagePath, 'pki_private_key');\n fs_1.default.writeFileSync(this.metadata.pkiKeyPath, key);\n }\n if (cert) {\n this.metadata.pkiCertPath = path_1.default.join(storagePath, 'pki_cert');\n fs_1.default.writeFileSync(this.metadata.pkiCertPath, cert);\n }\n if (caCert) {\n this.metadata.caCertPath = path_1.default.join(storagePath, 'ca_cert');\n fs_1.default.writeFileSync(this.metadata.caCertPath, caCert);\n }\n }\n }\n /* ============ HELPERS =============== */\n /**\n * Get the key for a given name\n * @param name The unique name of the desired key\n */\n getKey(name) {\n return this.derivedKeys[name];\n }\n /**\n * Determines if the Key Manager has a certain key\n * @param name The unique name of the desired key\n */\n hasKey(name) {\n if (this.derivedKeys[name]) {\n return true;\n }\n return false;\n }\n writeMetadata() {\n const metadata = JSON.stringify(this.metadata);\n this.fileSystem.writeFileSync(this.metadataPath, metadata);\n }\n loadMetadata() {\n // Check if file exists\n if (this.fileSystem.existsSync(this.metadataPath)) {\n const metadata = this.fileSystem.readFileSync(this.metadataPath).toString();\n this.metadata = JSON.parse(metadata);\n }\n }\n}\nexports.default = KeyManager;\n","module.exports = require(\"kbpgp\");","module.exports = require(\"util\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst grpc = __importStar(require(\"@grpc/grpc-js\"));\nconst GitClient_1 = __importDefault(require(\"../git/GitClient\"));\nconst GitBackend_1 = __importDefault(require(\"../git/GitBackend\"));\nconst Peer_1 = require(\"../../../proto/js/Peer\");\nconst utils_1 = require(\"../utils\");\nconst PeerInfo_1 = __importStar(require(\"../peers/PeerInfo\"));\nconst MulticastBroadcaster_1 = __importDefault(require(\"../peers/MulticastBroadcaster\"));\nconst Git_grpc_pb_1 = require(\"../../../proto/compiled/Git_grpc_pb\");\nconst Git_pb_1 = require(\"../../../proto/compiled/Git_pb\");\nconst keybaseDiscovery = {\n name: 'Keybase',\n findUser: async (handle, service) => {\n const url = `https://keybase.io/_/api/1.0/user/lookup.json?${service}=${handle}`;\n try {\n const response = await fetch(url);\n const data = await response.json();\n const pubKey = data.them[0].public_keys.primary.bundle;\n return pubKey;\n }\n catch (err) {\n throw new Error(`User was not found: ${err.message}`);\n }\n }\n};\nclass PeerManager {\n constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager, vaultManager, peerInfo, socialDiscoveryServices = []) {\n var _a;\n this.metadata = { localPeerInfo: null };\n this.serverStarted = false;\n this.fileSystem = fileSystem;\n this.fileSystem.mkdirSync(polykeyPath, { recursive: true });\n this.metadataPath = path_1.default.join(polykeyPath, '.peerMetadata');\n // Set given variables\n this.keyManager = keyManager;\n this.socialDiscoveryServices = socialDiscoveryServices;\n // Load metadata with peer info\n this.loadMetadata();\n // Load peer store and local peer info\n if (peerInfo) {\n this.localPeerInfo = peerInfo;\n this.writeMetadata();\n }\n else if (this.metadata.localPeerInfo) {\n this.localPeerInfo = this.metadata.localPeerInfo;\n }\n else if (this.keyManager.hasPublicKey()) {\n this.localPeerInfo = new PeerInfo_1.default(this.keyManager.getPublicKey());\n }\n this.peerStore = new Map();\n this.socialDiscoveryServices = [];\n this.socialDiscoveryServices.push(keybaseDiscovery);\n for (const service of socialDiscoveryServices) {\n this.socialDiscoveryServices.push(service);\n }\n this.multicastBroadcaster = new MulticastBroadcaster_1.default(this.addPeer, this.localPeerInfo, this.keyManager);\n this.peerConnections = new Map();\n /////////////////\n // GRPC Server //\n /////////////////\n this.gitBackend = new GitBackend_1.default(polykeyPath, vaultManager);\n this.server = new grpc.Server();\n // Add service\n this.server.addService(Git_grpc_pb_1.GitServerService, {\n requestInfo: this.requestInfo.bind(this),\n requestPack: this.requestPack.bind(this)\n });\n // Create the server credentials. SSL only if ca cert exists\n const pkiInfo = this.keyManager.PKIInfo;\n // if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) {\n // this.credentials = grpc.ServerCredentials.createSsl(\n // pkiInfo.caCert,\n // [{\n // private_key: pkiInfo.key,\n // cert_chain: pkiInfo.cert,\n // }],\n // true\n // )\n // } else {\n this.credentials = grpc.ServerCredentials.createInsecure();\n // }\n this.server.bindAsync(`0.0.0.0:${(_a = process.env.PK_PORT) !== null && _a !== void 0 ? _a : 0}`, this.credentials, (err, boundPort) => {\n if (err) {\n throw err;\n }\n else {\n const address = new PeerInfo_1.Address('localhost', boundPort.toString());\n this.server.start();\n this.localPeerInfo.connect(address);\n this.serverStarted = true;\n }\n });\n }\n async requestInfo(call, callback) {\n const infoRequest = call.request;\n const vaultName = infoRequest.getVaultname();\n const infoReply = new Git_pb_1.InfoReply();\n infoReply.setVaultname(vaultName);\n infoReply.setBody(await this.gitBackend.handleInfoRequest(vaultName));\n callback(null, infoReply);\n }\n async requestPack(call, callback) {\n const packRequest = call.request;\n const vaultName = packRequest.getVaultname();\n const body = Buffer.from(packRequest.getBody_asB64(), 'base64');\n const reply = new Git_pb_1.PackReply();\n reply.setVaultname(vaultName);\n reply.setBody(await this.gitBackend.handlePackRequest(vaultName, body));\n callback(null, reply);\n }\n ////////////////\n // Peer store //\n ////////////////\n /**\n * Get the peer info of the current keynode\n */\n getLocalPeerInfo() {\n return this.localPeerInfo;\n }\n /**\n * Set the address of the active server\n * @param adress Address of active server\n */\n connectLocalPeerInfo(address) {\n this.localPeerInfo.connect(address);\n }\n /**\n * Add a peer's info to the peerStore\n * @param peerInfo Info of the peer to be added\n */\n addPeer(peerInfo) {\n this.peerStore.set(peerInfo.publicKey, peerInfo);\n }\n /**\n * Retrieves a peer for the given public key\n * @param publicKey Public key of the desired peer\n */\n getPeer(publicKey) {\n var _a;\n return (_a = this.peerStore.get(publicKey)) !== null && _a !== void 0 ? _a : null;\n }\n /**\n * Determines if the peerStore contains the desired peer\n * @param publicKey Public key of the desired peer\n */\n hasPeer(pubKey) {\n return this.peerStore.has(pubKey);\n }\n //////////////////////\n // Social discovery //\n //////////////////////\n /**\n * Finds an existing peer using multicast peer discovery\n * @param publicKey Public key of the desired peer\n */\n async findPubKey(publicKey) {\n return new Promise((resolve, reject) => {\n this.multicastBroadcaster.requestPeerContact(publicKey);\n this.multicastBroadcaster.on('found', (peerInfo) => {\n if (peerInfo.publicKey == publicKey) {\n resolve(peerInfo);\n }\n });\n this.multicastBroadcaster.on('timeout', (timedOutPubKey) => {\n if (timedOutPubKey == publicKey) {\n reject('The broadcaster stopped looking');\n }\n });\n });\n }\n /**\n * Finds an existing peer given a social service and handle\n * @param handle Username or handle of the user (e.g. @john-smith)\n * @param service Service on which to search for the user (e.g. github)\n */\n async findSocialUser(handle, service) {\n const tasks = [];\n for (const socialDiscovery of this.socialDiscoveryServices) {\n try {\n tasks.push(socialDiscovery.findUser(handle, service));\n }\n catch (error) {\n console.log(`Could not find user on this discovery service: ${socialDiscovery.name}`);\n }\n }\n const pubKeyOrFail = await utils_1.firstPromiseFulfilled(tasks);\n if (pubKeyOrFail.length > 1) {\n throw new Error('Could not find public key from services');\n }\n const pubKeyFound = pubKeyOrFail[0];\n const peerInfo = await this.findPubKey(pubKeyFound);\n return peerInfo;\n }\n ///////////////////////\n // Peers Connections //\n ///////////////////////\n /**\n * Get a secure connection to the peer\n * @param peer Public key of an existing peer or address of new peer\n */\n connectToPeer(peer) {\n var _a;\n // Throw error if trying to connect to self\n if (peer == this.localPeerInfo.connectedAddr || peer == this.localPeerInfo.publicKey) {\n throw new Error('Cannot connect to self');\n }\n let address;\n if (typeof peer == 'string') {\n const existingSocket = this.peerConnections.get(peer);\n if (existingSocket) {\n return existingSocket;\n }\n const peerAddress = (_a = this.getPeer(peer)) === null || _a === void 0 ? void 0 : _a.connectedAddr;\n if (peerAddress) {\n address = peerAddress;\n }\n else {\n throw new Error('Peer does not exist in peer store');\n }\n }\n else {\n address = peer;\n }\n const conn = new GitClient_1.default(address, this.keyManager);\n if (typeof peer == 'string') {\n this.peerConnections.set(peer, conn);\n }\n return conn;\n }\n /* ============ HELPERS =============== */\n writeMetadata() {\n var _a;\n const peerInfo = this.localPeerInfo;\n const metadata = Peer_1.peer.PeerInfoMessage.encode({\n addresses: peerInfo.AdressStringList,\n connectedAddr: (_a = peerInfo.connectedAddr) === null || _a === void 0 ? void 0 : _a.toString(),\n pubKey: peerInfo.publicKey\n }).finish();\n this.fileSystem.writeFileSync(this.metadataPath, metadata);\n }\n loadMetadata() {\n // Check if file exists\n if (this.fileSystem.existsSync(this.metadataPath)) {\n const metadata = this.fileSystem.readFileSync(this.metadataPath);\n const { addresses, connectedAddr, pubKey } = Peer_1.peer.PeerInfoMessage.decode(metadata);\n this.localPeerInfo = new PeerInfo_1.default(pubKey, addresses, connectedAddr);\n }\n }\n}\nexports.default = PeerManager;\n","\"use strict\";\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst grpc = __importStar(require(\"@grpc/grpc-js\"));\nconst Git_grpc_pb_1 = require(\"../../../proto/compiled/Git_grpc_pb\");\nconst Git_pb_1 = require(\"../../../proto/compiled/Git_pb\");\n/**\n * Responsible for converting HTTP messages from isomorphic-git into requests and sending them to a specific peer.\n */\nclass GitClient {\n constructor(address, keyManager) {\n // const pkiInfo = keyManager.PKIInfo\n // if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) {\n // this.credentials = grpc.credentials.createSsl(\n // pkiInfo.caCert,\n // pkiInfo.key,\n // pkiInfo.cert,\n // )\n // } else {\n this.credentials = grpc.credentials.createInsecure();\n // }\n this.client = new Git_grpc_pb_1.GitServerClient(address.toString(), this.credentials);\n }\n /**\n * The custom http request method to feed into isomorphic-git's [custom http object](https://isomorphic-git.org/docs/en/http)\n */\n async request({ url, method, headers, body, onProgress }) {\n return new Promise(async (resolve, reject) => {\n const u = new URL(url);\n // Parse request\n if (method == 'GET') {\n // Info request\n const match = u.pathname.match(/\\/(.+)\\/info\\/refs$/);\n if (!match || /\\.\\./.test(match[1])) {\n reject(new Error('Error'));\n }\n const vaultName = match[1];\n const infoResponse = await this.requestInfo(vaultName);\n resolve({\n url: url,\n method: method,\n statusCode: 200,\n statusMessage: 'OK',\n body: this.iteratorFromData(infoResponse),\n headers: headers\n });\n }\n else if (method == 'POST') {\n // Info request\n const match = u.pathname.match(/\\/(.+)\\/git-(.+)/);\n if (!match || /\\.\\./.test(match[1])) {\n reject(new Error('Error'));\n }\n const vaultName = match[1];\n const packResponse = await this.requestPack(vaultName, body[0]);\n resolve({\n url: url,\n method: method,\n statusCode: 200,\n statusMessage: 'OK',\n body: this.iteratorFromData(packResponse),\n headers: headers\n });\n }\n else {\n reject(new Error('Method not supported'));\n }\n });\n }\n // ==== HELPER METHODS ==== //\n /**\n * Requests remote info from the connected peer for the named vault.\n * @param vaultName Name of the desired vault\n */\n async requestInfo(vaultName) {\n return new Promise((resolve, reject) => {\n const request = new Git_pb_1.InfoRequest();\n request.setVaultname(vaultName);\n this.client.requestInfo(request, function (err, response) {\n if (err) {\n reject(err);\n }\n else {\n resolve(Buffer.from(response.getBody_asB64(), 'base64'));\n }\n });\n });\n }\n /**\n * Requests a pack from the connected peer for the named vault.\n * @param vaultName Name of the desired vault\n */\n async requestPack(vaultName, body) {\n return new Promise((resolve, reject) => {\n const request = new Git_pb_1.PackRequest;\n request.setVaultname(vaultName);\n request.setBody(body);\n this.client.requestPack(request, function (err, response) {\n if (err) {\n reject(err);\n }\n else {\n resolve(Buffer.from(response.getBody_asB64(), 'base64'));\n }\n });\n });\n }\n /**\n * Converts a buffer into an iterator expected by isomorphic git.\n * @param data Data to be turned into an iterator\n */\n iteratorFromData(data) {\n let ended = false;\n return {\n next() {\n return new Promise((resolve, reject) => {\n if (ended) {\n return resolve({ done: true });\n }\n else {\n ended = true;\n resolve({ value: data, done: false });\n }\n });\n },\n };\n }\n}\nexports.default = GitClient;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst path_1 = __importDefault(require(\"path\"));\nconst readable_stream_1 = require(\"readable-stream\");\nconst uploadPack_1 = __importDefault(require(\"./upload-pack/uploadPack\"));\nconst GitSideBand_1 = __importDefault(require(\"./side-band/GitSideBand\"));\nconst packObjects_1 = __importDefault(require(\"./pack-objects/packObjects\"));\n// Here is the protocol git outlines for sending pack files over http:\n// https://git-scm.com/docs/pack-protocol/2.17.0\n// https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt\n// This should be consulted in developing our upload pack implementation\n// This git backend (as well as HttpDuplex class) is heavily inspired by node-git-server:\n// https://github.com/gabrielcsapo/node-git-server\n// We need someway to notify other agents about what vaults we have based on some type of authorisation because they don't explicitly know about them\nclass GitBackend {\n constructor(polykeyPath, vaultManager) {\n this.polykeyPath = polykeyPath;\n this.vaultManager = vaultManager;\n }\n /**\n * Find out whether vault exists.\n * @param vaultName Name of vault to check\n * @param publicKey Public key of peer trying to access vault\n */\n exists(vaultName, publicKey) {\n try {\n const vault = this.vaultManager.getVault(vaultName);\n if (vault) {\n return vault.peerCanAccess(publicKey);\n }\n return false;\n }\n catch (error) {\n return false;\n }\n }\n async handleInfoRequest(vaultName) {\n var _a;\n // Only handle upload-pack for now\n const service = 'upload-pack';\n const connectingPublicKey = '';\n const responseBuffers = [];\n if (!this.exists(vaultName, connectingPublicKey)) {\n throw new Error('Vault does not exist');\n }\n else {\n responseBuffers.push(Buffer.from(this.createGitPacketLine('# service=git-' + service + '\\n')));\n responseBuffers.push(Buffer.from('0000'));\n const fileSystem = (_a = this.vaultManager.getVault(vaultName)) === null || _a === void 0 ? void 0 : _a.EncryptedFS;\n const buffers = await uploadPack_1.default(fileSystem, path_1.default.join(this.polykeyPath, vaultName), undefined, true);\n const buffersToWrite = buffers !== null && buffers !== void 0 ? buffers : [];\n responseBuffers.push(...buffersToWrite);\n }\n return Buffer.concat(responseBuffers);\n }\n async handlePackRequest(vaultName, body) {\n return new Promise(async (resolve, reject) => {\n var _a;\n const responseBuffers = [];\n // Check if vault exists\n const connectingPublicKey = '';\n if (!this.exists(vaultName, connectingPublicKey)) {\n throw new Error('Vault does not exist');\n }\n const fileSystem = (_a = this.vaultManager.getVault(vaultName)) === null || _a === void 0 ? void 0 : _a.EncryptedFS;\n if (fileSystem) {\n if (body.toString().slice(4, 8) == 'want') {\n const wantedObjectId = body.toString().slice(9, 49);\n const packResult = await packObjects_1.default(fileSystem, path_1.default.join(this.polykeyPath, vaultName), [wantedObjectId], undefined);\n // This the 'wait for more data' line as I understand it\n responseBuffers.push(Buffer.from('0008NAK\\n'));\n // This is to get the side band stuff working\n const readable = new readable_stream_1.PassThrough();\n const progressStream = new readable_stream_1.PassThrough();\n const sideBand = GitSideBand_1.default.mux('side-band-64', readable, packResult.packstream, progressStream, []);\n sideBand.on('data', (data) => {\n responseBuffers.push(data);\n });\n sideBand.on('end', () => {\n resolve(Buffer.concat(responseBuffers));\n });\n sideBand.on('error', (err) => {\n reject(err);\n });\n // Write progress to the client\n progressStream.write(Buffer.from('0014progress is at 50%\\n'));\n progressStream.end();\n }\n }\n });\n }\n // ============ Helper functions ============ //\n createGitPacketLine(line) {\n const hexPrefix = (4 + line.length).toString(16);\n return Array(4 - hexPrefix.length + 1).join('0') + hexPrefix + line;\n }\n}\nexports.default = GitBackend;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst path_1 = __importDefault(require(\"path\"));\nconst GitPktLine_1 = __importDefault(require(\"./GitPktLine\"));\nconst GitRefManager_1 = __importDefault(require(\"./GitRefManager\"));\nasync function writeRefsAdResponse({ capabilities, refs, symrefs }) {\n const stream = [];\n // Compose capabilities string\n let syms = '';\n for (const [key, value] of Object.entries(symrefs)) {\n syms += `symref=${key}:${value} `;\n }\n let caps = `\\x00${[...capabilities].join(' ')} ${syms}agent=git/isomorphic-git@1.4.0`;\n // stream.write(GitPktLine.encode(`# service=${service}\\n`))\n // stream.write(GitPktLine.flush())\n // Note: In the edge case of a brand new repo, zero refs (and zero capabilities)\n // are returned.\n for (const [key, value] of Object.entries(refs)) {\n stream.push(GitPktLine_1.default.encode(`${value} ${key}${caps}\\n`));\n caps = '';\n }\n stream.push(GitPktLine_1.default.flush());\n return stream;\n}\nasync function uploadPack(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), advertiseRefs = false) {\n try {\n if (advertiseRefs) {\n // Send a refs advertisement\n const capabilities = [\n 'side-band-64k',\n ];\n let keys = await GitRefManager_1.default.listRefs(fileSystem, gitdir, 'refs');\n keys = keys.map(ref => `refs/${ref}`);\n const refs = {};\n keys.unshift('HEAD'); // HEAD must be the first in the list\n for (const key of keys) {\n refs[key] = await GitRefManager_1.default.resolve(fileSystem, gitdir, key);\n }\n const symrefs = {};\n symrefs['HEAD'] = await GitRefManager_1.default.resolve(fileSystem, gitdir, 'HEAD', 2);\n return writeRefsAdResponse({\n capabilities,\n refs,\n symrefs,\n });\n }\n }\n catch (err) {\n err.caller = 'git.uploadPack';\n throw err;\n }\n}\nexports.default = uploadPack;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass GitPackedRefs {\n constructor(text) {\n this.refs = new Map();\n this.parsedConfig = [];\n if (text) {\n let key;\n this.parsedConfig = text\n .trim()\n .split('\\n')\n .map(line => {\n if (/^\\s*#/.test(line)) {\n return { line: line, comment: true };\n }\n const i = line.indexOf(' ');\n if (line.startsWith('^')) {\n // This is a oid for the commit associated with the annotated tag immediately preceding this line.\n // Trim off the '^'\n const value = line.slice(1);\n // The tagname^{} syntax is based on the output of `git show-ref --tags -d`\n this.refs.set(key + '^{}', value);\n return { line: line, ref: key, peeled: value };\n }\n else {\n // This is an oid followed by the ref name\n const value = line.slice(0, i);\n key = line.slice(i + 1);\n this.refs.set(key, value);\n return { line: line, ref: key, oid: value };\n }\n });\n }\n return this;\n }\n static from(text) {\n return new GitPackedRefs(text);\n }\n}\nexports.default = GitPackedRefs;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/*\nIf 'side-band' or 'side-band-64k' capabilities have been specified by\nthe client, the server will send the packfile data multiplexed.\n\nEach packet starting with the packet-line length of the amount of data\nthat follows, followed by a single byte specifying the sideband the\nfollowing data is coming in on.\n\nIn 'side-band' mode, it will send up to 999 data bytes plus 1 control\ncode, for a total of up to 1000 bytes in a pkt-line. In 'side-band-64k'\nmode it will send up to 65519 data bytes plus 1 control code, for a\ntotal of up to 65520 bytes in a pkt-line.\n\nThe sideband byte will be a '1', '2' or a '3'. Sideband '1' will contain\npackfile data, sideband '2' will be used for progress information that the\nclient will generally print to stderr and sideband '3' is used for error\ninformation.\n\nIf no 'side-band' capability was specified, the server will stream the\nentire packfile without multiplexing.\n*/\nconst buffer_1 = require(\"buffer\");\nconst readable_stream_1 = require(\"readable-stream\");\nconst GitPktLine_1 = __importDefault(require(\"../upload-pack/GitPktLine\"));\nfunction splitBuffer(buffer, maxBytes) {\n const result = [];\n let index = 0;\n while (index < buffer.length) {\n const buf = buffer.slice(index, index + maxBytes);\n result.push(buf);\n index += buf.length;\n }\n result.push(buffer.slice(index));\n return result;\n}\nclass GitSideBand {\n static demux(input) {\n let read = GitPktLine_1.default.streamReader(input);\n // And now for the ridiculous side-band or side-band-64k protocol\n let packetlines = new readable_stream_1.PassThrough();\n let packfile = new readable_stream_1.PassThrough();\n let progress = new readable_stream_1.PassThrough();\n // TODO: Use a proper through stream?\n const nextBit = async function () {\n let line = await read();\n // Skip over flush packets\n if (line === null)\n return nextBit();\n // A made up convention to signal there's no more to read.\n if (line === true) {\n packetlines.end();\n progress.end();\n packfile.end();\n return;\n }\n // Examine first byte to determine which output \"stream\" to use\n switch (line[0]) {\n case 1: // pack data\n packfile.write(line.slice(1));\n break;\n case 2: // progress message\n progress.write(line.slice(1));\n break;\n case 3: // fatal error message just before stream aborts\n let error = line.slice(1);\n progress.write(error);\n packfile.destroy(new Error(error.toString('utf8')));\n return;\n default:\n // Not part of the side-band-64k protocol\n packetlines.write(line.slice(0));\n }\n // Careful not to blow up the stack.\n // I think Promises in a tail-call position should be OK.\n nextBit();\n };\n nextBit();\n return {\n packetlines,\n packfile,\n progress\n };\n }\n static mux(protocol, // 'side-band' or 'side-band-64k'\n packetlines, packfile, progress, error) {\n const MAX_PACKET_LENGTH = protocol === 'side-band-64k' ? 999 : 65519;\n let output = new readable_stream_1.PassThrough();\n packetlines.on('data', data => {\n if (data === null) {\n output.write(GitPktLine_1.default.flush());\n }\n else {\n output.write(GitPktLine_1.default.encode(data));\n }\n });\n let packfileWasEmpty = true;\n let packfileEnded = false;\n let progressEnded = false;\n let errorEnded = true;\n let goodbye = buffer_1.Buffer.concat([\n GitPktLine_1.default.encode(buffer_1.Buffer.from('010A', 'hex')),\n GitPktLine_1.default.flush()\n ]);\n packfile\n .on('data', data => {\n packfileWasEmpty = false;\n const buffers = splitBuffer(data, MAX_PACKET_LENGTH);\n for (const buffer of buffers) {\n output.write(GitPktLine_1.default.encode(buffer_1.Buffer.concat([buffer_1.Buffer.from('01', 'hex'), buffer])));\n }\n })\n .on('end', () => {\n packfileEnded = true;\n if (!packfileWasEmpty)\n output.write(goodbye);\n if (progressEnded && errorEnded)\n output.end();\n });\n progress\n .on('data', data => {\n const buffers = splitBuffer(data, MAX_PACKET_LENGTH);\n for (const buffer of buffers) {\n output.write(GitPktLine_1.default.encode(buffer_1.Buffer.concat([buffer_1.Buffer.from('02', 'hex'), buffer])));\n }\n })\n .on('end', () => {\n progressEnded = true;\n if (packfileEnded && errorEnded)\n output.end();\n });\n // error\n // .on('data', data => {\n // const buffers = splitBuffer(data, MAX_PACKET_LENGTH)\n // for (const buffer of buffers) {\n // output.write(\n // GitPktLine.encode(Buffer.concat([Buffer.from('03', 'hex'), buffer]))\n // )\n // }\n // })\n // .on('end', () => {\n // errorEnded = true\n // if (progressEnded && packfileEnded) output.end()\n // })\n return output;\n }\n}\nexports.default = GitSideBand;\n","module.exports = require(\"buffer\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst pako_1 = __importDefault(require(\"pako\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst log_1 = __importDefault(require(\"./log\"));\nconst GitTree_1 = __importDefault(require(\"./GitTree\"));\nconst sha_js_1 = __importDefault(require(\"sha.js\"));\nconst GitCommit_1 = __importDefault(require(\"./GitCommit\"));\nconst readable_stream_1 = require(\"readable-stream\");\nconst GitObjectManager_1 = __importDefault(require(\"./GitObjectManager\"));\nconst types = {\n commit: 0b0010000,\n tree: 0b0100000,\n blob: 0b0110000,\n tag: 0b1000000,\n ofs_delta: 0b1100000,\n ref_delta: 0b1110000\n};\n/**\n * Create a packfile stream\n *\n * @link https://isomorphic-git.github.io/docs/packObjects.html\n */\nasync function packObjects(fileSystem, dir, refs, depth, haves) {\n const gitdir = path_1.default.join(dir, '.git');\n let oids = new Set();\n let shallows = new Set();\n let unshallows = new Set();\n let acks = [];\n haves = (haves) ? haves : [];\n const emitter = undefined;\n const since = undefined;\n for (const ref of refs) {\n try {\n let commits = await log_1.default(fileSystem, dir, gitdir, emitter, ref, depth, since);\n let oldshallows = [];\n for (let i = 0; i < commits.length; i++) {\n let commit = commits[i];\n if (haves.includes(commit.oid)) {\n acks.push({\n oid: ref\n });\n break;\n }\n oids.add(commit.oid);\n if (i === commits.length - 1) {\n if (!oldshallows.includes(commit.oid) &&\n (depth !== undefined || since !== undefined)) {\n console.log('make it shallow', commit.oid);\n shallows.add(commit.oid);\n }\n }\n else if (oldshallows.includes(commit.oid)) {\n console.log('make it unshallow', commit.oid);\n unshallows.add(commit.oid);\n }\n }\n }\n catch (err) {\n console.log(err);\n // oh well.\n }\n }\n let objects = await listObjects(fileSystem, dir, gitdir, Array.from(oids));\n let packstream = new readable_stream_1.PassThrough();\n pack(fileSystem, dir, undefined, [...objects], packstream);\n return { packstream, shallows, unshallows, acks };\n}\nasync function listObjects(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), oids) {\n let commits = new Set();\n let trees = new Set();\n let blobs = new Set();\n // We don't do the purest simplest recursion, because we can\n // avoid reading Blob objects entirely since the Tree objects\n // tell us which oids are Blobs and which are Trees. And we\n // do not need to recurse through commit parents.\n async function walk(oid) {\n let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid);\n if (type === 'commit') {\n commits.add(oid);\n let commit = GitCommit_1.default.from(object);\n let tree = commit.headers().tree;\n await walk(tree);\n }\n else if (type === 'tree') {\n trees.add(oid);\n let tree = GitTree_1.default.from(object);\n for (let entry of tree) {\n if (entry.type === 'blob') {\n blobs.add(entry.oid);\n }\n // only recurse for trees\n if (entry.type === 'tree') {\n await walk(entry.oid);\n }\n }\n }\n }\n // Let's go walking!\n for (let oid of oids) {\n await walk(oid);\n }\n return [...commits, ...trees, ...blobs];\n}\nexports.listObjects = listObjects;\nasync function pack(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), oids, outputStream) {\n let hash = sha_js_1.default('sha1');\n function write(chunk, enc = undefined) {\n if (enc) {\n outputStream.write(chunk, enc);\n }\n else {\n outputStream.write(chunk);\n }\n hash.update(chunk, enc);\n }\n function writeObject(object, stype) {\n let lastFour;\n let multibyte;\n let length;\n // Object type is encoded in bits 654\n let type = types[stype];\n if (type === undefined)\n throw new Error('Unrecognized type: ' + stype);\n // The length encoding get complicated.\n length = object.length;\n // Whether the next byte is part of the variable-length encoded number\n // is encoded in bit 7\n multibyte = length > 0b1111 ? 0b10000000 : 0b0;\n // Last four bits of length is encoded in bits 3210\n lastFour = length & 0b1111;\n // Discard those bits\n length = length >>> 4;\n // The first byte is then (1-bit multibyte?), (3-bit type), (4-bit least sig 4-bits of length)\n let byte = (multibyte | type | lastFour).toString(16);\n write(byte, 'hex');\n // Now we keep chopping away at length 7-bits at a time until its zero,\n // writing out the bytes in what amounts to little-endian order.\n while (multibyte) {\n multibyte = length > 0b01111111 ? 0b10000000 : 0b0;\n byte = multibyte | (length & 0b01111111);\n const unpaddedChunk = byte.toString(16);\n const paddedChunk = '0'.repeat(2 - unpaddedChunk.length) + unpaddedChunk;\n write(paddedChunk, 'hex');\n length = length >>> 7;\n }\n // Lastly, we can compress and write the object.\n write(Buffer.from(pako_1.default.deflate(object)));\n }\n write('PACK');\n write('00000002', 'hex');\n // Write a 4 byte (32-bit) int\n const unpaddedChunk = oids.length.toString(16);\n const paddedChunk = '0'.repeat(8 - unpaddedChunk.length) + unpaddedChunk;\n write(paddedChunk, 'hex');\n for (let oid of oids) {\n let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid);\n writeObject(object, type);\n }\n // Write SHA1 checksum\n let digest = hash.digest();\n outputStream.end(digest);\n return outputStream;\n}\nexports.pack = pack;\nexports.default = packObjects;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst path = require(\"path\");\nconst GitCommit_1 = __importDefault(require(\"./GitCommit\"));\nconst GitObjectManager_1 = __importDefault(require(\"./GitObjectManager\"));\nconst GitRefManager_1 = __importDefault(require(\"../upload-pack/GitRefManager\"));\nasync function logCommit(fileSystem, gitdir, oid, signing) {\n try {\n let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid);\n if (type !== 'commit') {\n throw (new Error('expected type to be commit'));\n }\n const commit = GitCommit_1.default.from(object);\n const result = Object.assign({ oid }, commit.parse());\n if (signing) {\n result.payload = commit.withoutSignature();\n }\n return result;\n }\n catch (err) {\n return {\n oid,\n error: err\n };\n }\n}\nexports.logCommit = logCommit;\nfunction compareAge(a, b) {\n return a.committer.timestamp - b.committer.timestamp;\n}\n/**\n * Get commit descriptions from the git history\n *\n * @link https://isomorphic-git.github.io/docs/log.html\n */\nasync function log(fileSystem, dir, gitdir = path.join(dir, '.git'), ref = 'HEAD', depth, since, // Date\nsigning = false) {\n try {\n let sinceTimestamp = since === undefined ? undefined : Math.floor(since.valueOf() / 1000);\n // TODO: In the future, we may want to have an API where we return a\n // async iterator that emits commits.\n let commits = [];\n let oid = await GitRefManager_1.default.resolve(fileSystem, gitdir, ref);\n let tips /* : Array */ = [await logCommit(fileSystem, gitdir, oid, signing)];\n while (true) {\n let commit = tips.pop();\n // Stop the loop if we encounter an error\n if (commit.error) {\n commits.push(commit);\n break;\n }\n // Stop the log if we've hit the age limit\n if (sinceTimestamp !== undefined &&\n commit.committer.timestamp <= sinceTimestamp) {\n break;\n }\n commits.push(commit);\n // Stop the loop if we have enough commits now.\n if (depth !== undefined && commits.length === depth)\n break;\n // Add the parents of this commit to the queue\n // Note: for the case of a commit with no parents, it will concat an empty array, having no net effect.\n for (const oid of commit.parent) {\n let commit = await logCommit(fileSystem, gitdir, oid, signing);\n if (!tips.map(commit => commit.oid).includes(commit.oid)) {\n tips.push(commit);\n }\n }\n // Stop the loop if there are no more commit parents\n if (tips.length === 0)\n break;\n // Process tips in order by age\n tips.sort(compareAge);\n }\n return commits;\n }\n catch (err) {\n err.caller = 'git.log';\n throw err;\n }\n}\nexports.default = log;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst shasum_1 = __importDefault(require(\"./shasum\"));\nclass GitObject {\n static hash({ type, object }) {\n let buffer = Buffer.concat([\n Buffer.from(`${type} ${object.byteLength.toString()}\\0`),\n Buffer.from(object)\n ]);\n let oid = shasum_1.default(buffer);\n return oid;\n }\n static wrap({ type, object }) {\n let buffer = Buffer.concat([\n Buffer.from(`${type} ${object.byteLength.toString()}\\0`),\n object\n ]);\n let oid = shasum_1.default(buffer);\n return {\n oid,\n buffer\n };\n }\n static unwrap({ oid, buffer }) {\n if (oid) {\n let sha = shasum_1.default(buffer);\n if (sha !== oid) {\n throw (new Error(`SHA check failed! Expected ${oid}, computed ${sha}`));\n }\n }\n let s = buffer.indexOf(32); // first space\n let i = buffer.indexOf(0); // first null value\n let type = buffer.slice(0, s).toString('utf8'); // get type of object\n let length = buffer.slice(s + 1, i).toString('utf8'); // get type of object\n let actualLength = buffer.length - (i + 1);\n // verify length\n if (parseInt(length) !== actualLength) {\n throw (new Error(`Length mismatch: expected ${length} bytes but got ${actualLength} instead.`));\n }\n return {\n type,\n object: Buffer.from(buffer.slice(i + 1))\n };\n }\n}\nexports.default = GitObject;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst sha1_1 = __importDefault(require(\"sha.js/sha1\"));\n// This is modeled after @dominictarr's \"shasum\" module,\n// but without the 'json-stable-stringify' dependency and\n// extra type-casting features.\nfunction shasum(buffer) {\n return new sha1_1.default().update(buffer).digest('hex');\n}\nexports.default = shasum;\n","module.exports = require(\"sha.js/sha1\");","\"use strict\";\n/*::\ntype TreeEntry = {\n mode: string,\n path: string,\n oid: string,\n type?: string\n}\n*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction parseBuffer(buffer) {\n let _entries = [];\n let cursor = 0;\n while (cursor < buffer.length) {\n let space = buffer.indexOf(32, cursor);\n if (space === -1) {\n throw (new Error(`GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next space character.`));\n }\n let nullchar = buffer.indexOf(0, cursor);\n if (nullchar === -1) {\n throw (new Error(`GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next null character.`));\n }\n let mode = buffer.slice(cursor, space).toString('utf8');\n if (mode === '40000')\n mode = '040000'; // makes it line up neater in printed output\n let type = mode === '040000' ? 'tree' : 'blob';\n let path = buffer.slice(space + 1, nullchar).toString('utf8');\n let oid = buffer.slice(nullchar + 1, nullchar + 21).toString('hex');\n cursor = nullchar + 21;\n _entries.push({ mode, path, oid, type });\n }\n return _entries;\n}\nfunction limitModeToAllowed(mode) {\n if (typeof mode === 'number') {\n mode = mode.toString(8);\n }\n // tree\n if (mode.match(/^0?4.*/))\n return '40000'; // Directory\n if (mode.match(/^1006.*/))\n return '100644'; // Regular non-executable file\n if (mode.match(/^1007.*/))\n return '100755'; // Regular executable file\n if (mode.match(/^120.*/))\n return '120000'; // Symbolic link\n if (mode.match(/^160.*/))\n return '160000'; // Commit (git submodule reference)\n throw (new Error(`Could not understand file mode: ${mode}`));\n}\nfunction nudgeIntoShape(entry) {\n if (!entry.oid && entry.sha) {\n entry.oid = entry.sha; // Github\n }\n entry.mode = limitModeToAllowed(entry.mode); // index\n if (!entry.type) {\n entry.type = 'blob'; // index\n }\n return entry;\n}\nclass GitTree {\n constructor(entries) {\n if (Buffer.isBuffer(entries)) {\n this._entries = parseBuffer(entries);\n }\n else if (Array.isArray(entries)) {\n this._entries = entries.map(nudgeIntoShape);\n }\n else {\n throw (new Error('invalid type passed to GitTree constructor'));\n }\n }\n static from(tree) {\n return new GitTree(tree);\n }\n render() {\n return this._entries\n .map(entry => `${entry.mode} ${entry.type} ${entry.oid} ${entry.path}`)\n .join('\\n');\n }\n toObject() {\n return Buffer.concat(this._entries.map((entry) => {\n let mode = Buffer.from(entry.mode.replace(/^0/, ''));\n let space = Buffer.from(' ');\n let path = Buffer.from(entry.path);\n // let path = Buffer.from(entry.path, { encoding: 'utf8' })\n let nullchar = Buffer.from([0]);\n let oid = Buffer.from(entry.oid.match(/../g).map(n => parseInt(n, 16)));\n return Buffer.concat([mode, space, path, nullchar, oid]);\n }));\n }\n entries() {\n return this._entries;\n }\n *[Symbol.iterator]() {\n for (let entry of this._entries) {\n yield entry;\n }\n }\n}\nexports.default = GitTree;\n","module.exports = require(\"sha.js\");","module.exports = require(\"../../proto/js/Peer\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Returns a 5 character long random string of lower case letters\n */\nfunction randomString() {\n return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);\n}\nexports.randomString = randomString;\n/**\n * Inverts the provided promise\n * @param p Promise to invert\n */\nfunction invertPromise(p) {\n return new Promise((res, rej) => p.then(rej, res));\n}\n/**\n * Gets the first promise fulfiled\n * @param ps List of promises\n */\nfunction firstPromiseFulfilled(ps) {\n return invertPromise(Promise.all(ps.map(invertPromise)));\n}\nexports.firstPromiseFulfilled = firstPromiseFulfilled;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar _a, _b;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dgram_1 = __importDefault(require(\"dgram\"));\nconst crypto_1 = __importDefault(require(\"crypto\"));\nconst PeerInfo_1 = __importDefault(require(\"./PeerInfo\"));\nconst events_1 = require(\"events\");\nconst Peer_js_1 = require(\"../../../proto/js/Peer.js\");\nconst { HandshakeMessage, PeerInfoMessage } = Peer_js_1.peer;\n// This module is based heavily on libp2p's mDNS module:\n// https://github.com/libp2p/js-libp2p-mdns\n// It is supposed to discover peers on the local network\n// This module was also generated with the help of:\n// https://nrempel.com/using-udp-multicast-with-node-js/\n//\n// \"\"\"\n// In computer networking, the multicast DNS (mDNS) protocol\n// resolves hostnames to IP addresses within small networks\n// that do not include a local name server\n// \"\"\"\nconst UDP_MULTICAST_PORT = parseInt((_a = process.env.UDP_MULTICAST_PORT) !== null && _a !== void 0 ? _a : '5353');\nconst UDP_MULTICAST_ADDR = (_b = process.env.UDP_MULTICAST_ADDR) !== null && _b !== void 0 ? _b : \"224.0.0.251\";\nclass MulticastBroadcaster extends events_1.EventEmitter {\n constructor(addPeer, localPeerInfo, keyManager) {\n super();\n this.peerPubKeyMessages = new Map();\n this.addPeer = addPeer;\n this.localPeerInfo = localPeerInfo;\n this.keyManager = keyManager;\n this.interval = (1e3);\n this.queryInterval = null;\n // Create socket\n this.socket = dgram_1.default.createSocket({ type: \"udp4\", reuseAddr: true });\n this.socket.bind(UDP_MULTICAST_PORT);\n // Set up listener\n this.socket.on(\"listening\", (() => {\n this.socket.addMembership(UDP_MULTICAST_ADDR);\n const address = this.socket.address();\n }).bind(this));\n // Handle messages\n this.socket.on(\"message\", this.handleHandshakeMessages.bind(this));\n // Start the query process\n this.queryInterval = this.queryLAN();\n }\n /**\n * Request a peer contact for the multicast peer discovery to check for\n * @param publicKey Public key of the desired peer\n */\n async requestPeerContact(publicKey) {\n const pubKeyBuf = Buffer.from(publicKey);\n const randomMessage = crypto_1.default.randomBytes(16);\n // Encrypt message\n const encryptedPeerPubKey = await this.keyManager.encryptData(pubKeyBuf, pubKeyBuf);\n const encryptedRandomMessage = await this.keyManager.encryptData(randomMessage, pubKeyBuf);\n const encryptedLocalPubKey = await this.keyManager.encryptData(Buffer.from(this.keyManager.getPublicKey()), pubKeyBuf);\n // Add to peer messages to be sent over multicast\n this.peerPubKeyMessages.set(publicKey, {\n encryptedLocalPubKey: Buffer.from(encryptedLocalPubKey),\n encryptedPeerPubKey: Buffer.from(encryptedPeerPubKey),\n rawRandomMessage: randomMessage,\n encryptedRandomMessage: Buffer.from(encryptedRandomMessage)\n });\n }\n // ==== Helper methods ==== //\n queryLAN() {\n const query = () => {\n for (const pubKey of this.peerPubKeyMessages.keys()) {\n const peerMessage = this.peerPubKeyMessages.get(pubKey);\n if (peerMessage) {\n const handshakeMessage = HandshakeMessage.encode({\n targetPubKey: peerMessage.encryptedPeerPubKey,\n requestingPubKey: peerMessage.encryptedLocalPubKey,\n message: peerMessage.encryptedRandomMessage\n }).finish();\n this.socket.send(handshakeMessage, 0, handshakeMessage.length, UDP_MULTICAST_PORT, UDP_MULTICAST_ADDR);\n }\n }\n };\n // Immediately start a query, then do it every interval.\n query();\n return setInterval(query, this.interval);\n }\n async handleHandshakeMessages(request, rinfo) {\n var _a, _b;\n try {\n const { message, requestingPubKey, responsePeerInfo, targetPubKey } = HandshakeMessage.decode(request);\n // Try to decrypt message and pubKey\n const decryptedMessage = await this.keyManager.decryptData(Buffer.from(message));\n const decryptedTargetPubKey = await this.keyManager.decryptData(Buffer.from(targetPubKey));\n const decryptedRequestingPubKey = await this.keyManager.decryptData(Buffer.from(requestingPubKey));\n const myPubKey = this.keyManager.getPublicKey();\n if (decryptedRequestingPubKey.toString() == myPubKey) { // Response\n // Make sure decrypted bytes equal raw bytes in memory\n const originalMessage = (_a = this.peerPubKeyMessages.get(decryptedTargetPubKey.toString())) === null || _a === void 0 ? void 0 : _a.rawRandomMessage;\n if (decryptedMessage.toString() == (originalMessage === null || originalMessage === void 0 ? void 0 : originalMessage.toString())) { // Validated!\n // Add peer info to peerStore\n const { addresses, connectedAddr, pubKey } = PeerInfoMessage.decode(responsePeerInfo);\n const newPeerInfo = new PeerInfo_1.default(pubKey, addresses, connectedAddr);\n if (newPeerInfo) {\n this.addPeer(newPeerInfo);\n // Remove peerId from requested messages\n const pubKey = newPeerInfo.publicKey;\n this.peerPubKeyMessages.delete(pubKey);\n console.log(`New peer added to the store`);\n this.emit('found', newPeerInfo);\n }\n else {\n this.emit('error', \"I got a validated response. But no peerInfo\");\n }\n }\n }\n else { // Requests on target node\n // Try decrypting message\n // Re-encrypt the data and send it on its way\n const encryptedTargetPubKey = await this.keyManager.encryptData(Buffer.from(myPubKey), decryptedRequestingPubKey);\n const encryptedMessage = await this.keyManager.encryptData(decryptedMessage, decryptedRequestingPubKey);\n const encryptedPubKey = await this.keyManager.encryptData(decryptedRequestingPubKey, decryptedRequestingPubKey);\n const encodedLocalPeerInfo = PeerInfoMessage.encode({\n addresses: this.localPeerInfo.AdressStringList,\n connectedAddr: (_b = this.localPeerInfo.connectedAddr) === null || _b === void 0 ? void 0 : _b.toString(),\n pubKey: this.localPeerInfo.publicKey\n }).finish();\n const handshakeMessage = HandshakeMessage.encode({\n targetPubKey: Buffer.from(encryptedTargetPubKey),\n requestingPubKey: Buffer.from(encryptedPubKey),\n message: Buffer.from(encryptedMessage),\n responsePeerInfo: encodedLocalPeerInfo\n }).finish();\n this.socket.send(handshakeMessage, 0, handshakeMessage.length, UDP_MULTICAST_PORT, UDP_MULTICAST_ADDR);\n }\n }\n catch (err) { // Couldn't decode message\n // We don't want the multicast discovery to error on every message it coudln't decode!\n }\n }\n}\nexports.default = MulticastBroadcaster;\n","module.exports = require(\"dgram\");","module.exports = require(\"events\");","module.exports = require(\"../../proto/js/Peer.js\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst isomorphic_git_1 = __importDefault(require(\"isomorphic-git\"));\nconst Vault_1 = __importDefault(require(\"../vaults/Vault\"));\nconst encryptedfs_1 = require(\"encryptedfs\");\nclass VaultManager {\n constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager) {\n this.polykeyPath = polykeyPath;\n this.fileSystem = fileSystem;\n this.keyManager = keyManager;\n this.metadataPath = path_1.default.join(polykeyPath, '.vaultKeys');\n // Make polykeyPath if it doesn't exist\n this.fileSystem.mkdirSync(this.polykeyPath, { recursive: true });\n // Initialize stateful variables\n this.vaults = new Map();\n this.vaultKeys = new Map();\n // Read in vault keys\n this.loadMetadata();\n // Initialize vaults in memory\n for (const [vaultName, vaultKey] of this.vaultKeys.entries()) {\n const path = path_1.default.join(this.polykeyPath, vaultName);\n if (this.fileSystem.existsSync(path)) {\n const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath);\n this.vaults.set(vaultName, vault);\n }\n }\n }\n /**\n * Get a vault from the vault manager\n * @param vaultName Name of desired vault\n */\n getVault(vaultName) {\n if (this.vaults.has(vaultName)) {\n const vault = this.vaults.get(vaultName);\n return vault;\n }\n else if (this.vaultKeys.has(vaultName)) {\n // vault not in map, create new instance\n this.validateVault(vaultName);\n const vaultKey = this.vaultKeys.get(vaultName);\n const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath);\n this.vaults.set(vaultName, vault);\n return vault;\n }\n else {\n throw new Error('Vault does not exist in memory');\n }\n }\n /**\n * Get a vault from the vault manager\n * @param vaultName Unique name of new vault\n * @param key Optional key to use for the vault encryption, otherwise it is generated\n */\n async createVault(vaultName, key) {\n if (this.vaultExists(vaultName)) {\n throw Error('Vault already exists!');\n }\n try {\n const path = path_1.default.join(this.polykeyPath, vaultName);\n // Directory not present, create one\n this.fileSystem.mkdirSync(path, { recursive: true });\n // Create key if not provided\n let vaultKey;\n if (!key) {\n // Generate new key\n vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey());\n }\n else {\n // Assign key if it is provided\n vaultKey = key;\n }\n this.vaultKeys.set(vaultName, vaultKey);\n this.writeMetadata();\n const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath);\n await vault.initRepository();\n this.vaults.set(vaultName, vault);\n return this.getVault(vaultName);\n }\n catch (err) {\n // Delete vault dir and garbage collect\n this.destroyVault(vaultName);\n throw err;\n }\n }\n /**\n * Get a vault from the vault manager\n * @param vaultName Name of vault to be cloned\n * @param address Address of polykey node that owns vault to be cloned\n * @param getSocket Function to get an active connection to provided address\n */\n async cloneVault(vaultName, gitClient) {\n // Confirm it doesn't exist locally already\n if (this.vaultExists(vaultName)) {\n throw new Error('Vault name already exists locally, try pulling instead');\n }\n const vaultUrl = `http://0.0.0.0/${vaultName}`;\n // First check if it exists on remote\n const info = await isomorphic_git_1.default.getRemoteInfo({\n http: gitClient,\n url: vaultUrl\n });\n if (!info.refs) {\n throw new Error(`Peer does not have vault: '${vaultName}'`);\n }\n // Create new efs first\n // Generate new key\n const vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey());\n // Set filesystem\n const vfsInstance = new (require('virtualfs')).VirtualFS;\n const newEfs = new encryptedfs_1.EncryptedFS(vaultKey, vfsInstance, vfsInstance, this.fileSystem, process);\n // Clone vault from address\n await isomorphic_git_1.default.clone({\n fs: { promises: newEfs.promises },\n http: gitClient,\n dir: path_1.default.join(this.polykeyPath, vaultName),\n url: vaultUrl,\n ref: 'master',\n singleBranch: true\n });\n // Finally return the vault\n const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath);\n this.vaults.set(vaultName, vault);\n return vault;\n }\n /**\n * Determines whether the vault exists\n * @param vaultName Name of desired vault\n */\n vaultExists(vaultName) {\n const path = path_1.default.join(this.polykeyPath, vaultName);\n const vaultExists = this.fileSystem.existsSync(path);\n return vaultExists;\n }\n /**\n * [WARNING] Destroys a certain vault and all its secrets\n * @param vaultName Name of vault to be destroyed\n */\n destroyVault(vaultName) {\n // this is convenience function for removing all tags\n // and triggering garbage collection\n // destruction is a better word as we should ensure all traces is removed\n const path = path_1.default.join(this.polykeyPath, vaultName);\n // Remove directory on file system\n if (this.fileSystem.existsSync(path)) {\n this.fileSystem.rmdirSync(path, { recursive: true });\n }\n // Remove from maps\n this.vaults.delete(vaultName);\n this.vaultKeys.delete(vaultName);\n // Write to metadata file\n this.writeMetadata();\n const vaultPathExists = this.fileSystem.existsSync(path);\n if (vaultPathExists) {\n throw new Error('Vault folder could not be destroyed!');\n }\n }\n /**\n * List the names of all vaults in memory\n */\n listVaults() {\n return Array.from(this.vaults.keys());\n }\n /* ============ HELPERS =============== */\n validateVault(vaultName) {\n if (!this.vaults.has(vaultName)) {\n throw Error('Vault does not exist in memory');\n }\n if (!this.vaultKeys.has(vaultName)) {\n throw Error('Vault key does not exist in memory');\n }\n const vaultPath = path_1.default.join(this.polykeyPath, vaultName);\n if (!this.fileSystem.existsSync(vaultPath)) {\n throw Error('Vault directory does not exist');\n }\n }\n async writeMetadata() {\n const metadata = JSON.stringify([...this.vaultKeys]);\n const encryptedMetadata = await this.keyManager.encryptData(Buffer.from(metadata));\n await this.fileSystem.promises.writeFile(this.metadataPath, encryptedMetadata);\n }\n async loadMetadata() {\n // Check if file exists\n if (this.fileSystem.existsSync(this.metadataPath) && this.keyManager.identityLoaded) {\n const encryptedMetadata = this.fileSystem.readFileSync(this.metadataPath);\n const metadata = (await this.keyManager.decryptData(encryptedMetadata)).toString();\n for (const [key, value] of new Map(JSON.parse(metadata))) {\n this.vaultKeys[key] = Buffer.from(value);\n }\n }\n }\n}\nexports.default = VaultManager;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = __importDefault(require(\"fs\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst isomorphic_git_1 = __importDefault(require(\"isomorphic-git\"));\nconst encryptedfs_1 = require(\"encryptedfs\");\nclass Vault {\n constructor(name, symKey, baseDir) {\n // how do we create pub/priv key pair?\n // do we use the same gpg pub/priv keypair\n this.key = symKey;\n this.keyLen = symKey.length;\n // Set filesystem\n const vfsInstance = new (require('virtualfs')).VirtualFS;\n this.efs = new encryptedfs_1.EncryptedFS(this.key, vfsInstance, vfsInstance, fs_1.default, process);\n this.name = name;\n this.vaultPath = path_1.default.join(baseDir, name);\n // make the vault directory\n this.efs.mkdirSync(this.vaultPath, { recursive: true });\n this.secrets = new Map();\n this.loadSecrets();\n // Load metadata\n this.metadataPath = path_1.default.join(this.vaultPath, '.vault', 'metadata');\n this.loadMetadata();\n }\n /**\n * Returns the Encrypted File System used for vault operations\n */\n get EncryptedFS() {\n return this.efs;\n }\n /**\n * Determines whether a secret exists in the vault\n * @param secretName Name of desired secret\n */\n secretExists(secretName) {\n const secretPath = path_1.default.join(this.vaultPath, secretName);\n return this.secrets.has(secretName) && this.efs.existsSync(secretPath);\n }\n /**\n * Adds a secret to the vault\n * @param secretName Name of new secret\n * @param secret Content of new secret\n */\n async addSecret(secretName, secret) {\n // Check if secret already exists\n if (this.secrets.has(secretName)) {\n throw new Error('Secret already exists, try updating it instead.');\n }\n const writePath = path_1.default.join(this.vaultPath, secretName);\n // Write secret\n await this.efs.promises.writeFile(writePath, secret, {});\n // Update secrets map\n this.secrets.set(secretName, secret);\n // Auto commit message\n await this.commitChanges(`Add secret: ${secretName}`, secretName, 'added');\n }\n /**\n * Updates a secret in the vault\n * @param secretName Name of secret to be updated\n * @param secret Content of updated secret\n */\n async updateSecret(secretName, secret) {\n // Check if secret already exists\n if (!this.secrets.has(secretName)) {\n throw new Error('Secret does not exist, try adding it instead.');\n }\n const writePath = path_1.default.join(this.vaultPath, secretName);\n // Write secret\n await this.efs.promises.writeFile(writePath, secret, {});\n // Update secrets map\n this.secrets.set(secretName, secret);\n // Auto commit message\n await this.commitChanges(`Update secret: ${secretName}`, secretName, 'modified');\n }\n /**\n * Get a secret from the vault\n * @param secretName Name of secret to be retrieved\n */\n getSecret(secretName) {\n if (this.secrets.has(secretName)) {\n const secret = this.secrets.get(secretName);\n if (secret) {\n return secret;\n }\n else {\n const secretPath = path_1.default.join(this.vaultPath, secretName);\n // TODO: this should be async\n const secretBuf = this.efs.readFileSync(secretPath, {});\n this.secrets.set(secretName, secretBuf);\n return secretBuf;\n }\n }\n throw Error('Secret: ' + secretName + ' does not exist');\n }\n /**\n * [WARNING] Removes a secret from the vault\n * @param secretName Name of secret to be removed\n */\n async removeSecret(secretName) {\n if (this.secrets.has(secretName)) {\n const successful = this.secrets.delete(secretName);\n // Remove from fs\n await this.efs.promises.unlink(path_1.default.join(this.vaultPath, secretName));\n // Auto commit message\n await this.commitChanges(`Remove secret: ${secretName}`, secretName, 'removed');\n if (successful) {\n return;\n }\n throw Error('Secret: ' + secretName + ' was not removed');\n }\n throw Error('Secret: ' + secretName + ' does not exist');\n }\n /**\n * Lists all the secrets currently in the vault\n */\n listSecrets() {\n let secrets = Array.from(this.secrets.keys());\n return secrets;\n }\n tagVault() {\n }\n untagVault() {\n }\n /////////////\n // Sharing //\n /////////////\n /**\n * Allows a particular public key to access the vault\n * @param publicKey Public key to share with\n */\n shareVault(publicKey) {\n if (this.sharedPubKeys.has(name)) {\n throw new Error('Vault is already shared with given public key');\n }\n this.sharedPubKeys.add(publicKey);\n // Write metadata\n this.writeMetadata();\n }\n /**\n * Removes access to the vault for a particular public key\n * @param publicKey Public key to unshare with\n */\n unshareVault(publicKey) {\n if (!this.sharedPubKeys.has(publicKey)) {\n throw new Error('Vault is not shared with given public key');\n }\n this.sharedPubKeys.delete(publicKey);\n // Write metadata\n this.writeMetadata();\n }\n /**\n * Determines if a particular public key can access the vault\n * @param publicKey Public key to check\n */\n peerCanAccess(publicKey) {\n // return this.sharedPubKeys.has(publicKey)\n return true;\n }\n /**\n * Pulls the vault from a specific address\n * @param address Address of polykey node that owns vault to be pulled\n * @param getSocket Function to get an active connection to provided address\n */\n async pullVault(gitClient) {\n // Strangely enough this is needed for pulls along with ref set to 'HEAD'\n // In isogit's documentation, this is just to get the currentBranch name\n // But it solves a bug whereby if not used, git.pull complains that it can't\n // find the master branch or HEAD\n await isomorphic_git_1.default.currentBranch({\n fs: { promises: this.efs.promises },\n dir: this.vaultPath,\n fullname: true\n });\n // First pull\n await isomorphic_git_1.default.pull({\n fs: { promises: this.efs.promises },\n http: gitClient,\n dir: this.vaultPath,\n url: \"http://\" + '0.0.0.0:0' + '/' + this.name,\n ref: 'HEAD',\n singleBranch: true,\n author: {\n name: this.name\n }\n });\n // Load any new secrets\n this.loadSecrets();\n }\n /**\n * Initializes the git repository for new vaults\n */\n async initRepository() {\n const fileSystem = this.efs;\n await isomorphic_git_1.default.init({\n fs: fileSystem,\n dir: this.vaultPath\n });\n // Initial commit\n await isomorphic_git_1.default.commit({\n fs: fileSystem,\n dir: this.vaultPath,\n author: {\n name: this.name\n },\n message: \"init commit\"\n });\n // Write packed-refs file because isomorphic git goes searching for it\n // and apparently its not autogenerated\n this.efs.writeFileSync(path_1.default.join(this.vaultPath, '.git', 'packed-refs'), '# pack-refs with: peeled fully-peeled sorted');\n }\n // ============== Helper methods ============== //\n writeMetadata() {\n // mkdir first\n this.efs.mkdirSync(path_1.default.dirname(this.metadataPath), { recursive: true });\n // Create and write metadata\n const metadata = {\n sharedPubKeys: Array.from(this.sharedPubKeys.keys())\n };\n this.efs.writeFileSync(this.metadataPath, JSON.stringify(metadata));\n }\n loadMetadata() {\n if (this.efs.existsSync(this.metadataPath)) {\n const fileContents = this.efs.readFileSync(this.metadataPath).toString();\n const metadata = JSON.parse(fileContents);\n this.sharedPubKeys = new Set(metadata.sharedPubKeys);\n }\n else {\n // Need to create it\n this.sharedPubKeys = new Set();\n this.writeMetadata();\n }\n }\n async commitChanges(message, secretName, action) {\n if (action == 'removed') {\n await isomorphic_git_1.default.remove({\n fs: this.efs,\n dir: this.vaultPath,\n filepath: secretName\n });\n }\n else {\n await isomorphic_git_1.default.add({\n fs: this.efs,\n dir: this.vaultPath,\n filepath: secretName\n });\n }\n return await isomorphic_git_1.default.commit({\n fs: this.efs,\n dir: this.vaultPath,\n author: {\n name: this.name\n },\n message: message\n });\n }\n loadSecrets() {\n const secrets = fs_1.default.readdirSync(this.vaultPath, undefined);\n for (const secret of secrets.filter((s) => s[0] != '.')) {\n this.secrets.set(secret, null);\n }\n }\n}\nexports.default = Vault;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst fs_1 = __importDefault(require(\"fs\"));\nconst net_1 = __importDefault(require(\"net\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst process_1 = __importDefault(require(\"process\"));\nconst child_process_1 = require(\"child_process\");\nconst Polykey_1 = __importStar(require(\"../Polykey\"));\nconst configstore_1 = __importDefault(require(\"configstore\"));\nconst PolykeyClient_1 = __importDefault(require(\"./PolykeyClient\"));\nconst Agent_1 = require(\"../../../proto/js/Agent\");\nconst readable_stream_1 = require(\"readable-stream\");\nconst { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage } = Agent_1.agent;\nclass PolykeyAgent {\n constructor() {\n this.persistentStore = new configstore_1.default('polykey');\n // For storing the state of each polykey node\n // Keys are the paths to the polykey node, e.g. '~/.polykey'\n this.polykeyMap = new Map();\n this.socketPath = PolykeyAgent.SocketPath;\n // Make sure the socket file doesn't already exist (agent is already running)\n if (fs_1.default.existsSync(this.socketPath)) {\n fs_1.default.unlinkSync(this.socketPath);\n }\n // Make the socket path if it doesn't exist\n if (!fs_1.default.existsSync(path_1.default.dirname(this.socketPath))) {\n fs_1.default.promises.mkdir(path_1.default.dirname(this.socketPath));\n }\n // Load polykeys\n const nodePaths = this.persistentStore.get('nodePaths');\n if (nodePaths) {\n for (const path of nodePaths) {\n if (fs_1.default.existsSync(path)) {\n this.polykeyMap.set(path, new Polykey_1.default(path, fs_1.default));\n }\n else {\n this.removeFromNodePaths(path);\n }\n }\n }\n else {\n this.persistentStore.set('nodePaths', []);\n }\n // Start the server\n this.server = net_1.default.createServer().listen(this.socketPath);\n this.server.on('connection', (socket) => {\n this.handleClientCommunication(socket);\n });\n }\n get AllNodePaths() {\n return Array.from(this.polykeyMap.keys()).filter((nodePath) => {\n try {\n this.getPolykey(nodePath);\n return true;\n }\n catch (_a) {\n return false;\n }\n });\n }\n get UnlockedNodePaths() {\n return this.AllNodePaths.filter((nodePath) => {\n try {\n return this.getPolykey(nodePath).keyManager.identityLoaded;\n }\n catch (_a) {\n return false;\n }\n });\n }\n stop() {\n this.server.close();\n }\n addToNodePaths(nodePath, pk) {\n this.polykeyMap.set(nodePath, pk);\n const nodePathSet = new Set(this.persistentStore.get('nodePaths'));\n nodePathSet.add(nodePath);\n this.persistentStore.set('nodePaths', Array.from(nodePathSet.values()));\n }\n removeFromNodePaths(nodePath) {\n this.polykeyMap.delete(nodePath);\n const nodePathSet = new Set(this.persistentStore.get('nodePaths'));\n nodePathSet.delete(nodePath);\n this.persistentStore.set('nodePaths', Array.from(nodePathSet.values()));\n }\n handleClientCommunication(socket) {\n socket.on('data', async (encodedMessage) => {\n var _a;\n try {\n const { type, nodePath, subMessage } = AgentMessage.decode(encodedMessage);\n let response = undefined;\n switch (type) {\n case Type.STATUS:\n response = Buffer.from('online');\n break;\n case Type.STOP_AGENT:\n this.stop();\n process_1.default.exit();\n case Type.REGISTER_NODE:\n response = await this.registerNode(nodePath, subMessage);\n break;\n case Type.NEW_NODE:\n response = await this.newNode(nodePath, subMessage);\n break;\n case Type.LIST_NODES:\n response = this.listNodes(subMessage);\n break;\n case Type.DERIVE_KEY:\n response = await this.deriveKey(nodePath, subMessage);\n break;\n case Type.SIGN_FILE:\n response = await this.signFile(nodePath, subMessage);\n break;\n case Type.VERIFY_FILE:\n response = await this.verifyFile(nodePath, subMessage);\n break;\n case Type.LIST_VAULTS:\n response = await this.listVaults(nodePath);\n break;\n case Type.NEW_VAULT:\n response = await this.newVault(nodePath, subMessage);\n break;\n case Type.DESTROY_VAULT:\n response = await this.destroyVault(nodePath, subMessage);\n break;\n case Type.LIST_SECRETS:\n response = await this.listSecrets(nodePath, subMessage);\n break;\n case Type.CREATE_SECRET:\n response = await this.createSecret(nodePath, subMessage);\n break;\n case Type.DESTROY_SECRET:\n response = await this.destroySecret(nodePath, subMessage);\n break;\n case Type.GET_SECRET:\n response = await this.getSecret(nodePath, subMessage);\n break;\n default:\n throw Error(`message type not supported: ${type}`);\n }\n if (response) {\n const encodedResponse = AgentMessage.encode({ type: type, isResponse: true, nodePath: nodePath, subMessage: response }).finish();\n socket.write(encodedResponse);\n }\n else {\n throw Error('something went wrong');\n }\n }\n catch (err) {\n const errorResponse = AgentMessage.encode({ type: Type.ERROR, isResponse: true, nodePath: undefined, subMessage: ErrorMessage.encode({ error: (_a = err.message) !== null && _a !== void 0 ? _a : err }).finish() }).finish();\n socket.write(errorResponse);\n }\n // Close connection\n socket.end();\n });\n }\n // Register an existing polykey agent\n async registerNode(nodePath, request) {\n const { passphrase } = RegisterNodeRequestMessage.decode(request);\n let pk = this.polykeyMap.get(nodePath);\n if (pk) {\n if (pk.keyManager.identityLoaded) {\n throw Error(`node path is already loaded and unlocked: '${nodePath}'`);\n }\n await pk.keyManager.unlockIdentity(passphrase);\n }\n else {\n const km = new Polykey_1.KeyManager(nodePath, fs_1.default);\n await km.unlockIdentity(passphrase);\n // Create polykey class\n pk = new Polykey_1.default(nodePath, fs_1.default, km);\n }\n // Set polykey class\n this.addToNodePaths(nodePath, pk);\n // Encode and send response\n const response = NewNodeResponseMessage.encode({ successful: pk.keyManager.identityLoaded && this.polykeyMap.has(nodePath) }).finish();\n return response;\n }\n // Create a new polykey agent\n async newNode(nodePath, request) {\n // Throw if path already exists\n if (this.polykeyMap.has(nodePath) && fs_1.default.existsSync(nodePath)) {\n throw Error(`node path '${nodePath}' is already loaded`);\n }\n else if (fs_1.default.existsSync(nodePath)) {\n throw Error(`node path already exists: '${nodePath}'`);\n }\n const { name, email, passphrase, nbits } = NewNodeRequestMessage.decode(request);\n const km = new Polykey_1.KeyManager(nodePath, fs_1.default);\n await km.generateKeyPair(name, email, passphrase, (nbits == 0) ? undefined : nbits, true, (info) => {\n // socket.write(JSON.stringify(info))\n });\n // Create and set polykey class\n const pk = new Polykey_1.default(nodePath, fs_1.default, km);\n this.addToNodePaths(nodePath, pk);\n // Encode and send response\n const response = NewNodeResponseMessage.encode({ successful: km.identityLoaded && this.polykeyMap.has(nodePath) }).finish();\n return response;\n }\n // Create a new polykey agent\n listNodes(request) {\n const { unlockedOnly } = ListNodesRequestMessage.decode(request);\n if (unlockedOnly) {\n return ListNodesResponseMessage.encode({ nodes: this.UnlockedNodePaths }).finish();\n }\n else {\n return ListNodesResponseMessage.encode({ nodes: this.AllNodePaths }).finish();\n }\n }\n getPolykey(nodePath) {\n var _a;\n if (this.polykeyMap.has(nodePath)) {\n return this.polykeyMap.get(nodePath);\n }\n else if (fs_1.default.existsSync(nodePath)) {\n throw Error(`polykey node has not been loaded yet: '${nodePath}'`);\n }\n else {\n const nodePathList = new Set((_a = this.persistentStore.get('nodePaths')) !== null && _a !== void 0 ? _a : []);\n nodePathList.delete(nodePath);\n this.persistentStore.set('nodePaths', nodePathList);\n throw Error(`node path does not exist: '${nodePath}'`);\n }\n }\n /////////////////////////\n // KeyManager commands //\n /////////////////////////\n async deriveKey(nodePath, request) {\n const { keyName, passphrase } = DeriveKeyRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n await pk.keyManager.generateKey(keyName, passphrase);\n return DeriveKeyResponseMessage.encode({ successful: true }).finish();\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async signFile(nodePath, request) {\n const { filePath, privateKeyPath, passphrase } = SignFileRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const signaturePath = await pk.keyManager.signFile(filePath, privateKeyPath, passphrase);\n return SignFileResponseMessage.encode({ signaturePath }).finish();\n }\n async verifyFile(nodePath, request) {\n const { filePath, signaturePath } = VerifyFileRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const verified = await pk.keyManager.verifyFile(filePath, signaturePath);\n return VerifyFileResponseMessage.encode({ verified }).finish();\n }\n //////////////////////\n // Vault Operations //\n //////////////////////\n async listVaults(nodePath) {\n const pk = this.getPolykey(nodePath);\n const vaultNames = pk.vaultManager.listVaults();\n return ListVaultsResponseMessage.encode({ vaultNames }).finish();\n }\n async newVault(nodePath, request) {\n const { vaultName } = NewVaultRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n await pk.vaultManager.createVault(vaultName);\n return NewVaultResponseMessage.encode({ successful: true }).finish();\n }\n async destroyVault(nodePath, request) {\n const { vaultName } = DestroyVaultRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n pk.vaultManager.destroyVault(vaultName);\n return DestroyVaultResponseMessage.encode({ successful: true }).finish();\n }\n ///////////////////////\n // Secret Operations //\n ///////////////////////\n async listSecrets(nodePath, request) {\n const { vaultName } = ListSecretsRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const vault = pk.vaultManager.getVault(vaultName);\n const secretNames = vault.listSecrets();\n return ListSecretsResponseMessage.encode({ secretNames }).finish();\n }\n async createSecret(nodePath, request) {\n const { vaultName, secretName, secretPath } = CreateSecretRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const vault = pk.vaultManager.getVault(vaultName);\n const secret = await fs_1.default.promises.readFile(secretPath);\n await vault.addSecret(secretName, secret);\n return CreateSecretResponseMessage.encode({ successful: true }).finish();\n }\n async destroySecret(nodePath, request) {\n const { vaultName, secretName } = DestroySecretRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const vault = pk.vaultManager.getVault(vaultName);\n await vault.removeSecret(secretName);\n return DestroySecretResponseMessage.encode({ successful: true }).finish();\n }\n async getSecret(nodePath, request) {\n const { vaultName, secretName } = GetSecretRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const vault = pk.vaultManager.getVault(vaultName);\n const secret = Buffer.from(vault.getSecret(secretName));\n return GetSecretResponseMessage.encode({ secret: secret }).finish();\n }\n ///////////////////////\n // Client Connection //\n ///////////////////////\n static connectToAgent(getStream) {\n const defaultStream = () => {\n const passThrough = new readable_stream_1.PassThrough();\n const socket = net_1.default.createConnection(PolykeyAgent.SocketPath);\n socket.pipe(passThrough);\n passThrough.pipe(socket);\n return passThrough;\n };\n const client = new PolykeyClient_1.default(getStream !== null && getStream !== void 0 ? getStream : defaultStream);\n // if (checkStatus) {\n // const status = await client.getAgentStatus()\n // if (status != 'online') {\n // throw Error(`agent status is: ${status}, restart with 'pk agent start'`)\n // }\n // }\n return client;\n }\n // ===== Helper methods===== //\n static get SocketPath() {\n const platform = os_1.default.platform();\n const userInfo = os_1.default.userInfo();\n if (platform == 'win32') {\n return path_1.default.join('\\\\\\\\?\\\\pipe', process_1.default.cwd(), 'polykey-agent');\n }\n else {\n return `/run/user/${userInfo.uid}/polykey/S.polykey-agent`;\n }\n }\n static get LogPath() {\n const platform = os_1.default.platform();\n const userInfo = os_1.default.userInfo();\n if (platform == 'win32') {\n return path_1.default.join(os_1.default.tmpdir(), 'polykey', 'log');\n }\n else {\n return `/run/user/${userInfo.uid}/polykey/log`;\n }\n }\n static async startAgent(daemon = false) {\n return new Promise((resolve, reject) => {\n try {\n let options = {\n uid: process_1.default.getuid(),\n detached: daemon\n };\n if (daemon) {\n fs_1.default.rmdirSync(PolykeyAgent.LogPath, { recursive: true });\n fs_1.default.mkdirSync(PolykeyAgent.LogPath, { recursive: true });\n options.stdio = [\n 'ipc',\n fs_1.default.openSync(path_1.default.join(PolykeyAgent.LogPath, 'output.log'), 'a'),\n fs_1.default.openSync(path_1.default.join(PolykeyAgent.LogPath, 'error.log'), 'a'), ,\n ];\n }\n const agentProcess = child_process_1.fork(PolykeyAgent.DAEMON_SCRIPT_PATH, undefined, options);\n const pid = agentProcess.pid;\n agentProcess.unref();\n resolve(pid);\n }\n catch (err) {\n reject(err);\n }\n });\n }\n}\n//////////////////////\n// Agent Operations //\n//////////////////////\nPolykeyAgent.DAEMON_SCRIPT_PATH = path_1.default.join(__dirname, 'internal', 'daemon-script.js');\nexports.default = PolykeyAgent;\n","module.exports = require(\"net\");","module.exports = require(\"process\");","module.exports = require(\"child_process\");","module.exports = require(\"configstore\");"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://polykey/webpack/universalModuleDefinition","webpack://polykey/webpack/bootstrap","webpack://polykey/external \"path\"","webpack://polykey/external \"os\"","webpack://polykey/external \"fs\"","webpack://polykey/external \"readable-stream\"","webpack://polykey/./src/lib/Polykey.ts","webpack://polykey/external \"crypto\"","webpack://polykey/external \"@grpc/grpc-js\"","webpack://polykey/external \"../../proto/compiled/Git_grpc_pb\"","webpack://polykey/external \"../../proto/compiled/Git_pb\"","webpack://polykey/./src/lib/git/upload-pack/GitPktLine.ts","webpack://polykey/./src/lib/git/upload-pack/GitRefManager.ts","webpack://polykey/external \"pako\"","webpack://polykey/./src/lib/git/pack-objects/GitCommit.ts","webpack://polykey/./src/lib/git/pack-objects/GitObjectManager.ts","webpack://polykey/./src/lib/peers/PeerInfo.ts","webpack://polykey/external \"isomorphic-git\"","webpack://polykey/external \"encryptedfs\"","webpack://polykey/external \"virtualfs\"","webpack://polykey/./src/lib/agent/PolykeyClient.ts","webpack://polykey/external \"../../proto/js/Agent\"","webpack://polykey/./src/lib/keys/KeyManager.ts","webpack://polykey/external \"kbpgp\"","webpack://polykey/external \"util\"","webpack://polykey/./src/lib/peers/PeerManager.ts","webpack://polykey/./src/lib/git/GitClient.ts","webpack://polykey/./src/lib/git/GitBackend.ts","webpack://polykey/./src/lib/git/upload-pack/uploadPack.ts","webpack://polykey/./src/lib/git/upload-pack/GitPackedRefs.ts","webpack://polykey/./src/lib/git/side-band/GitSideBand.ts","webpack://polykey/external \"buffer\"","webpack://polykey/./src/lib/git/pack-objects/packObjects.ts","webpack://polykey/./src/lib/git/pack-objects/log.ts","webpack://polykey/./src/lib/git/pack-objects/GitObject.ts","webpack://polykey/./src/lib/git/pack-objects/shasum.ts","webpack://polykey/external \"sha.js/sha1\"","webpack://polykey/./src/lib/git/pack-objects/GitTree.ts","webpack://polykey/external \"sha.js\"","webpack://polykey/external \"../../proto/js/Peer\"","webpack://polykey/./src/lib/utils.ts","webpack://polykey/./src/lib/peers/MulticastBroadcaster.ts","webpack://polykey/external \"dgram\"","webpack://polykey/external \"events\"","webpack://polykey/external \"../../proto/js/Peer.js\"","webpack://polykey/./src/lib/vaults/VaultManager.ts","webpack://polykey/./src/lib/vaults/Vault.ts","webpack://polykey/external \"async-mutex\"","webpack://polykey/./src/lib/agent/PolykeyAgent.ts","webpack://polykey/external \"net\"","webpack://polykey/external \"process\"","webpack://polykey/external \"child_process\"","webpack://polykey/external \"configstore\""],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBAAmB,EAAE;QACrI;QACA;;QAEA;QACA;QACA;QACA,2BAA2B,0BAA0B,EAAE;QACvD,iCAAiC,eAAe;QAChD;QACA;QACA;;QAEA;QACA,sDAAsD,+DAA+D;;QAErH;QACA;;;QAGA;QACA;;;;;;;AClFA,iC;;;;;;ACAA,+B;;;;;;ACAA,+B;;;;;;ACAA,4C;;;;;;;ACAa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,6BAA6B,mBAAO,CAAC,CAAI;AACzC,qCAAqC,mBAAO,CAAC,EAAmB;AAChE;AACA,sCAAsC,mBAAO,CAAC,EAAqB;AACnE;AACA,uCAAuC,mBAAO,CAAC,EAAuB;AACtE;AACA,uCAAuC,mBAAO,CAAC,EAAsB;AACrE;AACA,wCAAwC,mBAAO,CAAC,EAAuB;AACvE;AACA;AACA,iCAAiC,uBAAuB;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC3BA,mC;;;;;;ACAA,0C;;;;;;ACAA,6D;;;;;;ACAA,wD;;;;;;;ACAa;AACb;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,cAAc;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5Fa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D;AACA,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,wCAAwC,mBAAO,CAAC,EAAiB;AACjE;AACA;AACA,OAAO,IAAI;AACX,YAAY,IAAI;AAChB,iBAAiB,IAAI;AACrB,kBAAkB,IAAI;AACtB,oBAAoB,IAAI;AACxB,oBAAoB,IAAI;AACxB;AACA;AACA;AACA,8BAA8B,EAAE;AAChC,8BAA8B,EAAE;AAChC;AACA;AACA,8BAA8B;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,aAAa;AACb,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT,KAAK;AACL;AACA;AACA;AACA,gDAAgD,OAAO,gBAAgB,mBAAmB;AAC1F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,OAAO,GAAG,SAAS;AACvE,kDAAkD,OAAO,GAAG,SAAS;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,GAAG;AAC9C;AACA;AACA;AACA;AACA;AACA,6EAA6E;AAC7E;AACA,mDAAmD,OAAO,GAAG,IAAI,IAAI,mBAAmB;AACxF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC5HA,iC;;;;;;;ACAa;AACb;AACA;AACA;AACA,8CAA8C,cAAc;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,qBAAqB;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,0BAA0B;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,SAAS;AACxC;AACA;AACA,yEAAyE;AACzE;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,EAAE;AACvC;AACA;AACA;AACA,6BAA6B,YAAY,IAAI,aAAa,IAAI,iBAAiB,GAAG,4CAA4C;AAC9H;AACA,gCAAgC,eAAe,IAAI,gBAAgB,IAAI,oBAAoB,GAAG,+CAA+C;AAC7I;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtLa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,6BAA6B,mBAAO,CAAC,CAAI;AACzC,+BAA+B,mBAAO,CAAC,EAAM;AAC7C,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,oCAAoC,mBAAO,CAAC,EAAa;AACzD;AACA;AACA;AACA;AACA,8CAA8C,OAAO,WAAW,gBAAgB,GAAG,aAAa;AAChG,kCAAkC,gBAAgB,GAAG,aAAa;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gEAAgE,OAAO,gBAAgB,SAAS;AAChG,sCAAsC,OAAO;AAC7C;AACA;AACA,+CAA+C,2BAA2B;AAC1E,sDAAsD,SAAS;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD,OAAO,YAAY,mBAAmB;AACxF;AACA,0DAA0D,IAAI;AAC9D;AACA;AACA;AACA;AACA,+CAA+C,IAAI;AACnD;AACA;AACA,oBAAoB;AACpB;AACA;AACA;AACA,oBAAoB;AACpB;AACA,aAAa,eAAe,+BAA+B,cAAc;AACzE;AACA,oBAAoB;AACpB;AACA;AACA;;;;;;;;AC/Da;AACb,8CAA8C,cAAc;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+DAA+D,QAAQ,GAAG,UAAU;AACpF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gDAAgD,QAAQ,GAAG,UAAU;AACrE;AACA;AACA,kBAAkB,QAAQ,GAAG,UAAU;AACvC;AACA;AACA;AACA;AACA,cAAc,QAAQ,GAAG,UAAU;AACnC;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;;;;;;;AClEA,2C;;;;;;ACAA,wC;;;;;;ACAA,sC;;;;;;;ACAa;AACb,8CAA8C,cAAc;AAC5D,gBAAgB,mBAAO,CAAC,EAAyB;AACjD,OAAO,qtBAAqtB;AAC5tB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,mBAAmB,mBAAmB;AACtC;AACA,uBAAuB,QAAQ;AAC/B,yDAAyD,MAAM;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uEAAuE,aAAa;AACpF;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,6DAA6D,iCAAiC;AAC9F;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,+DAA+D,eAAe;AAC9E;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wDAAwD,sBAAsB;AAC9E;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,uCAAuC;AAC9F;AACA;AACA;AACA;AACA;AACA,eAAe,gBAAgB;AAC/B;AACA;AACA;AACA;AACA,yDAAyD,0BAA0B;AACnF;AACA;AACA;AACA;AACA;AACA,eAAe,WAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,uDAAuD,YAAY;AACnE;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,2DAA2D,YAAY;AACvE;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,YAAY;AACtE;AACA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,4CAA4C;AACrG;AACA;AACA,yDAAyD,+CAA+C;AACxG;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,4DAA4D,wBAAwB;AACpF;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA,wDAAwD,wBAAwB;AAChF;AACA;AACA;AACA;AACA;AACA,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1PA,iD;;;;;;;ACAa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,6BAA6B,mBAAO,CAAC,CAAI;AACzC,6BAA6B,mBAAO,CAAC,CAAI;AACzC,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,gCAAgC,mBAAO,CAAC,EAAO;AAC/C,iCAAiC,mBAAO,CAAC,CAAQ;AACjD,eAAe,mBAAO,CAAC,EAAM;AAC7B;AACA,iCAAiC,uBAAuB;AACxD,+BAA+B;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,kBAAkB;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6DAA6D,kCAAkC;AAC/F,uBAAuB,KAAK,IAAI,MAAM;AACtC;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA,+DAA+D;AAC/D;AACA,8FAA8F;AAC9F;AACA,+FAA+F,yBAAyB;AACxH;AACA,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qGAAqG,qBAAqB;AAC1H,2EAA2E,sBAAsB;AACjG;AACA,wEAAwE,yBAAyB;AACjG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,KAAK;AACjE;AACA;AACA,qEAAqE,kBAAkB;AACvF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,KAAK;AACjE;AACA;AACA,gFAAgF,kBAAkB;AAClG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qGAAqG,qBAAqB;AAC1H;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qGAAqG,sBAAsB;AAC3H;AACA,yDAAyD,yBAAyB;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,SAAS;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC3kBA,kC;;;;;;ACAA,iC;;;;;;;ACAa;AACb;AACA,4CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,cAAc;AAC5D,6BAA6B,mBAAO,CAAC,CAAI;AACzC,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,0BAA0B,mBAAO,CAAC,CAAe;AACjD,oCAAoC,mBAAO,CAAC,EAAkB;AAC9D,qCAAqC,mBAAO,CAAC,EAAmB;AAChE,eAAe,mBAAO,CAAC,EAAwB;AAC/C,gBAAgB,mBAAO,CAAC,EAAU;AAClC,gCAAgC,mBAAO,CAAC,EAAmB;AAC3D,+CAA+C,mBAAO,CAAC,EAA+B;AACtF,sBAAsB,mBAAO,CAAC,CAAqC;AACnE,iBAAiB,mBAAO,CAAC,CAAgC;AACzD;AACA;AACA;AACA,qEAAqE,QAAQ,GAAG,OAAO;AACvF;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,YAAY;AAC3D;AACA,KAAK;AACL;AACA;AACA,iCAAiC,uBAAuB;AACxD;AACA,yBAAyB;AACzB;AACA;AACA,gDAAgD,kBAAkB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,yCAAyC,8DAA8D;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,aAAa;AACb,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8EAA8E,qBAAqB;AACnG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mCAAmC;AACtD;AACA;AACA;AACA;AACA;;;;;;;;ACrQa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,cAAc;AAC5D,0BAA0B,mBAAO,CAAC,CAAe;AACjD,sBAAsB,mBAAO,CAAC,CAAqC;AACnE,iBAAiB,mBAAO,CAAC,CAAgC;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,yCAAyC;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,aAAa;AACrD;AACA;AACA;AACA,iCAAiC,2BAA2B;AAC5D;AACA,iBAAiB;AACjB,aAAa;AACb;AACA;AACA;AACA;;;;;;;;ACpIa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,0BAA0B,mBAAO,CAAC,CAAiB;AACnD,qCAAqC,mBAAO,CAAC,EAA0B;AACvE,sCAAsC,mBAAO,CAAC,EAAyB;AACvE,sCAAsC,mBAAO,CAAC,EAA4B;AAC1E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA,qBAAqB;AACrB;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrGa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,qCAAqC,mBAAO,CAAC,CAAc;AAC3D,wCAAwC,mBAAO,CAAC,EAAiB;AACjE,oCAAoC,8BAA8B;AAClE;AACA;AACA;AACA;AACA,0BAA0B,IAAI,GAAG,MAAM;AACvC;AACA,sBAAsB,4BAA4B,GAAG,KAAK;AAC1D,mDAAmD,QAAQ;AAC3D;AACA;AACA;AACA;AACA,mDAAmD,MAAM,GAAG,IAAI,EAAE,KAAK;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,IAAI;AACjD;AACA,iCAAiC;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrDa;AACb,8CAA8C,cAAc;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC;AACrC,4CAA4C;AAC5C,4BAA4B;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvCa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,mBAAO,CAAC,EAAQ;AACjC,0BAA0B,mBAAO,CAAC,CAAiB;AACnD,qCAAqC,mBAAO,CAAC,CAA2B;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;;;;;;;ACrJA,mC;;;;;;;ACAa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,+BAA+B,mBAAO,CAAC,EAAM;AAC7C,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,8BAA8B,mBAAO,CAAC,EAAO;AAC7C,kCAAkC,mBAAO,CAAC,EAAW;AACrD,iCAAiC,mBAAO,CAAC,EAAQ;AACjD,oCAAoC,mBAAO,CAAC,EAAa;AACzD,0BAA0B,mBAAO,CAAC,CAAiB;AACnD,2CAA2C,mBAAO,CAAC,EAAoB;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAoB;AAC/C;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,eAAe;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,eAAe;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvKa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,aAAa,mBAAO,CAAC,CAAM;AAC3B,oCAAoC,mBAAO,CAAC,EAAa;AACzD,2CAA2C,mBAAO,CAAC,EAAoB;AACvE,wCAAwC,mBAAO,CAAC,EAA8B;AAC9E;AACA;AACA,aAAa,eAAe;AAC5B;AACA;AACA;AACA;AACA,sCAAsC,MAAM;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpFa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,iCAAiC,mBAAO,CAAC,EAAU;AACnD;AACA,iBAAiB,eAAe;AAChC,mDAAmD,KAAK,GAAG,6BAA6B;AACxF;AACA;AACA;AACA,iBAAiB,eAAe;AAChC,mDAAmD,KAAK,GAAG,6BAA6B;AACxF;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,cAAc;AACjC;AACA;AACA;AACA,8DAA8D,IAAI,aAAa,IAAI;AACnF;AACA;AACA,mCAAmC;AACnC,kCAAkC;AAClC,uDAAuD;AACvD,6DAA6D;AAC7D;AACA;AACA;AACA,yDAAyD,OAAO,iBAAiB,aAAa;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1Ca;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,+BAA+B,mBAAO,CAAC,EAAa;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACZA,wC;;;;;;;ACAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,cAAc;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA,8EAA8E,OAAO;AACrF;AACA;AACA;AACA,8EAA8E,OAAO;AACrF;AACA;AACA;AACA,4BAA4B;AAC5B;AACA;AACA;AACA;AACA,uBAAuB,wBAAwB;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB;AACA,wBAAwB;AACxB;AACA,wBAAwB;AACxB;AACA,wBAAwB;AACxB;AACA,wBAAwB;AACxB,uDAAuD,KAAK;AAC5D;AACA;AACA;AACA,8BAA8B;AAC9B;AACA,gDAAgD;AAChD;AACA,4BAA4B;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,WAAW,GAAG,WAAW,GAAG,UAAU,MAAM,WAAW;AACtG;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,mBAAmB;AACtE;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AClGA,mC;;;;;;ACAA,gD;;;;;;;ACAa;AACb,8CAA8C,cAAc;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1Ba;AACb;AACA,4CAA4C;AAC5C;AACA;AACA,8CAA8C,cAAc;AAC5D,gCAAgC,mBAAO,CAAC,EAAO;AAC/C,iCAAiC,mBAAO,CAAC,CAAQ;AACjD,mCAAmC,mBAAO,CAAC,EAAY;AACvD,iBAAiB,mBAAO,CAAC,EAAQ;AACjC,kBAAkB,mBAAO,CAAC,EAA2B;AACrD,OAAO,oCAAoC;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,gCAAgC;AACpF;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,4DAA4D;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,mCAAmC;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC/IA,kC;;;;;;ACAA,mC;;;;;;ACAA,mD;;;;;;;ACAa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,6BAA6B,mBAAO,CAAC,CAAI;AACzC,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,yCAAyC,mBAAO,CAAC,EAAgB;AACjE,gCAAgC,mBAAO,CAAC,EAAiB;AACzD,sBAAsB,mBAAO,CAAC,EAAa;AAC3C;AACA,iCAAiC,uBAAuB;AACxD;AACA;AACA;AACA;AACA;AACA,qDAAqD,kBAAkB;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,kBAAkB;AAC/D;AACA;AACA;AACA;AACA,gEAAgE,UAAU;AAC1E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,UAAU;AACrD;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,sDAAsD,UAAU;AAChE;AACA;AACA;AACA,8DAA8D,UAAU;AACxE;AACA,iCAAiC,mBAAO,CAAC,EAAW;AACpD;AACA;AACA;AACA,iBAAiB,4BAA4B;AAC7C;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,kBAAkB;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzNa;AACb;AACA,4CAA4C;AAC5C;AACA,8CAA8C,cAAc;AAC5D,6BAA6B,mBAAO,CAAC,CAAI;AACzC,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,yCAAyC,mBAAO,CAAC,EAAgB;AACjE,sBAAsB,mBAAO,CAAC,EAAa;AAC3C,sBAAsB,mBAAO,CAAC,EAAa;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,mBAAO,CAAC,EAAW;AACpD;AACA;AACA;AACA;AACA,4CAA4C,kBAAkB;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mEAAmE;AACnE;AACA;AACA;AACA,oDAAoD,WAAW;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mEAAmE;AACnE;AACA;AACA;AACA,uDAAuD,WAAW;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sEAAsE;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2DAA2D,WAAW;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,8BAA8B;AACnD;AACA;AACA,aAAa;AACb;AACA;AACA,qBAAqB,8BAA8B;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB,8BAA8B;AAC/C;AACA;AACA,SAAS;AACT;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,uEAAuE,kBAAkB;AACzF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,8BAA8B;AACnD;AACA;AACA,aAAa;AACb;AACA;AACA;AACA,qBAAqB,8BAA8B;AACnD;AACA;AACA,aAAa;AACb;AACA;AACA,iBAAiB,8BAA8B;AAC/C;AACA;AACA;AACA,aAAa;AACb;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1SA,wC;;;;;;;ACAa;AACb;AACA,4CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,cAAc;AAC5D,6BAA6B,mBAAO,CAAC,CAAI;AACzC,6BAA6B,mBAAO,CAAC,CAAI;AACzC,8BAA8B,mBAAO,CAAC,EAAK;AAC3C,+BAA+B,mBAAO,CAAC,CAAM;AAC7C,kCAAkC,mBAAO,CAAC,EAAS;AACnD,wBAAwB,mBAAO,CAAC,EAAe;AAC/C,+BAA+B,mBAAO,CAAC,CAAY;AACnD,sCAAsC,mBAAO,CAAC,EAAa;AAC3D,wCAAwC,mBAAO,CAAC,EAAiB;AACjE,gBAAgB,mBAAO,CAAC,EAAyB;AACjD,OAAO,qtBAAqtB;AAC5tB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,6BAA6B;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mEAAmE,KAAK;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,iEAAiE;AACtH,iBAAiB;AACjB;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,eAAe,aAAa;AAC5B;AACA;AACA;AACA,0EAA0E,SAAS;AACnF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,SAAS;AAC/C;AACA;AACA,sDAAsD,SAAS;AAC/D;AACA,eAAe,iCAAiC;AAChD;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,eAAe,eAAe;AAC9B;AACA,oDAAoD,gCAAgC;AACpF;AACA;AACA,oDAAoD,2BAA2B;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,SAAS;AAC3E;AACA;AACA;AACA;AACA;AACA,sDAAsD,SAAS;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,sBAAsB;AACrC;AACA;AACA,gDAAgD,mBAAmB;AACnE;AACA;AACA;AACA;AACA;AACA,eAAe,uCAAuC;AACtD;AACA;AACA,+CAA+C,gBAAgB;AAC/D;AACA;AACA,eAAe,0BAA0B;AACzC;AACA;AACA,iDAAiD,WAAW;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,aAAa;AAC9D;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA,+CAA+C,mBAAmB;AAClE;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA,mDAAmD,mBAAmB;AACtE;AACA;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA,kDAAkD,cAAc;AAChE;AACA;AACA,eAAe,mDAAmD;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,mBAAmB;AACtE;AACA;AACA,eAAe,wBAAwB;AACvC;AACA;AACA;AACA,oDAAoD,mBAAmB;AACvE;AACA;AACA,eAAe,wBAAwB;AACvC;AACA;AACA;AACA,gDAAgD,iBAAiB;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,aAAa;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,aAAa;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,kBAAkB;AACpF,kEAAkE,kBAAkB;AACpF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1YA,gC;;;;;;ACAA,oC;;;;;;ACAA,0C;;;;;;ACAA,wC","file":"polykey.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"polykey\"] = factory();\n\telse\n\t\troot[\"polykey\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 4);\n","module.exports = require(\"path\");","module.exports = require(\"os\");","module.exports = require(\"fs\");","module.exports = require(\"readable-stream\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst KeyManager_1 = __importDefault(require(\"./keys/KeyManager\"));\nexports.KeyManager = KeyManager_1.default;\nconst PeerManager_1 = __importDefault(require(\"./peers/PeerManager\"));\nexports.PeerManager = PeerManager_1.default;\nconst VaultManager_1 = __importDefault(require(\"./vaults/VaultManager\"));\nexports.VaultManager = VaultManager_1.default;\nconst PolykeyAgent_1 = __importDefault(require(\"./agent/PolykeyAgent\"));\nexports.PolykeyAgent = PolykeyAgent_1.default;\nconst PolykeyClient_1 = __importDefault(require(\"./agent/PolykeyClient\"));\nexports.PolykeyClient = PolykeyClient_1.default;\nclass Polykey {\n constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager, vaultManager, peerManager) {\n this.polykeyPath = polykeyPath;\n // Set key manager\n this.keyManager = keyManager !== null && keyManager !== void 0 ? keyManager : new KeyManager_1.default(this.polykeyPath, fileSystem);\n // Set or Initialize vaultManager\n this.vaultManager = vaultManager !== null && vaultManager !== void 0 ? vaultManager : new VaultManager_1.default(this.polykeyPath, fileSystem, this.keyManager);\n // Initialize peer store and peer discovery classes\n this.peerManager = peerManager !== null && peerManager !== void 0 ? peerManager : new PeerManager_1.default(this.polykeyPath, fileSystem, this.keyManager, this.vaultManager);\n }\n}\nexports.default = Polykey;\n","module.exports = require(\"crypto\");","module.exports = require(\"@grpc/grpc-js\");","module.exports = require(\"../../proto/compiled/Git_grpc_pb\");","module.exports = require(\"../../proto/compiled/Git_pb\");","\"use strict\";\n/**\npkt-line Format\n---------------\n\nMuch (but not all) of the payload is described around pkt-lines.\n\nA pkt-line is a variable length binary string. The first four bytes\nof the line, the pkt-len, indicates the total length of the line,\nin hexadecimal. The pkt-len includes the 4 bytes used to contain\nthe length's hexadecimal representation.\n\nA pkt-line MAY contain binary data, so implementors MUST ensure\npkt-line parsing/formatting routines are 8-bit clean.\n\nA non-binary line SHOULD BE terminated by an LF, which if present\nMUST be included in the total length. Receivers MUST treat pkt-lines\nwith non-binary data the same whether or not they contain the trailing\nLF (stripping the LF if present, and not complaining when it is\nmissing).\n\nThe maximum length of a pkt-line's data component is 65516 bytes.\nImplementations MUST NOT send pkt-line whose length exceeds 65520\n(65516 bytes of payload + 4 bytes of length data).\n\nImplementations SHOULD NOT send an empty pkt-line (\"0004\").\n\nA pkt-line with a length field of 0 (\"0000\"), called a flush-pkt,\nis a special case and MUST be handled differently than an empty\npkt-line (\"0004\").\n\n----\n pkt-line = data-pkt / flush-pkt\n\n data-pkt = pkt-len pkt-payload\n pkt-len = 4*(HEXDIG)\n pkt-payload = (pkt-len - 4)*(OCTET)\n\n flush-pkt = \"0000\"\n----\n\nExamples (as C-style strings):\n\n----\n pkt-line actual value\n ---------------------------------\n \"0006a\\n\" \"a\\n\"\n \"0005a\" \"a\"\n \"000bfoobar\\n\" \"foobar\\n\"\n \"0004\" \"\"\n----\n*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction padHex(b, n) {\n const s = n.toString(16);\n return '0'.repeat(b - s.length) + s;\n}\n// I'm really using this more as a namespace.\n// There's not a lot of \"state\" in a pkt-line\nclass GitPktLine {\n static flush() {\n return Buffer.from('0000', 'utf8');\n }\n static encode(line) {\n if (typeof line === 'string') {\n line = Buffer.from(line);\n }\n const length = line.length + 4;\n const hexlength = padHex(4, length);\n return Buffer.concat([Buffer.from(hexlength, 'utf8'), line]);\n }\n static streamReader(stream) {\n return async function read() {\n try {\n let length = await stream.slice(4);\n if (length === null)\n return true;\n length = parseInt(length.toString('utf8'), 16);\n if (length === 0)\n return null;\n let buffer = await stream.slice(length - 4);\n if (buffer === null)\n return true;\n return buffer;\n }\n catch (err) {\n console.log('error', err);\n return true;\n }\n };\n }\n}\nexports.default = GitPktLine;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// This is a convenience wrapper for reading and writing files in the 'refs' directory.\nconst path_1 = __importDefault(require(\"path\"));\nconst GitPackedRefs_1 = __importDefault(require(\"./GitPackedRefs\"));\n// @see https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions\nconst refpaths = (ref) => [\n `${ref}`,\n `refs/${ref}`,\n `refs/tags/${ref}`,\n `refs/heads/${ref}`,\n `refs/remotes/${ref}`,\n `refs/remotes/${ref}/HEAD`,\n];\nfunction compareRefNames(a, b) {\n // https://stackoverflow.com/a/40355107/2168416\n const _a = a.replace(/\\^\\{\\}$/, '');\n const _b = b.replace(/\\^\\{\\}$/, '');\n const tmp = -(_a < _b) || +(_a > _b);\n if (tmp === 0) {\n return a.endsWith('^{}') ? 1 : -1;\n }\n return tmp;\n}\n// @see https://git-scm.com/docs/gitrepository-layout\nconst GIT_FILES = ['config', 'description', 'index', 'shallow', 'commondir'];\n// This function is used to get all the files in the refs folder for listRefs function\nasync function recursiveDirectoryWalk(dir, fileSystem) {\n return new Promise((resolve, reject) => {\n let results = [];\n fileSystem.promises\n .readdir(dir)\n .then(async (list) => {\n var pending = list.length;\n if (!pending)\n return resolve(results);\n list.forEach(async function (file) {\n file = path_1.default.resolve(dir, file);\n fileSystem.promises.stat(file).then(async (stat) => {\n if (stat && stat.isDirectory()) {\n const res = await recursiveDirectoryWalk(file, fileSystem);\n results = results.concat(res);\n if (!--pending)\n resolve(results);\n }\n else {\n results.push(file);\n if (!--pending)\n resolve(results);\n }\n });\n });\n })\n .catch((err) => {\n if (err)\n return reject(err);\n });\n });\n}\nclass GitRefManager {\n static async packedRefs(fileSystem, gitdir) {\n const text = fileSystem.readFileSync(`${gitdir}/packed-refs`, { encoding: 'utf8' });\n const packed = GitPackedRefs_1.default.from(text);\n return packed.refs;\n }\n // List all the refs that match the `filepath` prefix\n static async listRefs(fileSystem, gitdir, filepath) {\n const packedMap = GitRefManager.packedRefs(fileSystem, gitdir);\n let files = [];\n try {\n files = await recursiveDirectoryWalk(`${gitdir}/${filepath}`, fileSystem);\n files = files.map((x) => x.replace(`${gitdir}/${filepath}/`, ''));\n }\n catch (err) {\n files = [];\n }\n for (let key of (await packedMap).keys()) {\n // filter by prefix\n if (key.startsWith(filepath)) {\n // remove prefix\n key = key.replace(filepath + '/', '');\n // Don't include duplicates; the loose files have precedence anyway\n if (!files.includes(key)) {\n files.push(key);\n }\n }\n }\n // since we just appended things onto an array, we need to sort them now\n files.sort(compareRefNames);\n return files;\n }\n static async resolve(fileSystem, gitdir, ref, depth) {\n if (depth !== undefined) {\n depth--;\n if (depth === -1) {\n return ref;\n }\n }\n // Is it a ref pointer?\n if (ref.startsWith('ref: ')) {\n ref = ref.slice('ref: '.length);\n return GitRefManager.resolve(fileSystem, gitdir, ref, depth);\n }\n // Is it a complete and valid SHA?\n if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) {\n return ref;\n }\n // We need to alternate between the file system and the packed-refs\n const packedMap = await GitRefManager.packedRefs(fileSystem, gitdir);\n // Look in all the proper paths, in this order\n const allpaths = refpaths(ref).filter((p) => !GIT_FILES.includes(p)); // exclude git system files (#709)\n for (const ref of allpaths) {\n const sha = fileSystem.readFileSync(`${gitdir}/${ref}`, { encoding: 'utf8' }).toString() || packedMap.get(ref);\n if (sha) {\n return GitRefManager.resolve(fileSystem, gitdir, sha.trim(), depth);\n }\n }\n // Do we give up?\n throw Error('RefNotFound');\n }\n}\nexports.default = GitRefManager;\n","module.exports = require(\"pako\");","\"use strict\";\n// The amount of work that went into crafting these cases to handle\n// -0 (just so we don't lose that information when parsing and reconstructing)\n// but can also default to +0 was extraordinary.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction simpleSign(n) {\n return Math.sign(n) || (Object.is(n, -0) ? -1 : 1);\n}\nfunction negateExceptForZero(n) {\n return n === 0 ? n : -n;\n}\nfunction formatTimezoneOffset(minutes) {\n let sign = simpleSign(negateExceptForZero(minutes));\n minutes = Math.abs(minutes);\n let hours = Math.floor(minutes / 60);\n minutes -= hours * 60;\n let strHours = String(hours);\n let strMinutes = String(minutes);\n if (strHours.length < 2)\n strHours = '0' + strHours;\n if (strMinutes.length < 2)\n strMinutes = '0' + strMinutes;\n return (sign === -1 ? '-' : '+') + strHours + strMinutes;\n}\nfunction parseTimezoneOffset(offset) {\n let [, sign, hours, minutes] = offset.match(/(\\+|-)(\\d\\d)(\\d\\d)/);\n minutes = (sign === '+' ? 1 : -1) * (Number(hours) * 60 + Number(minutes));\n return negateExceptForZero(minutes);\n}\nfunction parseAuthor(author) {\n let [, name, email, timestamp, offset] = author.match(/^(.*) <(.*)> (.*) (.*)$/);\n return {\n name: name,\n email: email,\n timestamp: Number(timestamp),\n timezoneOffset: parseTimezoneOffset(offset),\n };\n}\nfunction normalize(str) {\n // remove all \n str = str.replace(/\\r/g, '');\n // no extra newlines up front\n str = str.replace(/^\\n+/, '');\n // and a single newline at the end\n str = str.replace(/\\n+$/, '') + '\\n';\n return str;\n}\nfunction indent(str) {\n return (str\n .trim()\n .split('\\n')\n .map((x) => ' ' + x)\n .join('\\n') + '\\n');\n}\nfunction outdent(str) {\n return str\n .split('\\n')\n .map((x) => x.replace(/^ /, ''))\n .join('\\n');\n}\n// TODO: Make all functions have static async signature?\nclass GitCommit {\n constructor(commit) {\n if (typeof commit === 'string') {\n this._commit = commit;\n }\n else if (Buffer.isBuffer(commit)) {\n this._commit = commit.toString('utf8');\n }\n else if (typeof commit === 'object') {\n this._commit = GitCommit.render(commit);\n }\n else {\n throw new Error('invalid type passed to GitCommit constructor');\n }\n }\n static fromPayloadSignature({ payload, signature }) {\n let headers = GitCommit.justHeaders(payload);\n let message = GitCommit.justMessage(payload);\n let commit = normalize(headers + '\\ngpgsig' + indent(signature) + '\\n' + message);\n return new GitCommit(commit);\n }\n static from(commit) {\n return new GitCommit(commit);\n }\n toObject() {\n return Buffer.from(this._commit, 'utf8');\n }\n // Todo: allow setting the headers and message\n headers() {\n return this.parseHeaders();\n }\n // Todo: allow setting the headers and message\n message() {\n return GitCommit.justMessage(this._commit);\n }\n parse() {\n return Object.assign({ message: this.message() }, this.headers());\n }\n static justMessage(commit) {\n return normalize(commit.slice(commit.indexOf('\\n\\n') + 2));\n }\n static justHeaders(commit) {\n return commit.slice(0, commit.indexOf('\\n\\n'));\n }\n parseHeaders() {\n let headers = GitCommit.justHeaders(this._commit).split('\\n');\n let hs = [];\n for (let h of headers) {\n if (h[0] === ' ') {\n // combine with previous header (without space indent)\n hs[hs.length - 1] += '\\n' + h.slice(1);\n }\n else {\n hs.push(h);\n }\n }\n let obj = {\n parent: [],\n };\n for (let h of hs) {\n let key = h.slice(0, h.indexOf(' '));\n let value = h.slice(h.indexOf(' ') + 1);\n if (Array.isArray(obj[key])) {\n obj[key].push(value);\n }\n else {\n obj[key] = value;\n }\n }\n if (obj.author) {\n obj.author = parseAuthor(obj.author);\n }\n if (obj.committer) {\n obj.committer = parseAuthor(obj.committer);\n }\n return obj;\n }\n static renderHeaders(obj) {\n let headers = '';\n if (obj.tree) {\n headers += `tree ${obj.tree}\\n`;\n }\n else {\n headers += `tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\\n`; // the null tree\n }\n if (obj.parent) {\n if (obj.parent.length === undefined) {\n throw new Error(`commit 'parent' property should be an array`);\n }\n for (let p of obj.parent) {\n headers += `parent ${p}\\n`;\n }\n }\n let author = obj.author;\n headers += `author ${author.name} <${author.email}> ${author.timestamp} ${formatTimezoneOffset(author.timezoneOffset)}\\n`;\n let committer = obj.committer || obj.author;\n headers += `committer ${committer.name} <${committer.email}> ${committer.timestamp} ${formatTimezoneOffset(committer.timezoneOffset)}\\n`;\n if (obj.gpgsig) {\n headers += 'gpgsig' + indent(obj.gpgsig);\n }\n return headers;\n }\n static render(obj) {\n return GitCommit.renderHeaders(obj) + '\\n' + normalize(obj.message);\n }\n render() {\n return this._commit;\n }\n withoutSignature() {\n let commit = normalize(this._commit);\n if (commit.indexOf('\\ngpgsig') === -1)\n return commit;\n let headers = commit.slice(0, commit.indexOf('\\ngpgsig'));\n let message = commit.slice(commit.indexOf('-----END PGP SIGNATURE-----\\n') + '-----END PGP SIGNATURE-----\\n'.length);\n return normalize(headers + '\\n' + message);\n }\n isolateSignature() {\n let signature = this._commit.slice(this._commit.indexOf('-----BEGIN PGP SIGNATURE-----'), this._commit.indexOf('-----END PGP SIGNATURE-----') + '-----END PGP SIGNATURE-----'.length);\n return outdent(signature);\n }\n}\nexports.default = GitCommit;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = __importDefault(require(\"fs\"));\nconst pako_1 = __importDefault(require(\"pako\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst GitObject_1 = __importDefault(require(\"./GitObject\"));\nconst PackfileCache = new Map();\nclass GitObjectManager {\n static async read(fileSystem, gitdir, oid, format = 'content') {\n // Look for it in the loose object directory.\n let file = fileSystem.readFileSync(`${gitdir}/objects/${oid.slice(0, 2)}/${oid.slice(2)}`);\n let source = `./objects/${oid.slice(0, 2)}/${oid.slice(2)}`;\n // Check to see if it's in a packfile.\n if (!file) {\n // Curry the current read method so that the packfile un-deltification\n // process can acquire external ref-deltas.\n const getExternalRefDelta = (oid) => GitObjectManager.read(fileSystem, gitdir, oid);\n // Iterate through all the .pack files\n let list = fs_1.default.readdirSync(path_1.default.join(gitdir, '/objects/pack'));\n list = list.filter((x) => x.endsWith('.pack'));\n for (let filename of list) {\n // Try to get the packfile from the in-memory cache\n let p = PackfileCache.get(filename);\n // If the packfile DOES have the oid we're looking for...\n if (p.offsets.has(oid)) {\n // Make sure the packfile is loaded in memory\n if (!p.pack) {\n const pack = fileSystem.readFileSync(`${gitdir}/objects/pack/${filename}`);\n await p.load({ pack });\n }\n // Get the resolved git object from the packfile\n let result = await p.read({ oid, getExternalRefDelta });\n result.source = `./objects/pack/${filename}`;\n return result;\n }\n }\n }\n // Check to see if it's in shallow commits.\n if (!file) {\n let text = fileSystem.readFileSync(`${gitdir}/shallow`, { encoding: 'utf8' });\n if (text !== null && text.includes(oid)) {\n throw new Error(`ReadShallowObjectFail: ${oid}`);\n }\n }\n // Finally\n if (!file) {\n throw new Error(`ReadObjectFail: ${oid}`);\n }\n if (format === 'deflated') {\n return { format: 'deflated', object: file, source };\n }\n let buffer = Buffer.from(pako_1.default.inflate(file));\n if (format === 'wrapped') {\n return { format: 'wrapped', object: buffer, source };\n }\n let { type, object } = GitObject_1.default.unwrap({ oid, buffer });\n if (format === 'content')\n return { type, format: 'content', object, source };\n }\n}\nexports.default = GitObjectManager;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass Address {\n constructor(ip, port) {\n this.ip = ip;\n this.port = port;\n }\n /**\n * Create an address object from a address string\n * @param addressString Address string in the format of `${this.ip}:${this.port}`\n */\n static parse(addressString) {\n const components = addressString.split(':');\n const ip = components[0];\n const port = components[1];\n return new Address(ip, port);\n }\n /**\n * Create an address object from a net.AddressInfo\n * @param addressInfo AddressInfo of desired address\n */\n static fromAddressInfo(addressInfo) {\n const ip = addressInfo.address == '::' ? 'localhost' : addressInfo.address;\n return new Address(ip, addressInfo.port.toString());\n }\n /**\n * Convert address into string of format `${this.ip}:${this.port}`\n */\n toString() {\n return `${this.ip}:${this.port}`;\n }\n}\nexports.Address = Address;\nAddress.prototype.toString = function () {\n return `${this.ip}:${this.port}`;\n};\nclass PeerInfo {\n constructor(pubKey, addresses = [], connectedAddr) {\n this.publicKey = pubKey;\n this.addresses = new Set(addresses.map((addr) => {\n return Address.parse(addr);\n }));\n this.connectedAddr = connectedAddr ? Address.parse(connectedAddr) : undefined;\n }\n /**\n * Sets the main server address for the peer\n * @param address Main server address for peer\n */\n connect(address) {\n if (!this.addresses.has(address)) {\n this.addresses.add(address);\n }\n this.connectedAddr = address;\n }\n /**\n * Clears the main server address for the peer\n */\n disconnect() {\n this.connectedAddr = undefined;\n }\n get AdressStringList() {\n return Array.from(this.addresses.values()).map((addr) => {\n return addr.toString();\n });\n }\n}\nexports.default = PeerInfo;\n","module.exports = require(\"isomorphic-git\");","module.exports = require(\"encryptedfs\");","module.exports = require(\"virtualfs\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Agent_1 = require(\"../../../proto/js/Agent\");\nconst { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage, } = Agent_1.agent;\nclass PolykeyClient {\n constructor(getStream) {\n this.getStream = getStream;\n }\n async sendRequestToAgent(request) {\n const stream = this.getStream();\n const responseList = await new Promise((resolve, reject) => {\n try {\n const responseList = [];\n stream.on('data', (data) => {\n if (data instanceof Uint8Array) {\n responseList.push(data);\n }\n else {\n responseList.push(...data);\n }\n });\n stream.on('error', (err) => {\n reject(err);\n });\n stream.on('end', () => {\n resolve(responseList);\n });\n if (!stream.writableEnded) {\n stream.write(request);\n }\n }\n catch (err) {\n reject(err);\n }\n });\n return responseList;\n }\n async handleAgentCommunication(type, nodePath, request) {\n // Encode message and sent\n const agentMessage = AgentMessage.encode({\n type: type,\n isResponse: false,\n nodePath: nodePath,\n subMessage: request,\n }).finish();\n const responseList = await this.sendRequestToAgent(agentMessage);\n const agentMessageList = [];\n for (const response of responseList.values()) {\n const { subMessage, type } = AgentMessage.decode(response);\n if (type == Type.ERROR) {\n const { error } = ErrorMessage.decode(subMessage);\n const reason = new Error(`Agent Error: ${error}`);\n throw reason;\n }\n else {\n agentMessageList.push(AgentMessage.decode(response));\n }\n }\n return agentMessageList;\n }\n async registerNode(path, passphrase) {\n var _a;\n const registerNodeRequest = RegisterNodeRequestMessage.encode({ passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.REGISTER_NODE, path, registerNodeRequest);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.REGISTER_NODE)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = RegisterNodeResponseMessage.decode(subMessage);\n return successful;\n }\n async newNode(path, name, email, passphrase, nbits) {\n var _a;\n const newNodeRequest = NewNodeRequestMessage.encode({ name, email, passphrase, nbits }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.NEW_NODE, path, newNodeRequest);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.NEW_NODE)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = NewNodeResponseMessage.decode(subMessage);\n return successful;\n }\n async listNodes(unlockedOnly = true) {\n var _a;\n const newNodeRequest = ListNodesRequestMessage.encode({ unlockedOnly }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_NODES, undefined, newNodeRequest);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_NODES)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { nodes } = ListNodesResponseMessage.decode(subMessage);\n return nodes;\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async deriveKey(nodePath, keyName, passphrase) {\n var _a;\n const request = DeriveKeyRequestMessage.encode({ keyName, passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DERIVE_KEY, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DERIVE_KEY)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = DeriveKeyResponseMessage.decode(subMessage);\n return successful;\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async signFile(nodePath, filePath, privateKeyPath, passphrase) {\n var _a;\n const request = SignFileRequestMessage.encode({ filePath, privateKeyPath, passphrase }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.SIGN_FILE, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.SIGN_FILE)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { signaturePath } = SignFileResponseMessage.decode(subMessage);\n return signaturePath;\n }\n async verifyFile(nodePath, filePath, signaturePath) {\n var _a;\n const request = VerifyFileRequestMessage.encode({ filePath, signaturePath }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.VERIFY_FILE, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.VERIFY_FILE)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { verified } = VerifyFileResponseMessage.decode(subMessage);\n return verified;\n }\n //////////////////////\n // Vault Operations //\n //////////////////////\n async listVaults(nodePath) {\n var _a;\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_VAULTS, nodePath);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_VAULTS)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { vaultNames } = ListVaultsResponseMessage.decode(subMessage);\n return vaultNames;\n }\n async newVault(nodePath, vaultName) {\n var _a;\n const request = NewVaultRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.NEW_VAULT, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.NEW_VAULT)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = NewVaultResponseMessage.decode(subMessage);\n return successful;\n }\n async destroyVault(nodePath, vaultName) {\n var _a;\n const request = DestroyVaultRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_VAULT, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DESTROY_VAULT)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = DestroyVaultResponseMessage.decode(subMessage);\n return successful;\n }\n ///////////////////////\n // Secret Operations //\n ///////////////////////\n async listSecrets(nodePath, vaultName) {\n var _a;\n const request = ListSecretsRequestMessage.encode({ vaultName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.LIST_SECRETS, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.LIST_SECRETS)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { secretNames } = ListSecretsResponseMessage.decode(subMessage);\n return secretNames;\n }\n async createSecret(nodePath, vaultName, secretName, secret) {\n var _a;\n let request;\n if (typeof secret == 'string') {\n request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretPath: secret }).finish();\n }\n else {\n request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretContent: secret }).finish();\n }\n const encodedResponse = await this.handleAgentCommunication(Type.CREATE_SECRET, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.CREATE_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = CreateSecretResponseMessage.decode(subMessage);\n return successful;\n }\n async destroySecret(nodePath, vaultName, secretName) {\n var _a;\n const request = DestroySecretRequestMessage.encode({ vaultName, secretName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_SECRET, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.DESTROY_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { successful } = DestroySecretResponseMessage.decode(subMessage);\n return successful;\n }\n async getSecret(nodePath, vaultName, secretName) {\n var _a;\n const request = GetSecretRequestMessage.encode({ vaultName, secretName }).finish();\n const encodedResponse = await this.handleAgentCommunication(Type.GET_SECRET, nodePath, request);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.GET_SECRET)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const { secret } = GetSecretResponseMessage.decode(subMessage);\n return Buffer.from(secret);\n }\n ///////////////////\n // Agent control //\n ///////////////////\n async getAgentStatus() {\n var _a;\n try {\n const encodedResponse = await this.handleAgentCommunication(Type.STATUS);\n const subMessage = (_a = encodedResponse.find((r) => r.type == Type.STATUS)) === null || _a === void 0 ? void 0 : _a.subMessage;\n if (!subMessage) {\n throw Error('agent did not respond');\n }\n const status = Buffer.from(subMessage).toString();\n return status;\n }\n catch (err) {\n console.log(err);\n return 'stopped';\n }\n }\n async stopAgent() {\n try {\n // Tell it to start shutting and wait for response\n await this.handleAgentCommunication(Type.STOP_AGENT);\n return true;\n }\n catch (err) {\n return (await this.getAgentStatus()) != 'online';\n }\n }\n}\nexports.default = PolykeyClient;\n","module.exports = require(\"../../proto/js/Agent\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst fs_1 = __importDefault(require(\"fs\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst kbpgp_1 = __importDefault(require(\"kbpgp\"));\nconst crypto_1 = __importDefault(require(\"crypto\"));\nconst util_1 = require(\"util\");\nclass KeyManager {\n constructor(polyKeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, useWebWorkers = false, workerPool) {\n this.primaryKeyPair = { private: null, public: null };\n this.metadata = {\n privateKeyPath: null,\n publicKeyPath: null,\n pkiKeyPath: null,\n pkiCertPath: null,\n caCertPath: null,\n };\n /////////\n // PKI //\n /////////\n this.pkiInfo = { key: null, cert: null, caCert: null };\n this.useWebWorkers = useWebWorkers;\n this.workerPool = workerPool;\n this.derivedKeys = new Map();\n this.fileSystem = fileSystem;\n // Load key manager metadata\n this.polykeyPath = polyKeyPath;\n this.keypairPath = path_1.default.join(polyKeyPath, '.keypair');\n if (!this.fileSystem.existsSync(this.keypairPath)) {\n this.fileSystem.mkdirSync(this.keypairPath, { recursive: true });\n }\n this.metadataPath = path_1.default.join(this.keypairPath, 'metadata');\n this.loadMetadata();\n // Load keys if they were provided\n if (this.metadata.privateKeyPath && this.metadata.publicKeyPath) {\n // Load files into memory\n this.loadKeyPair(this.metadata.publicKeyPath, this.metadata.privateKeyPath);\n }\n /////////\n // PKI //\n /////////\n // Load pki keys and certs\n if (this.metadata.pkiKeyPath) {\n this.pkiInfo.key = fs_1.default.readFileSync(this.metadata.pkiKeyPath);\n }\n if (this.metadata.pkiCertPath) {\n this.pkiInfo.cert = fs_1.default.readFileSync(this.metadata.pkiCertPath);\n }\n if (this.metadata.caCertPath) {\n this.pkiInfo.caCert = fs_1.default.readFileSync(this.metadata.caCertPath);\n }\n this.loadPKIInfo(this.pkiInfo.key, this.pkiInfo.cert, this.pkiInfo.caCert, true);\n }\n get identityLoaded() {\n return this.primaryIdentity ? true : false;\n }\n /**\n * Generates a new assymetric key pair (publicKey and privateKey).\n * @param name Name of keypair owner\n * @param email Email of keypair owner\n * @param passphrase Passphrase to lock the keypair\n * @param nbits Size of the new keypair\n * @param replacePrimary If true, the generated keypair becomes the new primary identity of the key manager\n * @param progressCallback A progress hook for keypair generation\n */\n async generateKeyPair(name, email, passphrase, nbits = 4096, replacePrimary = false, progressCallback) {\n // kbpgp doesn't seem to work for small nbits so set a minimum of 1024\n if (nbits < 1024) {\n throw Error('nbits must be greater than 1024 for keypair generation');\n }\n // Define options\n const flags = kbpgp_1.default['const'].openpgp;\n const params = {\n asp: progressCallback ? new kbpgp_1.default.ASP({ progress_hook: progressCallback }) : undefined,\n userid: `${name} <${email}>`,\n primary: {\n nbits: nbits,\n flags: flags.certify_keys | flags.sign_data | flags.auth | flags.encrypt_comm | flags.encrypt_storage,\n expire_in: 0,\n },\n subkeys: [],\n };\n const identity = await util_1.promisify(kbpgp_1.default.KeyManager.generate)(params);\n await util_1.promisify(identity.sign.bind(identity))({});\n // Export pub key first\n const publicKey = await util_1.promisify(identity.export_pgp_public.bind(identity))({});\n // Finally export priv key\n const privateKey = await util_1.promisify(identity.export_pgp_private.bind(identity))({ passphrase: passphrase });\n // Resolve to parent promise\n const keypair = { private: privateKey, public: publicKey };\n if (replacePrimary) {\n // Set the new keypair\n this.primaryKeyPair = keypair;\n // Set the new identity\n this.primaryIdentity = identity;\n // Overwrite in memory\n const privateKeyPath = path_1.default.join(this.keypairPath, 'private_key');\n const publicKeyPath = path_1.default.join(this.keypairPath, 'public_key');\n await this.fileSystem.promises.writeFile(privateKeyPath, keypair.private);\n await this.fileSystem.promises.writeFile(publicKeyPath, keypair.public);\n // Set metadata\n this.metadata.privateKeyPath = privateKeyPath;\n this.metadata.publicKeyPath = publicKeyPath;\n this.writeMetadata();\n }\n return keypair;\n }\n /**\n * Get the primary keypair\n */\n getKeyPair() {\n return this.primaryKeyPair;\n }\n /**\n * Determines whether public key is loaded or not\n */\n hasPublicKey() {\n return this.primaryKeyPair.public ? true : false;\n }\n /**\n * Get the public key of the primary keypair\n */\n getPublicKey() {\n if (!this.primaryKeyPair.public) {\n throw Error('Public key does not exist in memory');\n }\n return this.primaryKeyPair.public;\n }\n /**\n * Get the private key of the primary keypair\n */\n getPrivateKey() {\n if (!this.primaryKeyPair.private) {\n throw Error('Private key does not exist in memory');\n }\n return this.primaryKeyPair.private;\n }\n /**\n * Loads the keypair into the key manager as the primary identity\n * @param publicKey Public Key\n * @param privateKey Private Key\n */\n loadKeyPair(publicKey, privateKey) {\n this.loadPrivateKey(privateKey);\n this.loadPublicKey(publicKey);\n }\n /**\n * Loads the private key into the primary keypair\n * @param privateKey Private Key\n */\n loadPrivateKey(privateKey) {\n let keyBuffer;\n if (typeof privateKey === 'string') {\n keyBuffer = this.fileSystem.readFileSync(privateKey);\n this.metadata.privateKeyPath = privateKey;\n this.writeMetadata();\n }\n else {\n keyBuffer = privateKey;\n }\n this.primaryKeyPair.private = keyBuffer.toString();\n }\n /**\n * Loads the public key into the primary keypair\n * @param publicKey Public Key\n */\n loadPublicKey(publicKey) {\n let keyBuffer;\n if (typeof publicKey === 'string') {\n keyBuffer = this.fileSystem.readFileSync(publicKey);\n this.metadata.publicKeyPath = publicKey;\n this.writeMetadata();\n }\n else {\n keyBuffer = publicKey;\n }\n this.primaryKeyPair.public = keyBuffer.toString();\n }\n /**\n * Loads the primary identity into the key manager from the existing keypair\n * @param passphrase Passphrase to unlock the private key\n */\n async unlockIdentity(passphrase) {\n const publicKey = this.getPublicKey();\n const privateKey = this.getPrivateKey();\n const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: publicKey });\n await util_1.promisify(identity.merge_pgp_private.bind(identity))({ armored: privateKey });\n if (identity.is_pgp_locked.bind(identity)()) {\n await util_1.promisify(identity.unlock_pgp.bind(identity))({ passphrase: passphrase });\n }\n this.primaryIdentity = identity;\n }\n /**\n * Export the primary private key to a specified location\n * @param path Destination path\n */\n exportPrivateKey(path) {\n this.fileSystem.writeFileSync(path, this.primaryKeyPair.private);\n this.metadata.privateKeyPath = path;\n this.writeMetadata();\n }\n /**\n * Export the primary public key to a specified location\n * @param path Destination path\n */\n exportPublicKey(path) {\n this.fileSystem.writeFileSync(path, this.primaryKeyPair.public);\n this.metadata.publicKeyPath = path;\n this.writeMetadata();\n }\n /**\n * Synchronously generates a new symmetric key and stores it in the key manager\n * @param name Unique name of the generated key\n * @param passphrase Passphrase to derive the key from\n */\n generateKeySync(name, passphrase) {\n const salt = crypto_1.default.randomBytes(32);\n this.derivedKeys[name] = crypto_1.default.pbkdf2Sync(passphrase, salt, 10000, 256 / 8, 'sha256');\n return this.derivedKeys[name];\n }\n /**\n * Asynchronously Generates a new symmetric key and stores it in the key manager\n * @param name Unique name of the generated key\n * @param passphrase Passphrase to derive the key from\n */\n async generateKey(name, passphrase) {\n const salt = crypto_1.default.randomBytes(32);\n this.derivedKeys[name] = await util_1.promisify(crypto_1.default.pbkdf2)(passphrase, salt, 10000, 256 / 8, 'sha256');\n return this.derivedKeys[name];\n }\n /**\n * Synchronously imports an existing key from file or Buffer\n * @param name Unique name of the imported key\n * @param key Key to be imported\n */\n importKeySync(name, key) {\n if (typeof key === 'string') {\n this.derivedKeys[name] = this.fileSystem.readFileSync(key);\n }\n else {\n this.derivedKeys[name] = key;\n }\n }\n /**\n * Asynchronously imports an existing key from file or Buffer\n * @param name Unique name of the imported key\n * @param key Key to be imported\n */\n async importKey(name, key) {\n if (typeof key === 'string') {\n this.derivedKeys[name] = await this.fileSystem.promises.readFile(key);\n }\n else {\n this.derivedKeys[name] = key;\n }\n }\n /**\n * Synchronously exports an existing key from file or Buffer\n * @param name Name of the key to be exported\n * @param dest Destination path\n * @param createPath If set to true, the path is recursively created\n */\n exportKeySync(name, dest, createPath) {\n if (!this.derivedKeys.has(name)) {\n throw Error(`There is no key loaded for name: ${name}`);\n }\n if (createPath) {\n this.fileSystem.mkdirSync(path_1.default.dirname(dest), { recursive: true });\n }\n this.fileSystem.writeFileSync(dest, this.derivedKeys[name]);\n }\n /**\n * Asynchronously exports an existing key from file or Buffer\n * @param name Name of the key to be exported\n * @param dest Destination path\n * @param createPath If set to true, the path is recursively created\n */\n async exportKey(name, dest, createPath) {\n if (!this.derivedKeys.has(name)) {\n throw Error(`There is no key loaded for name: ${name}`);\n }\n if (createPath) {\n await this.fileSystem.promises.mkdir(path_1.default.dirname(dest), { recursive: true });\n }\n await this.fileSystem.promises.writeFile(dest, this.derivedKeys[name]);\n }\n /**\n * Loads an identity from the given public key\n * @param publicKey Buffer containing the public key\n */\n async getIdentityFromPublicKey(publicKey) {\n const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: publicKey });\n return identity;\n }\n /**\n * Loads an identity from the given private key\n * @param publicKey Buffer containing the public key\n */\n async getIdentityFromPrivateKey(privateKey, passphrase) {\n const identity = await util_1.promisify(kbpgp_1.default.KeyManager.import_from_armored_pgp)({ armored: privateKey });\n if (identity.is_pgp_locked()) {\n await util_1.promisify(identity.unlock_pgp)({ passphrase: passphrase });\n }\n return identity;\n }\n /**\n * Signs the given data with the provided key or the primary key if none is specified\n * @param data Buffer or file containing the data to be signed\n * @param privateKey Buffer containing the key to sign with. Defaults to primary private key if no key is given.\n * @param keyPassphrase Required if privateKey is provided.\n */\n async signData(data, privateKey, keyPassphrase) {\n let resolvedIdentity;\n if (privateKey) {\n if (!keyPassphrase) {\n throw Error('passphrase for private key was not provided');\n }\n resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase);\n }\n else if (this.primaryIdentity) {\n resolvedIdentity = this.primaryIdentity;\n }\n else {\n throw Error('key pair is not loaded');\n }\n if (this.useWebWorkers && this.workerPool) {\n const workerResponse = await this.workerPool.queue(async (workerCrypto) => {\n return await workerCrypto.signData(data, resolvedIdentity);\n });\n return workerResponse;\n }\n else {\n const params = {\n msg: data.toString(),\n sign_with: resolvedIdentity,\n };\n const result_string = await util_1.promisify(kbpgp_1.default.box)(params);\n return Buffer.from(result_string);\n }\n }\n /**\n * Signs the given file with the provided key or the primary key if none is specified\n * @param filePath Path to file containing the data to be signed\n * @param privateKey The key to sign with. Defaults to primary public key if no key is given.\n * @param keyPassphrase Required if privateKey is provided.\n */\n async signFile(filePath, privateKey, keyPassphrase) {\n // Get key if provided\n let keyBuffer;\n if (privateKey) {\n if (typeof privateKey === 'string') {\n // Path\n // Read in from fs\n keyBuffer = this.fileSystem.readFileSync(privateKey);\n }\n else {\n // Buffer\n keyBuffer = privateKey;\n }\n }\n // Read file into buffer\n const buffer = this.fileSystem.readFileSync(filePath);\n // Sign the buffer\n const signedBuffer = await this.signData(buffer, keyBuffer, keyPassphrase);\n // Write buffer to signed file\n const signedPath = `${filePath}.sig`;\n this.fileSystem.writeFileSync(signedPath, signedBuffer);\n return signedPath;\n }\n /**\n * Verifies the given data with the provided key or the primary key if none is specified\n * @param data Buffer or file containing the data to be verified\n * @param signature The PGP signature\n * @param publicKey Buffer containing the key to verify with. Defaults to primary public key if no key is given.\n */\n async verifyData(data, signature, publicKey) {\n const ring = new kbpgp_1.default.keyring.KeyRing();\n let resolvedIdentity;\n if (publicKey) {\n resolvedIdentity = await this.getIdentityFromPublicKey(publicKey);\n }\n else if (this.primaryIdentity) {\n resolvedIdentity = this.primaryIdentity;\n }\n else {\n throw Error('key pair is not loaded');\n }\n ring.add_key_manager(resolvedIdentity);\n if (this.useWebWorkers && this.workerPool) {\n const workerResponse = await this.workerPool.queue(async (workerCrypto) => {\n return await workerCrypto.verifyData(data, signature, resolvedIdentity);\n });\n return workerResponse;\n }\n else {\n const params = {\n armored: signature,\n data: data,\n keyfetch: ring,\n };\n const literals = await util_1.promisify(kbpgp_1.default.unbox)(params);\n // Get the identity that signed the data if any\n let dataSigner = literals[0].get_data_signer();\n // Retrieve the key manager associated with that data signer\n let keyManager;\n if (dataSigner) {\n keyManager = dataSigner.get_key_manager();\n }\n // If we know the pgp finger print then we say the data is verified.\n // Otherwise it is unverified.\n if (keyManager) {\n if (keyManager.get_pgp_fingerprint()) {\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return false;\n }\n }\n }\n /**\n * Verifies the given file with the provided key or the primary key if none is specified\n * @param filePath Path to file containing the data to be verified\n * @param signaturePath The path to the file containing the PGP signature\n * @param publicKey Buffer containing the key to verify with. Defaults to primary public key if no key is given.\n */\n async verifyFile(filePath, signaturePath, publicKey) {\n // Get key if provided\n let keyBuffer;\n if (publicKey) {\n if (typeof publicKey === 'string') {\n // Path\n // Read in from fs\n keyBuffer = this.fileSystem.readFileSync(publicKey);\n }\n else {\n // Buffer\n keyBuffer = publicKey;\n }\n }\n // Read in file buffer and signature\n const fileBuffer = this.fileSystem.readFileSync(filePath);\n const signatureBuffer = this.fileSystem.readFileSync(signaturePath);\n const isVerified = await this.verifyData(fileBuffer, signatureBuffer, keyBuffer);\n return isVerified;\n }\n /**\n * Encrypts the given data for a specific public key\n * @param data The data to be encrypted\n * @param publicKey The key to encrypt for\n */\n async encryptData(data, publicKey) {\n let resolvedIdentity;\n if (publicKey) {\n resolvedIdentity = await this.getIdentityFromPublicKey(publicKey);\n }\n else if (this.primaryIdentity) {\n resolvedIdentity = this.primaryIdentity;\n }\n else {\n throw Error(`Identity could not be resolved for encrypting`);\n }\n if (this.useWebWorkers && this.workerPool) {\n const workerResponse = await this.workerPool.queue(async (workerCrypto) => {\n return await workerCrypto.encryptData(data, resolvedIdentity);\n });\n return workerResponse;\n }\n else {\n const params = {\n msg: data,\n encrypt_for: resolvedIdentity,\n };\n const result_string = await util_1.promisify(kbpgp_1.default.box)(params);\n return result_string;\n }\n }\n /**\n * Decrypts the given data with the provided key or the primary key if none is given\n * @param data The data to be decrypted\n * @param privateKey The key to decrypt with. Defaults to primary private key if no key is given.\n * @param keyPassphrase Required if privateKey is provided.\n */\n async decryptData(data, privateKey, keyPassphrase) {\n var ring = new kbpgp_1.default.keyring.KeyRing();\n let resolvedIdentity;\n if (privateKey) {\n if (keyPassphrase) {\n resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase);\n }\n else {\n throw Error('A key passphrase must be supplied if a privateKey is specified');\n }\n }\n else if (this.primaryIdentity) {\n resolvedIdentity = this.primaryIdentity;\n }\n else {\n throw Error('no identity available for decrypting');\n }\n if (this.useWebWorkers && this.workerPool) {\n const workerResponse = await this.workerPool.queue(async (workerCrypto) => {\n return await workerCrypto.decryptData(data, resolvedIdentity);\n });\n return workerResponse;\n }\n else {\n ring.add_key_manager(resolvedIdentity);\n const params = {\n armored: data.toString(),\n keyfetch: ring,\n };\n const literals = await util_1.promisify(kbpgp_1.default.unbox)(params);\n const decryptedData = Buffer.from(literals[0].toString());\n return decryptedData;\n }\n }\n /////////\n // PKI //\n /////////\n get PKIInfo() {\n return this.pkiInfo;\n }\n loadPKIInfo(key, cert, caCert, writeToFile = false) {\n if (key) {\n this.pkiInfo.key = key;\n }\n if (cert) {\n this.pkiInfo.cert = cert;\n }\n if (caCert) {\n this.pkiInfo.caCert = caCert;\n }\n if (writeToFile) {\n // Store in the metadata path folder\n const storagePath = path_1.default.dirname(this.metadataPath);\n if (key) {\n this.metadata.pkiKeyPath = path_1.default.join(storagePath, 'pki_private_key');\n fs_1.default.writeFileSync(this.metadata.pkiKeyPath, key);\n }\n if (cert) {\n this.metadata.pkiCertPath = path_1.default.join(storagePath, 'pki_cert');\n fs_1.default.writeFileSync(this.metadata.pkiCertPath, cert);\n }\n if (caCert) {\n this.metadata.caCertPath = path_1.default.join(storagePath, 'ca_cert');\n fs_1.default.writeFileSync(this.metadata.caCertPath, caCert);\n }\n }\n }\n /* ============ HELPERS =============== */\n /**\n * Get the key for a given name\n * @param name The unique name of the desired key\n */\n getKey(name) {\n return this.derivedKeys[name];\n }\n /**\n * Determines if the Key Manager has a certain key\n * @param name The unique name of the desired key\n */\n hasKey(name) {\n if (this.derivedKeys[name]) {\n return true;\n }\n return false;\n }\n writeMetadata() {\n const metadata = JSON.stringify(this.metadata);\n this.fileSystem.writeFileSync(this.metadataPath, metadata);\n }\n loadMetadata() {\n // Check if file exists\n if (this.fileSystem.existsSync(this.metadataPath)) {\n const metadata = this.fileSystem.readFileSync(this.metadataPath).toString();\n this.metadata = JSON.parse(metadata);\n }\n }\n}\nexports.default = KeyManager;\n","module.exports = require(\"kbpgp\");","module.exports = require(\"util\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst grpc = __importStar(require(\"@grpc/grpc-js\"));\nconst GitClient_1 = __importDefault(require(\"../git/GitClient\"));\nconst GitBackend_1 = __importDefault(require(\"../git/GitBackend\"));\nconst Peer_1 = require(\"../../../proto/js/Peer\");\nconst utils_1 = require(\"../utils\");\nconst PeerInfo_1 = __importStar(require(\"../peers/PeerInfo\"));\nconst MulticastBroadcaster_1 = __importDefault(require(\"../peers/MulticastBroadcaster\"));\nconst Git_grpc_pb_1 = require(\"../../../proto/compiled/Git_grpc_pb\");\nconst Git_pb_1 = require(\"../../../proto/compiled/Git_pb\");\nconst keybaseDiscovery = {\n name: 'Keybase',\n findUser: async (handle, service) => {\n const url = `https://keybase.io/_/api/1.0/user/lookup.json?${service}=${handle}`;\n try {\n const response = await fetch(url);\n const data = await response.json();\n const pubKey = data.them[0].public_keys.primary.bundle;\n return pubKey;\n }\n catch (err) {\n throw Error(`User was not found: ${err.message}`);\n }\n },\n};\nclass PeerManager {\n constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager, vaultManager, peerInfo, socialDiscoveryServices = []) {\n var _a;\n this.metadata = { localPeerInfo: null };\n this.serverStarted = false;\n this.fileSystem = fileSystem;\n this.fileSystem.mkdirSync(polykeyPath, { recursive: true });\n this.metadataPath = path_1.default.join(polykeyPath, '.peerMetadata');\n // Set given variables\n this.keyManager = keyManager;\n this.socialDiscoveryServices = socialDiscoveryServices;\n // Load metadata with peer info\n this.loadMetadata();\n // Load peer store and local peer info\n if (peerInfo) {\n this.localPeerInfo = peerInfo;\n this.writeMetadata();\n }\n else if (this.metadata.localPeerInfo) {\n this.localPeerInfo = this.metadata.localPeerInfo;\n }\n else if (this.keyManager.hasPublicKey()) {\n this.localPeerInfo = new PeerInfo_1.default(this.keyManager.getPublicKey());\n }\n this.peerStore = new Map();\n this.socialDiscoveryServices = [];\n this.socialDiscoveryServices.push(keybaseDiscovery);\n for (const service of socialDiscoveryServices) {\n this.socialDiscoveryServices.push(service);\n }\n this.multicastBroadcaster = new MulticastBroadcaster_1.default(this.addPeer, this.localPeerInfo, this.keyManager);\n this.peerConnections = new Map();\n /////////////////\n // GRPC Server //\n /////////////////\n this.gitBackend = new GitBackend_1.default(polykeyPath, vaultManager);\n this.server = new grpc.Server();\n // Add service\n this.server.addService(Git_grpc_pb_1.GitServerService, {\n requestInfo: this.requestInfo.bind(this),\n requestPack: this.requestPack.bind(this),\n });\n // Create the server credentials. SSL only if ca cert exists\n const pkiInfo = this.keyManager.PKIInfo;\n if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) {\n this.credentials = grpc.ServerCredentials.createSsl(pkiInfo.caCert, [\n {\n private_key: pkiInfo.key,\n cert_chain: pkiInfo.cert,\n },\n ], true);\n }\n else {\n this.credentials = grpc.ServerCredentials.createInsecure();\n }\n this.server.bindAsync(`0.0.0.0:${(_a = process.env.PK_PORT) !== null && _a !== void 0 ? _a : 0}`, this.credentials, (err, boundPort) => {\n if (err) {\n throw err;\n }\n else {\n const address = new PeerInfo_1.Address('localhost', boundPort.toString());\n this.server.start();\n this.localPeerInfo.connect(address);\n this.serverStarted = true;\n }\n });\n }\n async requestInfo(call, callback) {\n const infoRequest = call.request;\n const vaultName = infoRequest.getVaultname();\n const infoReply = new Git_pb_1.InfoReply();\n infoReply.setVaultname(vaultName);\n infoReply.setBody(await this.gitBackend.handleInfoRequest(vaultName));\n callback(null, infoReply);\n }\n async requestPack(call, callback) {\n const packRequest = call.request;\n const vaultName = packRequest.getVaultname();\n const body = Buffer.from(packRequest.getBody_asB64(), 'base64');\n const reply = new Git_pb_1.PackReply();\n reply.setVaultname(vaultName);\n reply.setBody(await this.gitBackend.handlePackRequest(vaultName, body));\n callback(null, reply);\n }\n ////////////////\n // Peer store //\n ////////////////\n /**\n * Get the peer info of the current keynode\n */\n getLocalPeerInfo() {\n return this.localPeerInfo;\n }\n /**\n * Set the address of the active server\n * @param adress Address of active server\n */\n connectLocalPeerInfo(address) {\n this.localPeerInfo.connect(address);\n }\n /**\n * Add a peer's info to the peerStore\n * @param peerInfo Info of the peer to be added\n */\n addPeer(peerInfo) {\n this.peerStore.set(peerInfo.publicKey, peerInfo);\n }\n /**\n * Retrieves a peer for the given public key\n * @param publicKey Public key of the desired peer\n */\n getPeer(publicKey) {\n var _a;\n return (_a = this.peerStore.get(publicKey)) !== null && _a !== void 0 ? _a : null;\n }\n /**\n * Determines if the peerStore contains the desired peer\n * @param publicKey Public key of the desired peer\n */\n hasPeer(pubKey) {\n return this.peerStore.has(pubKey);\n }\n //////////////////////\n // Social discovery //\n //////////////////////\n /**\n * Finds an existing peer using multicast peer discovery\n * @param publicKey Public key of the desired peer\n */\n async findPubKey(publicKey) {\n return new Promise((resolve, reject) => {\n this.multicastBroadcaster.requestPeerContact(publicKey);\n this.multicastBroadcaster.on('found', (peerInfo) => {\n if (peerInfo.publicKey == publicKey) {\n resolve(peerInfo);\n }\n });\n this.multicastBroadcaster.on('timeout', (timedOutPubKey) => {\n if (timedOutPubKey == publicKey) {\n reject('The broadcaster stopped looking');\n }\n });\n });\n }\n /**\n * Finds an existing peer given a social service and handle\n * @param handle Username or handle of the user (e.g. @john-smith)\n * @param service Service on which to search for the user (e.g. github)\n */\n async findSocialUser(handle, service) {\n const tasks = [];\n for (const socialDiscovery of this.socialDiscoveryServices) {\n try {\n tasks.push(socialDiscovery.findUser(handle, service));\n }\n catch (error) {\n console.log(`Could not find user on this discovery service: ${socialDiscovery.name}`);\n }\n }\n const pubKeyOrFail = await utils_1.firstPromiseFulfilled(tasks);\n if (pubKeyOrFail.length > 1) {\n throw Error('Could not find public key from services');\n }\n const pubKeyFound = pubKeyOrFail[0];\n const peerInfo = await this.findPubKey(pubKeyFound);\n return peerInfo;\n }\n ///////////////////////\n // Peers Connections //\n ///////////////////////\n /**\n * Get a secure connection to the peer\n * @param peer Public key of an existing peer or address of new peer\n */\n connectToPeer(peer) {\n var _a;\n // Throw error if trying to connect to self\n if (peer == this.localPeerInfo.connectedAddr || peer == this.localPeerInfo.publicKey) {\n throw Error('Cannot connect to self');\n }\n let address;\n if (typeof peer == 'string') {\n const existingSocket = this.peerConnections.get(peer);\n if (existingSocket) {\n return existingSocket;\n }\n const peerAddress = (_a = this.getPeer(peer)) === null || _a === void 0 ? void 0 : _a.connectedAddr;\n if (peerAddress) {\n address = peerAddress;\n }\n else {\n throw Error('Peer does not exist in peer store');\n }\n }\n else {\n address = peer;\n }\n const conn = new GitClient_1.default(address, this.keyManager);\n if (typeof peer == 'string') {\n this.peerConnections.set(peer, conn);\n }\n return conn;\n }\n /* ============ HELPERS =============== */\n writeMetadata() {\n var _a;\n const peerInfo = this.localPeerInfo;\n const metadata = Peer_1.peer.PeerInfoMessage.encode({\n addresses: peerInfo.AdressStringList,\n connectedAddr: (_a = peerInfo.connectedAddr) === null || _a === void 0 ? void 0 : _a.toString(),\n pubKey: peerInfo.publicKey,\n }).finish();\n this.fileSystem.writeFileSync(this.metadataPath, metadata);\n }\n loadMetadata() {\n // Check if file exists\n if (this.fileSystem.existsSync(this.metadataPath)) {\n const metadata = this.fileSystem.readFileSync(this.metadataPath);\n const { addresses, connectedAddr, pubKey } = Peer_1.peer.PeerInfoMessage.decode(metadata);\n this.localPeerInfo = new PeerInfo_1.default(pubKey, addresses, connectedAddr);\n }\n }\n}\nexports.default = PeerManager;\n","\"use strict\";\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst grpc = __importStar(require(\"@grpc/grpc-js\"));\nconst Git_grpc_pb_1 = require(\"../../../proto/compiled/Git_grpc_pb\");\nconst Git_pb_1 = require(\"../../../proto/compiled/Git_pb\");\n/**\n * Responsible for converting HTTP messages from isomorphic-git into requests and sending them to a specific peer.\n */\nclass GitClient {\n constructor(address, keyManager) {\n const pkiInfo = keyManager.PKIInfo;\n if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) {\n this.credentials = grpc.credentials.createSsl(pkiInfo.caCert, pkiInfo.key, pkiInfo.cert);\n }\n else {\n this.credentials = grpc.credentials.createInsecure();\n }\n this.client = new Git_grpc_pb_1.GitServerClient(address.toString(), this.credentials);\n }\n /**\n * The custom http request method to feed into isomorphic-git's [custom http object](https://isomorphic-git.org/docs/en/http)\n */\n async request({ url, method, headers, body, onProgress }) {\n // eslint-disable-next-line\n return new Promise(async (resolve, reject) => {\n const u = new URL(url);\n // Parse request\n if (method == 'GET') {\n // Info request\n const match = u.pathname.match(/\\/(.+)\\/info\\/refs$/);\n if (!match || /\\.\\./.test(match[1])) {\n reject(new Error('Error'));\n }\n const vaultName = match[1];\n const infoResponse = await this.requestInfo(vaultName);\n resolve({\n url: url,\n method: method,\n statusCode: 200,\n statusMessage: 'OK',\n body: this.iteratorFromData(infoResponse),\n headers: headers,\n });\n }\n else if (method == 'POST') {\n // Info request\n const match = u.pathname.match(/\\/(.+)\\/git-(.+)/);\n if (!match || /\\.\\./.test(match[1])) {\n reject(new Error('Error'));\n }\n const vaultName = match[1];\n const packResponse = await this.requestPack(vaultName, body[0]);\n resolve({\n url: url,\n method: method,\n statusCode: 200,\n statusMessage: 'OK',\n body: this.iteratorFromData(packResponse),\n headers: headers,\n });\n }\n else {\n reject(new Error('Method not supported'));\n }\n });\n }\n // ==== HELPER METHODS ==== //\n /**\n * Requests remote info from the connected peer for the named vault.\n * @param vaultName Name of the desired vault\n */\n async requestInfo(vaultName) {\n return new Promise((resolve, reject) => {\n const request = new Git_pb_1.InfoRequest();\n request.setVaultname(vaultName);\n this.client.requestInfo(request, function (err, response) {\n if (err) {\n reject(err);\n }\n else {\n resolve(Buffer.from(response.getBody_asB64(), 'base64'));\n }\n });\n });\n }\n /**\n * Requests a pack from the connected peer for the named vault.\n * @param vaultName Name of the desired vault\n */\n async requestPack(vaultName, body) {\n return new Promise((resolve, reject) => {\n const request = new Git_pb_1.PackRequest();\n request.setVaultname(vaultName);\n request.setBody(body);\n this.client.requestPack(request, function (err, response) {\n if (err) {\n reject(err);\n }\n else {\n resolve(Buffer.from(response.getBody_asB64(), 'base64'));\n }\n });\n });\n }\n /**\n * Converts a buffer into an iterator expected by isomorphic git.\n * @param data Data to be turned into an iterator\n */\n iteratorFromData(data) {\n let ended = false;\n return {\n next() {\n return new Promise((resolve, reject) => {\n if (ended) {\n return resolve({ done: true });\n }\n else {\n ended = true;\n resolve({ value: data, done: false });\n }\n });\n },\n };\n }\n}\nexports.default = GitClient;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst path_1 = __importDefault(require(\"path\"));\nconst readable_stream_1 = require(\"readable-stream\");\nconst uploadPack_1 = __importDefault(require(\"./upload-pack/uploadPack\"));\nconst GitSideBand_1 = __importDefault(require(\"./side-band/GitSideBand\"));\nconst packObjects_1 = __importDefault(require(\"./pack-objects/packObjects\"));\n// Here is the protocol git outlines for sending pack files over http:\n// https://git-scm.com/docs/pack-protocol/2.17.0\n// https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt\n// This should be consulted in developing our upload pack implementation\n// This git backend (as well as HttpDuplex class) is heavily inspired by node-git-server:\n// https://github.com/gabrielcsapo/node-git-server\n// We need someway to notify other agents about what vaults we have based on some type of authorisation because they don't explicitly know about them\nclass GitBackend {\n constructor(polykeyPath, vaultManager) {\n this.polykeyPath = polykeyPath;\n this.vaultManager = vaultManager;\n }\n /**\n * Find out whether vault exists.\n * @param vaultName Name of vault to check\n * @param publicKey Public key of peer trying to access vault\n */\n exists(vaultName, publicKey) {\n try {\n const vault = this.vaultManager.getVault(vaultName);\n if (vault) {\n return vault.peerCanAccess(publicKey);\n }\n return false;\n }\n catch (error) {\n return false;\n }\n }\n async handleInfoRequest(vaultName) {\n var _a;\n // Only handle upload-pack for now\n const service = 'upload-pack';\n const connectingPublicKey = '';\n const responseBuffers = [];\n if (!this.exists(vaultName, connectingPublicKey)) {\n throw Error('Vault does not exist');\n }\n else {\n responseBuffers.push(Buffer.from(this.createGitPacketLine('# service=git-' + service + '\\n')));\n responseBuffers.push(Buffer.from('0000'));\n const fileSystem = (_a = this.vaultManager.getVault(vaultName)) === null || _a === void 0 ? void 0 : _a.EncryptedFS;\n const buffers = await uploadPack_1.default(fileSystem, path_1.default.join(this.polykeyPath, vaultName), undefined, true);\n const buffersToWrite = buffers !== null && buffers !== void 0 ? buffers : [];\n responseBuffers.push(...buffersToWrite);\n }\n return Buffer.concat(responseBuffers);\n }\n async handlePackRequest(vaultName, body) {\n // eslint-disable-next-line\n return new Promise(async (resolve, reject) => {\n var _a;\n const responseBuffers = [];\n // Check if vault exists\n const connectingPublicKey = '';\n if (!this.exists(vaultName, connectingPublicKey)) {\n throw Error('Vault does not exist');\n }\n const fileSystem = (_a = this.vaultManager.getVault(vaultName)) === null || _a === void 0 ? void 0 : _a.EncryptedFS;\n if (fileSystem) {\n if (body.toString().slice(4, 8) == 'want') {\n const wantedObjectId = body.toString().slice(9, 49);\n const packResult = await packObjects_1.default(fileSystem, path_1.default.join(this.polykeyPath, vaultName), [wantedObjectId], undefined);\n // This the 'wait for more data' line as I understand it\n responseBuffers.push(Buffer.from('0008NAK\\n'));\n // This is to get the side band stuff working\n const readable = new readable_stream_1.PassThrough();\n const progressStream = new readable_stream_1.PassThrough();\n const sideBand = GitSideBand_1.default.mux('side-band-64', readable, packResult.packstream, progressStream, []);\n sideBand.on('data', (data) => {\n responseBuffers.push(data);\n });\n sideBand.on('end', () => {\n resolve(Buffer.concat(responseBuffers));\n });\n sideBand.on('error', (err) => {\n reject(err);\n });\n // Write progress to the client\n progressStream.write(Buffer.from('0014progress is at 50%\\n'));\n progressStream.end();\n }\n }\n });\n }\n // ============ Helper functions ============ //\n createGitPacketLine(line) {\n const hexPrefix = (4 + line.length).toString(16);\n return Array(4 - hexPrefix.length + 1).join('0') + hexPrefix + line;\n }\n}\nexports.default = GitBackend;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst path_1 = __importDefault(require(\"path\"));\nconst GitPktLine_1 = __importDefault(require(\"./GitPktLine\"));\nconst GitRefManager_1 = __importDefault(require(\"./GitRefManager\"));\nasync function writeRefsAdResponse({ capabilities, refs, symrefs }) {\n const stream = [];\n // Compose capabilities string\n let syms = '';\n for (const [key, value] of Object.entries(symrefs)) {\n syms += `symref=${key}:${value} `;\n }\n let caps = `\\x00${[...capabilities].join(' ')} ${syms}agent=git/isomorphic-git@1.4.0`;\n // stream.write(GitPktLine.encode(`# service=${service}\\n`))\n // stream.write(GitPktLine.flush())\n // Note: In the edge case of a brand new repo, zero refs (and zero capabilities)\n // are returned.\n for (const [key, value] of Object.entries(refs)) {\n stream.push(GitPktLine_1.default.encode(`${value} ${key}${caps}\\n`));\n caps = '';\n }\n stream.push(GitPktLine_1.default.flush());\n return stream;\n}\nasync function uploadPack(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), advertiseRefs = false) {\n try {\n if (advertiseRefs) {\n // Send a refs advertisement\n const capabilities = ['side-band-64k'];\n let keys = await GitRefManager_1.default.listRefs(fileSystem, gitdir, 'refs');\n keys = keys.map((ref) => `refs/${ref}`);\n const refs = {};\n keys.unshift('HEAD'); // HEAD must be the first in the list\n for (const key of keys) {\n refs[key] = await GitRefManager_1.default.resolve(fileSystem, gitdir, key);\n }\n const symrefs = {};\n symrefs['HEAD'] = await GitRefManager_1.default.resolve(fileSystem, gitdir, 'HEAD', 2);\n return writeRefsAdResponse({\n capabilities,\n refs,\n symrefs,\n });\n }\n }\n catch (err) {\n err.caller = 'git.uploadPack';\n throw err;\n }\n}\nexports.default = uploadPack;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass GitPackedRefs {\n constructor(text) {\n this.refs = new Map();\n this.parsedConfig = [];\n if (text) {\n let key;\n this.parsedConfig = text\n .trim()\n .split('\\n')\n .map((line) => {\n if (/^\\s*#/.test(line)) {\n return { line: line, comment: true };\n }\n const i = line.indexOf(' ');\n if (line.startsWith('^')) {\n // This is a oid for the commit associated with the annotated tag immediately preceding this line.\n // Trim off the '^'\n const value = line.slice(1);\n // The tagname^{} syntax is based on the output of `git show-ref --tags -d`\n this.refs.set(key + '^{}', value);\n return { line: line, ref: key, peeled: value };\n }\n else {\n // This is an oid followed by the ref name\n const value = line.slice(0, i);\n key = line.slice(i + 1);\n this.refs.set(key, value);\n return { line: line, ref: key, oid: value };\n }\n });\n }\n return this;\n }\n static from(text) {\n return new GitPackedRefs(text);\n }\n}\nexports.default = GitPackedRefs;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/*\nIf 'side-band' or 'side-band-64k' capabilities have been specified by\nthe client, the server will send the packfile data multiplexed.\n\nEach packet starting with the packet-line length of the amount of data\nthat follows, followed by a single byte specifying the sideband the\nfollowing data is coming in on.\n\nIn 'side-band' mode, it will send up to 999 data bytes plus 1 control\ncode, for a total of up to 1000 bytes in a pkt-line. In 'side-band-64k'\nmode it will send up to 65519 data bytes plus 1 control code, for a\ntotal of up to 65520 bytes in a pkt-line.\n\nThe sideband byte will be a '1', '2' or a '3'. Sideband '1' will contain\npackfile data, sideband '2' will be used for progress information that the\nclient will generally print to stderr and sideband '3' is used for error\ninformation.\n\nIf no 'side-band' capability was specified, the server will stream the\nentire packfile without multiplexing.\n*/\nconst buffer_1 = require(\"buffer\");\nconst readable_stream_1 = require(\"readable-stream\");\nconst GitPktLine_1 = __importDefault(require(\"../upload-pack/GitPktLine\"));\nfunction splitBuffer(buffer, maxBytes) {\n const result = [];\n let index = 0;\n while (index < buffer.length) {\n const buf = buffer.slice(index, index + maxBytes);\n result.push(buf);\n index += buf.length;\n }\n result.push(buffer.slice(index));\n return result;\n}\nclass GitSideBand {\n static demux(input) {\n let read = GitPktLine_1.default.streamReader(input);\n // And now for the ridiculous side-band or side-band-64k protocol\n let packetlines = new readable_stream_1.PassThrough();\n let packfile = new readable_stream_1.PassThrough();\n let progress = new readable_stream_1.PassThrough();\n // TODO: Use a proper through stream?\n const nextBit = async function () {\n let line = await read();\n // Skip over flush packets\n if (line === null)\n return nextBit();\n // A made up convention to signal there's no more to read.\n if (line === true) {\n packetlines.end();\n progress.end();\n packfile.end();\n return;\n }\n // Examine first byte to determine which output \"stream\" to use\n switch (line[0]) {\n case 1: // pack data\n packfile.write(line.slice(1));\n break;\n case 2: // progress message\n progress.write(line.slice(1));\n break;\n case 3: // fatal error message just before stream aborts\n // eslint-disable-next-line\n const error = line.slice(1);\n progress.write(error);\n packfile.destroy(new Error(error.toString('utf8')));\n return;\n default:\n // Not part of the side-band-64k protocol\n packetlines.write(line.slice(0));\n }\n // Careful not to blow up the stack.\n // I think Promises in a tail-call position should be OK.\n nextBit();\n };\n nextBit();\n return {\n packetlines,\n packfile,\n progress,\n };\n }\n static mux(protocol, // 'side-band' or 'side-band-64k'\n packetlines, packfile, progress, error) {\n const MAX_PACKET_LENGTH = protocol === 'side-band-64k' ? 999 : 65519;\n let output = new readable_stream_1.PassThrough();\n packetlines.on('data', (data) => {\n if (data === null) {\n output.write(GitPktLine_1.default.flush());\n }\n else {\n output.write(GitPktLine_1.default.encode(data));\n }\n });\n let packfileWasEmpty = true;\n let packfileEnded = false;\n let progressEnded = false;\n let errorEnded = true;\n let goodbye = buffer_1.Buffer.concat([GitPktLine_1.default.encode(buffer_1.Buffer.from('010A', 'hex')), GitPktLine_1.default.flush()]);\n packfile\n .on('data', (data) => {\n packfileWasEmpty = false;\n const buffers = splitBuffer(data, MAX_PACKET_LENGTH);\n for (const buffer of buffers) {\n output.write(GitPktLine_1.default.encode(buffer_1.Buffer.concat([buffer_1.Buffer.from('01', 'hex'), buffer])));\n }\n })\n .on('end', () => {\n packfileEnded = true;\n if (!packfileWasEmpty)\n output.write(goodbye);\n if (progressEnded && errorEnded)\n output.end();\n });\n progress\n .on('data', (data) => {\n const buffers = splitBuffer(data, MAX_PACKET_LENGTH);\n for (const buffer of buffers) {\n output.write(GitPktLine_1.default.encode(buffer_1.Buffer.concat([buffer_1.Buffer.from('02', 'hex'), buffer])));\n }\n })\n .on('end', () => {\n progressEnded = true;\n if (packfileEnded && errorEnded)\n output.end();\n });\n // error\n // .on('data', data => {\n // const buffers = splitBuffer(data, MAX_PACKET_LENGTH)\n // for (const buffer of buffers) {\n // output.write(\n // GitPktLine.encode(Buffer.concat([Buffer.from('03', 'hex'), buffer]))\n // )\n // }\n // })\n // .on('end', () => {\n // errorEnded = true\n // if (progressEnded && packfileEnded) output.end()\n // })\n return output;\n }\n}\nexports.default = GitSideBand;\n","module.exports = require(\"buffer\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst pako_1 = __importDefault(require(\"pako\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst log_1 = __importDefault(require(\"./log\"));\nconst GitTree_1 = __importDefault(require(\"./GitTree\"));\nconst sha_js_1 = __importDefault(require(\"sha.js\"));\nconst GitCommit_1 = __importDefault(require(\"./GitCommit\"));\nconst readable_stream_1 = require(\"readable-stream\");\nconst GitObjectManager_1 = __importDefault(require(\"./GitObjectManager\"));\nconst types = {\n commit: 0b0010000,\n tree: 0b0100000,\n blob: 0b0110000,\n tag: 0b1000000,\n ofs_delta: 0b1100000,\n ref_delta: 0b1110000,\n};\n/**\n * Create a packfile stream\n *\n * @link https://isomorphic-git.github.io/docs/packObjects.html\n */\nasync function packObjects(fileSystem, dir, refs, depth, haves) {\n const gitdir = path_1.default.join(dir, '.git');\n let oids = new Set();\n let shallows = new Set();\n let unshallows = new Set();\n let acks = [];\n haves = haves ? haves : [];\n const emitter = undefined;\n const since = undefined;\n for (const ref of refs) {\n try {\n let commits = await log_1.default(fileSystem, dir, gitdir, emitter, ref, depth, since);\n let oldshallows = [];\n for (let i = 0; i < commits.length; i++) {\n let commit = commits[i];\n if (haves.includes(commit.oid)) {\n acks.push({\n oid: ref,\n });\n break;\n }\n oids.add(commit.oid);\n if (i === commits.length - 1) {\n if (!oldshallows.includes(commit.oid) && (depth !== undefined || since !== undefined)) {\n console.log('make it shallow', commit.oid);\n shallows.add(commit.oid);\n }\n }\n else if (oldshallows.includes(commit.oid)) {\n console.log('make it unshallow', commit.oid);\n unshallows.add(commit.oid);\n }\n }\n }\n catch (err) {\n console.log(err);\n // oh well.\n }\n }\n let objects = await listObjects(fileSystem, dir, gitdir, Array.from(oids));\n let packstream = new readable_stream_1.PassThrough();\n pack(fileSystem, dir, undefined, [...objects], packstream);\n return { packstream, shallows, unshallows, acks };\n}\nasync function listObjects(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), oids) {\n let commits = new Set();\n let trees = new Set();\n let blobs = new Set();\n // We don't do the purest simplest recursion, because we can\n // avoid reading Blob objects entirely since the Tree objects\n // tell us which oids are Blobs and which are Trees. And we\n // do not need to recurse through commit parents.\n async function walk(oid) {\n let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid);\n if (type === 'commit') {\n commits.add(oid);\n let commit = GitCommit_1.default.from(object);\n let tree = commit.headers().tree;\n await walk(tree);\n }\n else if (type === 'tree') {\n trees.add(oid);\n let tree = GitTree_1.default.from(object);\n for (let entry of tree) {\n if (entry.type === 'blob') {\n blobs.add(entry.oid);\n }\n // only recurse for trees\n if (entry.type === 'tree') {\n await walk(entry.oid);\n }\n }\n }\n }\n // Let's go walking!\n for (let oid of oids) {\n await walk(oid);\n }\n return [...commits, ...trees, ...blobs];\n}\nexports.listObjects = listObjects;\nasync function pack(fileSystem, dir, gitdir = path_1.default.join(dir, '.git'), oids, outputStream) {\n let hash = sha_js_1.default('sha1');\n function write(chunk, enc = undefined) {\n if (enc) {\n outputStream.write(chunk, enc);\n }\n else {\n outputStream.write(chunk);\n }\n hash.update(chunk, enc);\n }\n function writeObject(object, stype) {\n let lastFour;\n let multibyte;\n let length;\n // Object type is encoded in bits 654\n let type = types[stype];\n if (type === undefined)\n throw Error('Unrecognized type: ' + stype);\n // The length encoding get complicated.\n length = object.length;\n // Whether the next byte is part of the variable-length encoded number\n // is encoded in bit 7\n multibyte = length > 0b1111 ? 0b10000000 : 0b0;\n // Last four bits of length is encoded in bits 3210\n lastFour = length & 0b1111;\n // Discard those bits\n length = length >>> 4;\n // The first byte is then (1-bit multibyte?), (3-bit type), (4-bit least sig 4-bits of length)\n let byte = (multibyte | type | lastFour).toString(16);\n write(byte, 'hex');\n // Now we keep chopping away at length 7-bits at a time until its zero,\n // writing out the bytes in what amounts to little-endian order.\n while (multibyte) {\n multibyte = length > 0b01111111 ? 0b10000000 : 0b0;\n byte = multibyte | (length & 0b01111111);\n const unpaddedChunk = byte.toString(16);\n const paddedChunk = '0'.repeat(2 - unpaddedChunk.length) + unpaddedChunk;\n write(paddedChunk, 'hex');\n length = length >>> 7;\n }\n // Lastly, we can compress and write the object.\n write(Buffer.from(pako_1.default.deflate(object)));\n }\n write('PACK');\n write('00000002', 'hex');\n // Write a 4 byte (32-bit) int\n const unpaddedChunk = oids.length.toString(16);\n const paddedChunk = '0'.repeat(8 - unpaddedChunk.length) + unpaddedChunk;\n write(paddedChunk, 'hex');\n for (let oid of oids) {\n let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid);\n writeObject(object, type);\n }\n // Write SHA1 checksum\n let digest = hash.digest();\n outputStream.end(digest);\n return outputStream;\n}\nexports.pack = pack;\nexports.default = packObjects;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst path = require(\"path\");\nconst GitCommit_1 = __importDefault(require(\"./GitCommit\"));\nconst GitObjectManager_1 = __importDefault(require(\"./GitObjectManager\"));\nconst GitRefManager_1 = __importDefault(require(\"../upload-pack/GitRefManager\"));\nasync function logCommit(fileSystem, gitdir, oid, signing) {\n try {\n let { type, object } = await GitObjectManager_1.default.read(fileSystem, gitdir, oid);\n if (type !== 'commit') {\n throw new Error('expected type to be commit');\n }\n const commit = GitCommit_1.default.from(object);\n const result = Object.assign({ oid }, commit.parse());\n if (signing) {\n result.payload = commit.withoutSignature();\n }\n return result;\n }\n catch (err) {\n return {\n oid,\n error: err,\n };\n }\n}\nexports.logCommit = logCommit;\nfunction compareAge(a, b) {\n return a.committer.timestamp - b.committer.timestamp;\n}\n/**\n * Get commit descriptions from the git history\n *\n * @link https://isomorphic-git.github.io/docs/log.html\n */\nasync function log(fileSystem, dir, gitdir = path.join(dir, '.git'), ref = 'HEAD', depth, since, // Date\nsigning = false) {\n try {\n let sinceTimestamp = since === undefined ? undefined : Math.floor(since.valueOf() / 1000);\n // TODO: In the future, we may want to have an API where we return a\n // async iterator that emits commits.\n let commits = [];\n let oid = await GitRefManager_1.default.resolve(fileSystem, gitdir, ref);\n let tips = [await logCommit(fileSystem, gitdir, oid, signing)];\n // eslint-disable-next-line\n while (true) {\n let commit = tips.pop();\n // Stop the loop if we encounter an error\n if (commit.error) {\n commits.push(commit);\n break;\n }\n // Stop the log if we've hit the age limit\n if (sinceTimestamp !== undefined && commit.committer.timestamp <= sinceTimestamp) {\n break;\n }\n commits.push(commit);\n // Stop the loop if we have enough commits now.\n if (depth !== undefined && commits.length === depth)\n break;\n // Add the parents of this commit to the queue\n // Note: for the case of a commit with no parents, it will concat an empty array, having no net effect.\n for (const oid of commit.parent) {\n let commit = await logCommit(fileSystem, gitdir, oid, signing);\n if (!tips.map((commit) => commit.oid).includes(commit.oid)) {\n tips.push(commit);\n }\n }\n // Stop the loop if there are no more commit parents\n if (tips.length === 0)\n break;\n // Process tips in order by age\n tips.sort(compareAge);\n }\n return commits;\n }\n catch (err) {\n err.caller = 'git.log';\n throw err;\n }\n}\nexports.default = log;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst shasum_1 = __importDefault(require(\"./shasum\"));\nclass GitObject {\n static hash({ type, object }) {\n let buffer = Buffer.concat([Buffer.from(`${type} ${object.byteLength.toString()}\\0`), Buffer.from(object)]);\n let oid = shasum_1.default(buffer);\n return oid;\n }\n static wrap({ type, object }) {\n let buffer = Buffer.concat([Buffer.from(`${type} ${object.byteLength.toString()}\\0`), object]);\n let oid = shasum_1.default(buffer);\n return {\n oid,\n buffer,\n };\n }\n static unwrap({ oid, buffer }) {\n if (oid) {\n let sha = shasum_1.default(buffer);\n if (sha !== oid) {\n throw new Error(`SHA check failed! Expected ${oid}, computed ${sha}`);\n }\n }\n let s = buffer.indexOf(32); // first space\n let i = buffer.indexOf(0); // first null value\n let type = buffer.slice(0, s).toString('utf8'); // get type of object\n let length = buffer.slice(s + 1, i).toString('utf8'); // get type of object\n let actualLength = buffer.length - (i + 1);\n // verify length\n if (parseInt(length) !== actualLength) {\n throw new Error(`Length mismatch: expected ${length} bytes but got ${actualLength} instead.`);\n }\n return {\n type,\n object: Buffer.from(buffer.slice(i + 1)),\n };\n }\n}\nexports.default = GitObject;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst sha1_1 = __importDefault(require(\"sha.js/sha1\"));\n// This is modeled after @dominictarr's \"shasum\" module,\n// but without the 'json-stable-stringify' dependency and\n// extra type-casting features.\nfunction shasum(buffer) {\n return new sha1_1.default().update(buffer).digest('hex');\n}\nexports.default = shasum;\n","module.exports = require(\"sha.js/sha1\");","\"use strict\";\n/*::\ntype TreeEntry = {\n mode: string,\n path: string,\n oid: string,\n type?: string\n}\n*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction parseBuffer(buffer) {\n let _entries = [];\n let cursor = 0;\n while (cursor < buffer.length) {\n let space = buffer.indexOf(32, cursor);\n if (space === -1) {\n throw new Error(`GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next space character.`);\n }\n let nullchar = buffer.indexOf(0, cursor);\n if (nullchar === -1) {\n throw new Error(`GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next null character.`);\n }\n let mode = buffer.slice(cursor, space).toString('utf8');\n if (mode === '40000')\n mode = '040000'; // makes it line up neater in printed output\n let type = mode === '040000' ? 'tree' : 'blob';\n let path = buffer.slice(space + 1, nullchar).toString('utf8');\n let oid = buffer.slice(nullchar + 1, nullchar + 21).toString('hex');\n cursor = nullchar + 21;\n _entries.push({ mode, path, oid, type });\n }\n return _entries;\n}\nfunction limitModeToAllowed(mode) {\n if (typeof mode === 'number') {\n mode = mode.toString(8);\n }\n // tree\n if (mode.match(/^0?4.*/))\n return '40000'; // Directory\n if (mode.match(/^1006.*/))\n return '100644'; // Regular non-executable file\n if (mode.match(/^1007.*/))\n return '100755'; // Regular executable file\n if (mode.match(/^120.*/))\n return '120000'; // Symbolic link\n if (mode.match(/^160.*/))\n return '160000'; // Commit (git submodule reference)\n throw new Error(`Could not understand file mode: ${mode}`);\n}\nfunction nudgeIntoShape(entry) {\n if (!entry.oid && entry.sha) {\n entry.oid = entry.sha; // Github\n }\n entry.mode = limitModeToAllowed(entry.mode); // index\n if (!entry.type) {\n entry.type = 'blob'; // index\n }\n return entry;\n}\nclass GitTree {\n constructor(entries) {\n if (Buffer.isBuffer(entries)) {\n this._entries = parseBuffer(entries);\n }\n else if (Array.isArray(entries)) {\n this._entries = entries.map(nudgeIntoShape);\n }\n else {\n throw new Error('invalid type passed to GitTree constructor');\n }\n }\n static from(tree) {\n return new GitTree(tree);\n }\n render() {\n return this._entries.map((entry) => `${entry.mode} ${entry.type} ${entry.oid} ${entry.path}`).join('\\n');\n }\n toObject() {\n return Buffer.concat(this._entries.map((entry) => {\n let mode = Buffer.from(entry.mode.replace(/^0/, ''));\n let space = Buffer.from(' ');\n let path = Buffer.from(entry.path);\n // let path = Buffer.from(entry.path, { encoding: 'utf8' })\n let nullchar = Buffer.from([0]);\n let oid = Buffer.from(entry.oid.match(/../g).map((n) => parseInt(n, 16)));\n return Buffer.concat([mode, space, path, nullchar, oid]);\n }));\n }\n entries() {\n return this._entries;\n }\n *[Symbol.iterator]() {\n for (let entry of this._entries) {\n yield entry;\n }\n }\n}\nexports.default = GitTree;\n","module.exports = require(\"sha.js\");","module.exports = require(\"../../proto/js/Peer\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Returns a 5 character long random string of lower case letters\n */\nfunction randomString() {\n return Math.random()\n .toString(36)\n .replace(/[^a-z]+/g, '')\n .substr(0, 5);\n}\nexports.randomString = randomString;\n/**\n * Inverts the provided promise\n * @param p Promise to invert\n */\nfunction invertPromise(p) {\n return new Promise((res, rej) => p.then(rej, res));\n}\n/**\n * Gets the first promise fulfiled\n * @param ps List of promises\n */\nfunction firstPromiseFulfilled(ps) {\n return invertPromise(Promise.all(ps.map(invertPromise)));\n}\nexports.firstPromiseFulfilled = firstPromiseFulfilled;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar _a, _b;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dgram_1 = __importDefault(require(\"dgram\"));\nconst crypto_1 = __importDefault(require(\"crypto\"));\nconst PeerInfo_1 = __importDefault(require(\"./PeerInfo\"));\nconst events_1 = require(\"events\");\nconst Peer_js_1 = require(\"../../../proto/js/Peer.js\");\nconst { HandshakeMessage, PeerInfoMessage } = Peer_js_1.peer;\n// This module is based heavily on libp2p's mDNS module:\n// https://github.com/libp2p/js-libp2p-mdns\n// It is supposed to discover peers on the local network\n// This module was also generated with the help of:\n// https://nrempel.com/using-udp-multicast-with-node-js/\n//\n// \"\"\"\n// In computer networking, the multicast DNS (mDNS) protocol\n// resolves hostnames to IP addresses within small networks\n// that do not include a local name server\n// \"\"\"\nconst UDP_MULTICAST_PORT = parseInt((_a = process.env.UDP_MULTICAST_PORT) !== null && _a !== void 0 ? _a : '5353');\nconst UDP_MULTICAST_ADDR = (_b = process.env.UDP_MULTICAST_ADDR) !== null && _b !== void 0 ? _b : '224.0.0.251';\nclass MulticastBroadcaster extends events_1.EventEmitter {\n constructor(addPeer, localPeerInfo, keyManager) {\n super();\n this.peerPubKeyMessages = new Map();\n this.addPeer = addPeer;\n this.localPeerInfo = localPeerInfo;\n this.keyManager = keyManager;\n this.interval = 1e3;\n this.queryInterval = null;\n // Create socket\n this.socket = dgram_1.default.createSocket({ type: 'udp4', reuseAddr: true });\n this.socket.bind(UDP_MULTICAST_PORT);\n // Set up listener\n this.socket.on('listening', (() => {\n this.socket.addMembership(UDP_MULTICAST_ADDR);\n const address = this.socket.address();\n }).bind(this));\n // Handle messages\n this.socket.on('message', this.handleHandshakeMessages.bind(this));\n // Start the query process\n this.queryInterval = this.queryLAN();\n }\n /**\n * Request a peer contact for the multicast peer discovery to check for\n * @param publicKey Public key of the desired peer\n */\n async requestPeerContact(publicKey) {\n const pubKeyBuf = Buffer.from(publicKey);\n const randomMessage = crypto_1.default.randomBytes(16);\n // Encrypt message\n const encryptedPeerPubKey = await this.keyManager.encryptData(pubKeyBuf, pubKeyBuf);\n const encryptedRandomMessage = await this.keyManager.encryptData(randomMessage, pubKeyBuf);\n const encryptedLocalPubKey = await this.keyManager.encryptData(Buffer.from(this.keyManager.getPublicKey()), pubKeyBuf);\n // Add to peer messages to be sent over multicast\n this.peerPubKeyMessages.set(publicKey, {\n encryptedLocalPubKey: Buffer.from(encryptedLocalPubKey),\n encryptedPeerPubKey: Buffer.from(encryptedPeerPubKey),\n rawRandomMessage: randomMessage,\n encryptedRandomMessage: Buffer.from(encryptedRandomMessage),\n });\n }\n // ==== Helper methods ==== //\n queryLAN() {\n const query = () => {\n for (const pubKey of this.peerPubKeyMessages.keys()) {\n const peerMessage = this.peerPubKeyMessages.get(pubKey);\n if (peerMessage) {\n const handshakeMessage = HandshakeMessage.encode({\n targetPubKey: peerMessage.encryptedPeerPubKey,\n requestingPubKey: peerMessage.encryptedLocalPubKey,\n message: peerMessage.encryptedRandomMessage,\n }).finish();\n this.socket.send(handshakeMessage, 0, handshakeMessage.length, UDP_MULTICAST_PORT, UDP_MULTICAST_ADDR);\n }\n }\n };\n // Immediately start a query, then do it every interval.\n query();\n return setInterval(query, this.interval);\n }\n async handleHandshakeMessages(request, rinfo) {\n var _a, _b;\n try {\n const { message, requestingPubKey, responsePeerInfo, targetPubKey } = HandshakeMessage.decode(request);\n // Try to decrypt message and pubKey\n const decryptedMessage = await this.keyManager.decryptData(Buffer.from(message));\n const decryptedTargetPubKey = await this.keyManager.decryptData(Buffer.from(targetPubKey));\n const decryptedRequestingPubKey = await this.keyManager.decryptData(Buffer.from(requestingPubKey));\n const myPubKey = this.keyManager.getPublicKey();\n if (decryptedRequestingPubKey.toString() == myPubKey) {\n // Response\n // Make sure decrypted bytes equal raw bytes in memory\n const originalMessage = (_a = this.peerPubKeyMessages.get(decryptedTargetPubKey.toString())) === null || _a === void 0 ? void 0 : _a.rawRandomMessage;\n if (decryptedMessage.toString() == (originalMessage === null || originalMessage === void 0 ? void 0 : originalMessage.toString())) {\n // Validated!\n // Add peer info to peerStore\n const { addresses, connectedAddr, pubKey } = PeerInfoMessage.decode(responsePeerInfo);\n const newPeerInfo = new PeerInfo_1.default(pubKey, addresses, connectedAddr);\n if (newPeerInfo) {\n this.addPeer(newPeerInfo);\n // Remove peerId from requested messages\n const pubKey = newPeerInfo.publicKey;\n this.peerPubKeyMessages.delete(pubKey);\n console.log(`New peer added to the store`);\n this.emit('found', newPeerInfo);\n }\n else {\n this.emit('error', 'I got a validated response. But no peerInfo');\n }\n }\n }\n else {\n // Requests on target node\n // Try decrypting message\n // Re-encrypt the data and send it on its way\n const encryptedTargetPubKey = await this.keyManager.encryptData(Buffer.from(myPubKey), decryptedRequestingPubKey);\n const encryptedMessage = await this.keyManager.encryptData(decryptedMessage, decryptedRequestingPubKey);\n const encryptedPubKey = await this.keyManager.encryptData(decryptedRequestingPubKey, decryptedRequestingPubKey);\n const encodedLocalPeerInfo = PeerInfoMessage.encode({\n addresses: this.localPeerInfo.AdressStringList,\n connectedAddr: (_b = this.localPeerInfo.connectedAddr) === null || _b === void 0 ? void 0 : _b.toString(),\n pubKey: this.localPeerInfo.publicKey,\n }).finish();\n const handshakeMessage = HandshakeMessage.encode({\n targetPubKey: Buffer.from(encryptedTargetPubKey),\n requestingPubKey: Buffer.from(encryptedPubKey),\n message: Buffer.from(encryptedMessage),\n responsePeerInfo: encodedLocalPeerInfo,\n }).finish();\n this.socket.send(handshakeMessage, 0, handshakeMessage.length, UDP_MULTICAST_PORT, UDP_MULTICAST_ADDR);\n }\n }\n catch (err) {\n // Couldn't decode message\n // We don't want the multicast discovery to error on every message it coudln't decode!\n }\n }\n}\nexports.default = MulticastBroadcaster;\n","module.exports = require(\"dgram\");","module.exports = require(\"events\");","module.exports = require(\"../../proto/js/Peer.js\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst isomorphic_git_1 = __importDefault(require(\"isomorphic-git\"));\nconst Vault_1 = __importDefault(require(\"../vaults/Vault\"));\nconst encryptedfs_1 = require(\"encryptedfs\");\nclass VaultManager {\n constructor(polykeyPath = `${os_1.default.homedir()}/.polykey`, fileSystem, keyManager) {\n this.polykeyPath = polykeyPath;\n this.fileSystem = fileSystem;\n this.keyManager = keyManager;\n this.metadataPath = path_1.default.join(polykeyPath, '.vaultKeys');\n // Make polykeyPath if it doesn't exist\n this.fileSystem.mkdirSync(this.polykeyPath, { recursive: true });\n // Initialize stateful variables\n this.vaults = new Map();\n this.vaultKeys = new Map();\n // Read in vault keys\n this.loadMetadata();\n // Initialize vaults in memory\n for (const [vaultName, vaultKey] of this.vaultKeys.entries()) {\n const path = path_1.default.join(this.polykeyPath, vaultName);\n if (this.fileSystem.existsSync(path)) {\n const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath);\n this.vaults.set(vaultName, vault);\n }\n }\n }\n /**\n * Get a vault from the vault manager\n * @param vaultName Name of desired vault\n */\n getVault(vaultName) {\n if (this.vaults.has(vaultName)) {\n const vault = this.vaults.get(vaultName);\n return vault;\n }\n else if (this.vaultKeys.has(vaultName)) {\n // vault not in map, create new instance\n this.validateVault(vaultName);\n const vaultKey = this.vaultKeys.get(vaultName);\n const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath);\n this.vaults.set(vaultName, vault);\n return vault;\n }\n else {\n throw Error('Vault does not exist in memory');\n }\n }\n /**\n * Get a vault from the vault manager\n * @param vaultName Unique name of new vault\n * @param key Optional key to use for the vault encryption, otherwise it is generated\n */\n async createVault(vaultName, key) {\n if (this.vaultExists(vaultName)) {\n throw Error('Vault already exists!');\n }\n try {\n const path = path_1.default.join(this.polykeyPath, vaultName);\n // Directory not present, create one\n this.fileSystem.mkdirSync(path, { recursive: true });\n // Create key if not provided\n let vaultKey;\n if (!key) {\n // Generate new key\n vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey());\n }\n else {\n // Assign key if it is provided\n vaultKey = key;\n }\n this.vaultKeys.set(vaultName, vaultKey);\n this.writeMetadata();\n // Create vault\n const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath);\n // Init repository for vault\n const vaultPath = path_1.default.join(this.polykeyPath, vaultName);\n const efs = vault.EncryptedFS;\n const fileSystem = { promises: efs.promises };\n await isomorphic_git_1.default.init({\n fs: fileSystem,\n dir: vaultPath,\n });\n // Initial commit\n await isomorphic_git_1.default.commit({\n fs: fileSystem,\n dir: vaultPath,\n author: {\n name: vaultName,\n },\n message: 'init commit',\n });\n // Write packed-refs file because isomorphic git goes searching for it\n // and apparently its not autogenerated\n efs.writeFileSync(path_1.default.join(vaultPath, '.git', 'packed-refs'), '# pack-refs with: peeled fully-peeled sorted');\n // Set vault\n this.vaults.set(vaultName, vault);\n return this.getVault(vaultName);\n }\n catch (err) {\n // Delete vault dir and garbage collect\n this.destroyVault(vaultName);\n throw err;\n }\n }\n /**\n * Get a vault from the vault manager\n * @param vaultName Name of vault to be cloned\n * @param address Address of polykey node that owns vault to be cloned\n * @param getSocket Function to get an active connection to provided address\n */\n async cloneVault(vaultName, gitClient) {\n // Confirm it doesn't exist locally already\n if (this.vaultExists(vaultName)) {\n throw Error('Vault name already exists locally, try pulling instead');\n }\n const vaultUrl = `http://0.0.0.0/${vaultName}`;\n // First check if it exists on remote\n const info = await isomorphic_git_1.default.getRemoteInfo({\n http: gitClient,\n url: vaultUrl,\n });\n if (!info.refs) {\n throw Error(`Peer does not have vault: '${vaultName}'`);\n }\n // Create new efs first\n // Generate new key\n const vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey());\n // Set filesystem\n const vfsInstance = new (require('virtualfs').VirtualFS)();\n const newEfs = new encryptedfs_1.EncryptedFS(vaultKey, vfsInstance, vfsInstance, this.fileSystem, process);\n // Clone vault from address\n await isomorphic_git_1.default.clone({\n fs: { promises: newEfs.promises },\n http: gitClient,\n dir: path_1.default.join(this.polykeyPath, vaultName),\n url: vaultUrl,\n ref: 'master',\n singleBranch: true,\n });\n // Finally return the vault\n const vault = new Vault_1.default(vaultName, vaultKey, this.polykeyPath);\n this.vaults.set(vaultName, vault);\n return vault;\n }\n /**\n * Determines whether the vault exists\n * @param vaultName Name of desired vault\n */\n vaultExists(vaultName) {\n const path = path_1.default.join(this.polykeyPath, vaultName);\n const vaultExists = this.fileSystem.existsSync(path);\n return vaultExists;\n }\n /**\n * [WARNING] Destroys a certain vault and all its secrets\n * @param vaultName Name of vault to be destroyed\n */\n destroyVault(vaultName) {\n // this is convenience function for removing all tags\n // and triggering garbage collection\n // destruction is a better word as we should ensure all traces is removed\n const path = path_1.default.join(this.polykeyPath, vaultName);\n // Remove directory on file system\n if (this.fileSystem.existsSync(path)) {\n this.fileSystem.rmdirSync(path, { recursive: true });\n }\n // Remove from maps\n this.vaults.delete(vaultName);\n this.vaultKeys.delete(vaultName);\n // Write to metadata file\n this.writeMetadata();\n const vaultPathExists = this.fileSystem.existsSync(path);\n if (vaultPathExists) {\n throw Error('Vault folder could not be destroyed!');\n }\n }\n /**\n * List the names of all vaults in memory\n */\n listVaults() {\n return Array.from(this.vaults.keys());\n }\n /* ============ HELPERS =============== */\n validateVault(vaultName) {\n if (!this.vaults.has(vaultName)) {\n throw Error('Vault does not exist in memory');\n }\n if (!this.vaultKeys.has(vaultName)) {\n throw Error('Vault key does not exist in memory');\n }\n const vaultPath = path_1.default.join(this.polykeyPath, vaultName);\n if (!this.fileSystem.existsSync(vaultPath)) {\n throw Error('Vault directory does not exist');\n }\n }\n async writeMetadata() {\n const metadata = JSON.stringify([...this.vaultKeys]);\n const encryptedMetadata = await this.keyManager.encryptData(Buffer.from(metadata));\n await this.fileSystem.promises.writeFile(this.metadataPath, encryptedMetadata);\n }\n async loadMetadata() {\n // Check if file exists\n if (this.fileSystem.existsSync(this.metadataPath) && this.keyManager.identityLoaded) {\n const encryptedMetadata = this.fileSystem.readFileSync(this.metadataPath);\n const metadata = (await this.keyManager.decryptData(encryptedMetadata)).toString();\n for (const [key, value] of new Map(JSON.parse(metadata))) {\n this.vaultKeys[key] = Buffer.from(value);\n }\n }\n }\n}\nexports.default = VaultManager;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = __importDefault(require(\"fs\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst isomorphic_git_1 = __importDefault(require(\"isomorphic-git\"));\nconst encryptedfs_1 = require(\"encryptedfs\");\nconst async_mutex_1 = require(\"async-mutex\");\nclass Vault {\n constructor(name, symKey, baseDir) {\n // Concurrency\n this.mutex = new async_mutex_1.Mutex();\n // how do we create pub/priv key pair?\n // do we use the same gpg pub/priv keypair\n this.key = symKey;\n // Set filesystem\n const vfsInstance = new (require('virtualfs').VirtualFS)();\n this.efs = new encryptedfs_1.EncryptedFS(this.key, vfsInstance, vfsInstance, fs_1.default, process);\n this.name = name;\n this.vaultPath = path_1.default.join(baseDir, name);\n // make the vault directory\n this.efs.mkdirSync(this.vaultPath, { recursive: true });\n this.secrets = new Map();\n this.loadSecrets();\n // Load metadata\n this.metadataPath = path_1.default.join(this.vaultPath, '.vault', 'metadata');\n this.loadMetadata();\n }\n /**\n * Returns the Encrypted File System used for vault operations\n */\n get EncryptedFS() {\n return this.efs;\n }\n /**\n * Determines whether a secret exists in the vault\n * @param secretName Name of desired secret\n */\n secretExists(secretName) {\n const secretPath = path_1.default.join(this.vaultPath, secretName);\n return this.secrets.has(secretName) && this.efs.existsSync(secretPath);\n }\n /**\n * Adds a secret to the vault\n * @param secretName Name of new secret\n * @param secret Content of new secret\n */\n async addSecret(secretName, secret) {\n const release = await this.mutex.acquire();\n try {\n // Check if secret already exists\n if (this.secrets.has(secretName)) {\n throw Error('Secret already exists, try updating it instead.');\n }\n const writePath = path_1.default.join(this.vaultPath, secretName);\n // Write secret\n await this.efs.promises.writeFile(writePath, secret, {});\n // Update secrets map\n this.secrets.set(secretName, secret);\n // Auto commit message\n await this.commitChanges(`Add secret: ${secretName}`, secretName, 'added');\n }\n catch (error) {\n release();\n throw error;\n }\n finally {\n release();\n }\n }\n /**\n * Updates a secret in the vault\n * @param secretName Name of secret to be updated\n * @param secret Content of updated secret\n */\n async updateSecret(secretName, secret) {\n const release = await this.mutex.acquire();\n try {\n // Check if secret already exists\n if (!this.secrets.has(secretName)) {\n throw Error('Secret does not exist, try adding it instead.');\n }\n const writePath = path_1.default.join(this.vaultPath, secretName);\n // Write secret\n await this.efs.promises.writeFile(writePath, secret, {});\n // Update secrets map\n this.secrets.set(secretName, secret);\n // Auto commit message\n await this.commitChanges(`Update secret: ${secretName}`, secretName, 'modified');\n }\n catch (error) {\n release();\n throw error;\n }\n finally {\n release();\n }\n }\n /**\n * Get a secret from the vault\n * @param secretName Name of secret to be retrieved\n */\n getSecret(secretName) {\n if (this.secrets.has(secretName)) {\n const secret = this.secrets.get(secretName);\n if (secret) {\n return secret;\n }\n else {\n const secretPath = path_1.default.join(this.vaultPath, secretName);\n // TODO: this should be async\n const secretBuf = this.efs.readFileSync(secretPath, {});\n this.secrets.set(secretName, secretBuf);\n return secretBuf;\n }\n }\n throw Error('Secret: ' + secretName + ' does not exist');\n }\n /**\n * [WARNING] Removes a secret from the vault\n * @param secretName Name of secret to be removed\n */\n async removeSecret(secretName) {\n const release = await this.mutex.acquire();\n try {\n if (this.secrets.has(secretName)) {\n const successful = this.secrets.delete(secretName);\n // Remove from fs\n await this.efs.promises.unlink(path_1.default.join(this.vaultPath, secretName));\n // Auto commit message\n await this.commitChanges(`Remove secret: ${secretName}`, secretName, 'removed');\n if (successful) {\n return;\n }\n throw Error('Secret: ' + secretName + ' was not removed');\n }\n throw Error('Secret: ' + secretName + ' does not exist');\n }\n catch (error) {\n release();\n throw error;\n }\n finally {\n release();\n }\n }\n /**\n * Lists all the secrets currently in the vault\n */\n listSecrets() {\n let secrets = Array.from(this.secrets.keys());\n return secrets;\n }\n tagVault() { }\n untagVault() { }\n /////////////\n // Sharing //\n /////////////\n /**\n * Allows a particular public key to access the vault\n * @param publicKey Public key to share with\n */\n shareVault(publicKey) {\n if (this.sharedPubKeys.has(name)) {\n throw Error('Vault is already shared with given public key');\n }\n this.sharedPubKeys.add(publicKey);\n // Write metadata\n this.writeMetadata();\n }\n /**\n * Removes access to the vault for a particular public key\n * @param publicKey Public key to unshare with\n */\n unshareVault(publicKey) {\n if (!this.sharedPubKeys.has(publicKey)) {\n throw Error('Vault is not shared with given public key');\n }\n this.sharedPubKeys.delete(publicKey);\n // Write metadata\n this.writeMetadata();\n }\n /**\n * Determines if a particular public key can access the vault\n * @param publicKey Public key to check\n */\n peerCanAccess(publicKey) {\n // return this.sharedPubKeys.has(publicKey)\n return true;\n }\n /**\n * Pulls the vault from a specific address\n * @param address Address of polykey node that owns vault to be pulled\n * @param getSocket Function to get an active connection to provided address\n */\n async pullVault(gitClient) {\n const release = await this.mutex.acquire();\n try {\n // Strangely enough this is needed for pulls along with ref set to 'HEAD'\n // In isogit's documentation, this is just to get the currentBranch name\n // But it solves a bug whereby if not used, git.pull complains that it can't\n // find the master branch or HEAD\n await isomorphic_git_1.default.currentBranch({\n fs: { promises: this.efs.promises },\n dir: this.vaultPath,\n fullname: true,\n });\n // First pull\n await isomorphic_git_1.default.pull({\n fs: { promises: this.efs.promises },\n http: gitClient,\n dir: this.vaultPath,\n url: 'http://' + '0.0.0.0:0' + '/' + this.name,\n ref: 'HEAD',\n singleBranch: true,\n author: {\n name: this.name,\n },\n });\n // Load any new secrets\n this.loadSecrets();\n }\n catch (error) {\n release();\n throw error;\n }\n finally {\n release();\n }\n }\n async getVaultHistory(depth) {\n const logs = await isomorphic_git_1.default.log({\n fs: { promises: this.efs.promises },\n dir: this.vaultPath,\n depth,\n });\n return logs.map((commit) => {\n return commit.commit.message;\n });\n }\n // ============== Helper methods ============== //\n writeMetadata() {\n // mkdir first\n this.efs.mkdirSync(path_1.default.dirname(this.metadataPath), { recursive: true });\n // Create and write metadata\n const metadata = {\n sharedPubKeys: Array.from(this.sharedPubKeys.keys()),\n };\n this.efs.writeFileSync(this.metadataPath, JSON.stringify(metadata));\n }\n loadMetadata() {\n if (this.efs.existsSync(this.metadataPath)) {\n const fileContents = this.efs.readFileSync(this.metadataPath).toString();\n const metadata = JSON.parse(fileContents);\n this.sharedPubKeys = new Set(metadata.sharedPubKeys);\n }\n else {\n // Need to create it\n this.sharedPubKeys = new Set();\n this.writeMetadata();\n }\n }\n async commitChanges(message, secretName, action) {\n if (action == 'removed') {\n await isomorphic_git_1.default.remove({\n fs: { promises: this.efs.promises },\n dir: this.vaultPath,\n filepath: secretName,\n });\n }\n else {\n await isomorphic_git_1.default.add({\n fs: { promises: this.efs.promises },\n dir: this.vaultPath,\n filepath: secretName,\n });\n }\n return await isomorphic_git_1.default.commit({\n fs: { promises: this.efs.promises },\n dir: this.vaultPath,\n author: {\n name: this.name,\n },\n message: message,\n });\n }\n loadSecrets() {\n const secrets = fs_1.default.readdirSync(this.vaultPath, undefined);\n // Remove all secrets first\n this.secrets.clear();\n // Load secrets\n for (const secret of secrets.filter((s) => s[0] != '.')) {\n this.secrets.set(secret, null);\n }\n }\n}\nexports.default = Vault;\n","module.exports = require(\"async-mutex\");","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os_1 = __importDefault(require(\"os\"));\nconst fs_1 = __importDefault(require(\"fs\"));\nconst net_1 = __importDefault(require(\"net\"));\nconst path_1 = __importDefault(require(\"path\"));\nconst process_1 = __importDefault(require(\"process\"));\nconst child_process_1 = require(\"child_process\");\nconst Polykey_1 = __importStar(require(\"../Polykey\"));\nconst configstore_1 = __importDefault(require(\"configstore\"));\nconst PolykeyClient_1 = __importDefault(require(\"./PolykeyClient\"));\nconst Agent_1 = require(\"../../../proto/js/Agent\");\nconst { AgentMessage, CreateSecretRequestMessage, CreateSecretResponseMessage, DeriveKeyRequestMessage, DeriveKeyResponseMessage, DestroySecretRequestMessage, DestroySecretResponseMessage, DestroyVaultRequestMessage, DestroyVaultResponseMessage, ErrorMessage, GetSecretRequestMessage, GetSecretResponseMessage, ListNodesRequestMessage, ListNodesResponseMessage, ListSecretsRequestMessage, ListSecretsResponseMessage, ListVaultsRequestMessage, ListVaultsResponseMessage, NewNodeRequestMessage, NewNodeResponseMessage, NewVaultRequestMessage, NewVaultResponseMessage, RegisterNodeRequestMessage, RegisterNodeResponseMessage, SignFileRequestMessage, SignFileResponseMessage, Type, VerifyFileRequestMessage, VerifyFileResponseMessage, } = Agent_1.agent;\nclass PolykeyAgent {\n constructor() {\n this.persistentStore = new configstore_1.default('polykey');\n // For storing the state of each polykey node\n // Keys are the paths to the polykey node, e.g. '~/.polykey'\n this.polykeyMap = new Map();\n this.socketPath = PolykeyAgent.SocketPath;\n // Make sure the socket file doesn't already exist (agent is already running)\n if (fs_1.default.existsSync(this.socketPath)) {\n fs_1.default.unlinkSync(this.socketPath);\n }\n // Make the socket path if it doesn't exist\n if (!fs_1.default.existsSync(path_1.default.dirname(this.socketPath))) {\n fs_1.default.promises.mkdir(path_1.default.dirname(this.socketPath));\n }\n // Load polykeys\n const nodePaths = this.persistentStore.get('nodePaths');\n if (nodePaths === null || nodePaths === void 0 ? void 0 : nodePaths.values) {\n for (const path of nodePaths) {\n if (fs_1.default.existsSync(path)) {\n this.polykeyMap.set(path, new Polykey_1.default(path, fs_1.default));\n }\n else {\n this.removeFromNodePaths(path);\n }\n }\n }\n else {\n this.persistentStore.set('nodePaths', []);\n }\n // Start the server\n this.server = net_1.default.createServer().listen(this.socketPath);\n this.server.on('connection', (socket) => {\n this.handleClientCommunication(socket);\n });\n }\n get AllNodePaths() {\n return Array.from(this.polykeyMap.keys()).filter((nodePath) => {\n try {\n this.getPolykey(nodePath);\n return true;\n }\n catch (_a) {\n return false;\n }\n });\n }\n get UnlockedNodePaths() {\n return this.AllNodePaths.filter((nodePath) => {\n try {\n return this.getPolykey(nodePath).keyManager.identityLoaded;\n }\n catch (_a) {\n return false;\n }\n });\n }\n stop() {\n this.server.close();\n }\n addToNodePaths(nodePath, pk) {\n this.polykeyMap.set(nodePath, pk);\n const nodePathSet = new Set(this.persistentStore.get('nodePaths'));\n nodePathSet.add(nodePath);\n this.persistentStore.set('nodePaths', Array.from(nodePathSet.values()));\n }\n removeFromNodePaths(nodePath) {\n this.polykeyMap.delete(nodePath);\n const nodePathSet = new Set(this.persistentStore.get('nodePaths'));\n nodePathSet.delete(nodePath);\n this.persistentStore.set('nodePaths', Array.from(nodePathSet.values()));\n }\n handleClientCommunication(socket) {\n socket.on('data', async (encodedMessage) => {\n var _a;\n try {\n const { type, nodePath, subMessage } = AgentMessage.decode(encodedMessage);\n let response = undefined;\n switch (type) {\n case Type.STATUS:\n response = Buffer.from('online');\n break;\n case Type.STOP_AGENT:\n this.stop();\n process_1.default.exit();\n // eslint-disable-next-line\n case Type.REGISTER_NODE:\n response = await this.registerNode(nodePath, subMessage);\n break;\n case Type.NEW_NODE:\n response = await this.newNode(nodePath, subMessage);\n break;\n case Type.LIST_NODES:\n response = this.listNodes(subMessage);\n break;\n case Type.DERIVE_KEY:\n response = await this.deriveKey(nodePath, subMessage);\n break;\n case Type.SIGN_FILE:\n response = await this.signFile(nodePath, subMessage);\n break;\n case Type.VERIFY_FILE:\n response = await this.verifyFile(nodePath, subMessage);\n break;\n case Type.LIST_VAULTS:\n response = await this.listVaults(nodePath);\n break;\n case Type.NEW_VAULT:\n response = await this.newVault(nodePath, subMessage);\n break;\n case Type.DESTROY_VAULT:\n response = await this.destroyVault(nodePath, subMessage);\n break;\n case Type.LIST_SECRETS:\n response = await this.listSecrets(nodePath, subMessage);\n break;\n case Type.CREATE_SECRET:\n response = await this.createSecret(nodePath, subMessage);\n break;\n case Type.DESTROY_SECRET:\n response = await this.destroySecret(nodePath, subMessage);\n break;\n case Type.GET_SECRET:\n response = await this.getSecret(nodePath, subMessage);\n break;\n default:\n throw Error(`message type not supported: ${type}`);\n }\n if (response) {\n const encodedResponse = AgentMessage.encode({\n type: type,\n isResponse: true,\n nodePath: nodePath,\n subMessage: response,\n }).finish();\n socket.write(encodedResponse);\n }\n else {\n throw Error('something went wrong');\n }\n }\n catch (err) {\n const errorResponse = AgentMessage.encode({\n type: Type.ERROR,\n isResponse: true,\n nodePath: undefined,\n subMessage: ErrorMessage.encode({ error: (_a = err.message) !== null && _a !== void 0 ? _a : err }).finish(),\n }).finish();\n socket.write(errorResponse);\n }\n // Close connection\n socket.end();\n });\n }\n // Register an existing polykey agent\n async registerNode(nodePath, request) {\n const { passphrase } = RegisterNodeRequestMessage.decode(request);\n let pk = this.polykeyMap.get(nodePath);\n if (pk) {\n if (pk.keyManager.identityLoaded) {\n throw Error(`node path is already loaded and unlocked: '${nodePath}'`);\n }\n await pk.keyManager.unlockIdentity(passphrase);\n }\n else {\n const km = new Polykey_1.KeyManager(nodePath, fs_1.default);\n await km.unlockIdentity(passphrase);\n // Create polykey class\n pk = new Polykey_1.default(nodePath, fs_1.default, km);\n }\n // Set polykey class\n this.addToNodePaths(nodePath, pk);\n // Encode and send response\n const response = NewNodeResponseMessage.encode({\n successful: pk.keyManager.identityLoaded && this.polykeyMap.has(nodePath),\n }).finish();\n return response;\n }\n // Create a new polykey agent\n async newNode(nodePath, request) {\n // Throw if path already exists\n if (this.polykeyMap.has(nodePath) && fs_1.default.existsSync(nodePath)) {\n throw Error(`node path '${nodePath}' is already loaded`);\n }\n else if (fs_1.default.existsSync(nodePath)) {\n throw Error(`node path already exists: '${nodePath}'`);\n }\n const { name, email, passphrase, nbits } = NewNodeRequestMessage.decode(request);\n const km = new Polykey_1.KeyManager(nodePath, fs_1.default);\n await km.generateKeyPair(name, email, passphrase, nbits == 0 ? undefined : nbits, true, (info) => {\n // socket.write(JSON.stringify(info))\n });\n // Create and set polykey class\n const pk = new Polykey_1.default(nodePath, fs_1.default, km);\n this.addToNodePaths(nodePath, pk);\n // Encode and send response\n const response = NewNodeResponseMessage.encode({\n successful: km.identityLoaded && this.polykeyMap.has(nodePath),\n }).finish();\n return response;\n }\n // Create a new polykey agent\n listNodes(request) {\n const { unlockedOnly } = ListNodesRequestMessage.decode(request);\n if (unlockedOnly) {\n return ListNodesResponseMessage.encode({ nodes: this.UnlockedNodePaths }).finish();\n }\n else {\n return ListNodesResponseMessage.encode({ nodes: this.AllNodePaths }).finish();\n }\n }\n getPolykey(nodePath) {\n var _a;\n if (this.polykeyMap.has(nodePath)) {\n return this.polykeyMap.get(nodePath);\n }\n else if (fs_1.default.existsSync(nodePath)) {\n throw Error(`polykey node has not been loaded yet: '${nodePath}'`);\n }\n else {\n const nodePathList = new Set((_a = this.persistentStore.get('nodePaths')) !== null && _a !== void 0 ? _a : []);\n nodePathList.delete(nodePath);\n this.persistentStore.set('nodePaths', Array.from(nodePathList.values()));\n throw Error(`node path does not exist: '${nodePath}'`);\n }\n }\n /////////////////////////\n // KeyManager commands //\n /////////////////////////\n async deriveKey(nodePath, request) {\n const { keyName, passphrase } = DeriveKeyRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n await pk.keyManager.generateKey(keyName, passphrase);\n return DeriveKeyResponseMessage.encode({ successful: true }).finish();\n }\n /////////////////////\n // Crypto commands //\n /////////////////////\n async signFile(nodePath, request) {\n const { filePath, privateKeyPath, passphrase } = SignFileRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const signaturePath = await pk.keyManager.signFile(filePath, privateKeyPath, passphrase);\n return SignFileResponseMessage.encode({ signaturePath }).finish();\n }\n async verifyFile(nodePath, request) {\n const { filePath, signaturePath } = VerifyFileRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const verified = await pk.keyManager.verifyFile(filePath, signaturePath);\n return VerifyFileResponseMessage.encode({ verified }).finish();\n }\n //////////////////////\n // Vault Operations //\n //////////////////////\n async listVaults(nodePath) {\n const pk = this.getPolykey(nodePath);\n const vaultNames = pk.vaultManager.listVaults();\n return ListVaultsResponseMessage.encode({ vaultNames }).finish();\n }\n async newVault(nodePath, request) {\n const { vaultName } = NewVaultRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n await pk.vaultManager.createVault(vaultName);\n return NewVaultResponseMessage.encode({ successful: true }).finish();\n }\n async destroyVault(nodePath, request) {\n const { vaultName } = DestroyVaultRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n pk.vaultManager.destroyVault(vaultName);\n return DestroyVaultResponseMessage.encode({ successful: true }).finish();\n }\n ///////////////////////\n // Secret Operations //\n ///////////////////////\n async listSecrets(nodePath, request) {\n const { vaultName } = ListSecretsRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const vault = pk.vaultManager.getVault(vaultName);\n const secretNames = vault.listSecrets();\n return ListSecretsResponseMessage.encode({ secretNames }).finish();\n }\n async createSecret(nodePath, request) {\n const { vaultName, secretName, secretPath, secretContent } = CreateSecretRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const vault = pk.vaultManager.getVault(vaultName);\n let secretBuffer;\n if (secretPath) {\n secretBuffer = await fs_1.default.promises.readFile(secretPath);\n }\n else {\n secretBuffer = Buffer.from(secretContent);\n }\n await vault.addSecret(secretName, secretBuffer);\n return CreateSecretResponseMessage.encode({ successful: true }).finish();\n }\n async destroySecret(nodePath, request) {\n const { vaultName, secretName } = DestroySecretRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const vault = pk.vaultManager.getVault(vaultName);\n await vault.removeSecret(secretName);\n return DestroySecretResponseMessage.encode({ successful: true }).finish();\n }\n async getSecret(nodePath, request) {\n const { vaultName, secretName } = GetSecretRequestMessage.decode(request);\n const pk = this.getPolykey(nodePath);\n const vault = pk.vaultManager.getVault(vaultName);\n const secret = Buffer.from(vault.getSecret(secretName));\n return GetSecretResponseMessage.encode({ secret: secret }).finish();\n }\n ///////////////////////\n // Client Connection //\n ///////////////////////\n static connectToAgent(getStream) {\n const defaultStream = () => {\n const socket = net_1.default.createConnection(PolykeyAgent.SocketPath);\n return socket;\n };\n const client = new PolykeyClient_1.default(getStream !== null && getStream !== void 0 ? getStream : defaultStream);\n return client;\n }\n // ===== Helper methods===== //\n static get SocketPath() {\n const platform = os_1.default.platform();\n const userInfo = os_1.default.userInfo();\n if (platform == 'win32') {\n return path_1.default.join('\\\\\\\\?\\\\pipe', process_1.default.cwd(), 'polykey-agent');\n }\n else {\n return `/run/user/${userInfo.uid}/polykey/S.polykey-agent`;\n }\n }\n static get LogPath() {\n const platform = os_1.default.platform();\n const userInfo = os_1.default.userInfo();\n if (platform == 'win32') {\n return path_1.default.join(os_1.default.tmpdir(), 'polykey', 'log');\n }\n else {\n return `/run/user/${userInfo.uid}/polykey/log`;\n }\n }\n static async startAgent(daemon = false) {\n return new Promise((resolve, reject) => {\n try {\n let options = {\n uid: process_1.default.getuid(),\n detached: daemon,\n };\n if (daemon) {\n fs_1.default.rmdirSync(PolykeyAgent.LogPath, { recursive: true });\n fs_1.default.mkdirSync(PolykeyAgent.LogPath, { recursive: true });\n options.stdio = [\n 'ipc',\n fs_1.default.openSync(path_1.default.join(PolykeyAgent.LogPath, 'output.log'), 'a'),\n fs_1.default.openSync(path_1.default.join(PolykeyAgent.LogPath, 'error.log'), 'a'),\n ];\n }\n const agentProcess = child_process_1.fork(PolykeyAgent.DAEMON_SCRIPT_PATH, undefined, options);\n const pid = agentProcess.pid;\n agentProcess.unref();\n resolve(pid);\n }\n catch (err) {\n reject(err);\n }\n });\n }\n}\n//////////////////////\n// Agent Operations //\n//////////////////////\nPolykeyAgent.DAEMON_SCRIPT_PATH = path_1.default.join(__dirname, 'internal', 'daemon-script.js');\nexports.default = PolykeyAgent;\n","module.exports = require(\"net\");","module.exports = require(\"process\");","module.exports = require(\"child_process\");","module.exports = require(\"configstore\");"],"sourceRoot":""} \ No newline at end of file diff --git a/docs/assets/js/search.json b/docs/assets/js/search.json index 1c464e932d..ab2fa36303 100644 --- a/docs/assets/js/search.json +++ b/docs/assets/js/search.json @@ -1 +1 @@ -{"kinds":{"32":"Variable","64":"Function","128":"Class","256":"Interface","512":"Constructor","1024":"Property","2048":"Method","65536":"Type literal","262144":"Accessor","2097152":"Object literal","4194304":"Type alias"},"rows":[{"id":0,"kind":2097152,"name":"keyManagerWorker","url":"globals.html#keymanagerworker","classes":"tsd-kind-object-literal"},{"id":1,"kind":64,"name":"signData","url":"globals.html#keymanagerworker.signdata","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keyManagerWorker"},{"id":2,"kind":64,"name":"verifyData","url":"globals.html#keymanagerworker.verifydata","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keyManagerWorker"},{"id":3,"kind":64,"name":"encryptData","url":"globals.html#keymanagerworker.encryptdata","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keyManagerWorker"},{"id":4,"kind":64,"name":"decryptData","url":"globals.html#keymanagerworker.decryptdata","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keyManagerWorker"},{"id":5,"kind":4194304,"name":"KeyManagerWorker","url":"globals.html#keymanagerworker","classes":"tsd-kind-type-alias"},{"id":6,"kind":128,"name":"KeyManager","url":"classes/keymanager.html","classes":"tsd-kind-class"},{"id":7,"kind":1024,"name":"polykeyPath","url":"classes/keymanager.html#polykeypath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"KeyManager"},{"id":8,"kind":2097152,"name":"pkiInfo","url":"classes/keymanager.html#pkiinfo-1","classes":"tsd-kind-object-literal tsd-parent-kind-class","parent":"KeyManager"},{"id":9,"kind":32,"name":"key","url":"classes/keymanager.html#pkiinfo-1.key","classes":"tsd-kind-variable tsd-parent-kind-object-literal","parent":"KeyManager.pkiInfo"},{"id":10,"kind":32,"name":"cert","url":"classes/keymanager.html#pkiinfo-1.cert","classes":"tsd-kind-variable tsd-parent-kind-object-literal","parent":"KeyManager.pkiInfo"},{"id":11,"kind":32,"name":"caCert","url":"classes/keymanager.html#pkiinfo-1.cacert","classes":"tsd-kind-variable tsd-parent-kind-object-literal","parent":"KeyManager.pkiInfo"},{"id":12,"kind":512,"name":"constructor","url":"classes/keymanager.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"KeyManager"},{"id":13,"kind":262144,"name":"identityLoaded","url":"classes/keymanager.html#identityloaded","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"KeyManager"},{"id":14,"kind":2048,"name":"generateKeyPair","url":"classes/keymanager.html#generatekeypair","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":15,"kind":2048,"name":"getKeyPair","url":"classes/keymanager.html#getkeypair","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":16,"kind":2048,"name":"hasPublicKey","url":"classes/keymanager.html#haspublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":17,"kind":2048,"name":"getPublicKey","url":"classes/keymanager.html#getpublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":18,"kind":2048,"name":"getPrivateKey","url":"classes/keymanager.html#getprivatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":19,"kind":2048,"name":"loadKeyPair","url":"classes/keymanager.html#loadkeypair","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":20,"kind":2048,"name":"loadPrivateKey","url":"classes/keymanager.html#loadprivatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":21,"kind":2048,"name":"loadPublicKey","url":"classes/keymanager.html#loadpublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":22,"kind":2048,"name":"unlockIdentity","url":"classes/keymanager.html#unlockidentity","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":23,"kind":2048,"name":"exportPrivateKey","url":"classes/keymanager.html#exportprivatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":24,"kind":2048,"name":"exportPublicKey","url":"classes/keymanager.html#exportpublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":25,"kind":2048,"name":"generateKeySync","url":"classes/keymanager.html#generatekeysync","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":26,"kind":2048,"name":"generateKey","url":"classes/keymanager.html#generatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":27,"kind":2048,"name":"importKeySync","url":"classes/keymanager.html#importkeysync","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":28,"kind":2048,"name":"importKey","url":"classes/keymanager.html#importkey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":29,"kind":2048,"name":"exportKeySync","url":"classes/keymanager.html#exportkeysync","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":30,"kind":2048,"name":"exportKey","url":"classes/keymanager.html#exportkey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":31,"kind":2048,"name":"getIdentityFromPublicKey","url":"classes/keymanager.html#getidentityfrompublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":32,"kind":2048,"name":"getIdentityFromPrivateKey","url":"classes/keymanager.html#getidentityfromprivatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":33,"kind":2048,"name":"signData","url":"classes/keymanager.html#signdata","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":34,"kind":2048,"name":"signFile","url":"classes/keymanager.html#signfile","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":35,"kind":2048,"name":"verifyData","url":"classes/keymanager.html#verifydata","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":36,"kind":2048,"name":"verifyFile","url":"classes/keymanager.html#verifyfile","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":37,"kind":2048,"name":"encryptData","url":"classes/keymanager.html#encryptdata","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":38,"kind":2048,"name":"decryptData","url":"classes/keymanager.html#decryptdata","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":39,"kind":262144,"name":"PKIInfo","url":"classes/keymanager.html#pkiinfo","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"KeyManager"},{"id":40,"kind":2048,"name":"loadPKIInfo","url":"classes/keymanager.html#loadpkiinfo","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":41,"kind":2048,"name":"getKey","url":"classes/keymanager.html#getkey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":42,"kind":2048,"name":"hasKey","url":"classes/keymanager.html#haskey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":43,"kind":4194304,"name":"KeyManagerMetadata","url":"globals.html#keymanagermetadata","classes":"tsd-kind-type-alias"},{"id":44,"kind":65536,"name":"__type","url":"globals.html#keymanagermetadata.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"KeyManagerMetadata"},{"id":45,"kind":32,"name":"privateKeyPath","url":"globals.html#keymanagermetadata.__type.privatekeypath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":46,"kind":32,"name":"publicKeyPath","url":"globals.html#keymanagermetadata.__type.publickeypath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":47,"kind":32,"name":"pkiKeyPath","url":"globals.html#keymanagermetadata.__type.pkikeypath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":48,"kind":32,"name":"pkiCertPath","url":"globals.html#keymanagermetadata.__type.pkicertpath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":49,"kind":32,"name":"caCertPath","url":"globals.html#keymanagermetadata.__type.cacertpath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":50,"kind":4194304,"name":"KeyPair","url":"globals.html#keypair","classes":"tsd-kind-type-alias"},{"id":51,"kind":65536,"name":"__type","url":"globals.html#keypair.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"KeyPair"},{"id":52,"kind":32,"name":"private","url":"globals.html#keypair.__type.private","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyPair.__type"},{"id":53,"kind":32,"name":"public","url":"globals.html#keypair.__type.public","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyPair.__type"},{"id":54,"kind":4194304,"name":"PKInfo","url":"globals.html#pkinfo","classes":"tsd-kind-type-alias"},{"id":55,"kind":65536,"name":"__type","url":"globals.html#pkinfo.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"PKInfo"},{"id":56,"kind":32,"name":"key","url":"globals.html#pkinfo.__type.key","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PKInfo.__type"},{"id":57,"kind":32,"name":"cert","url":"globals.html#pkinfo.__type.cert","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PKInfo.__type"},{"id":58,"kind":32,"name":"caCert","url":"globals.html#pkinfo.__type.cacert","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PKInfo.__type"},{"id":59,"kind":128,"name":"Address","url":"classes/address.html","classes":"tsd-kind-class"},{"id":60,"kind":1024,"name":"ip","url":"classes/address.html#ip","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Address"},{"id":61,"kind":1024,"name":"port","url":"classes/address.html#port","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Address"},{"id":62,"kind":512,"name":"constructor","url":"classes/address.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"Address"},{"id":63,"kind":2048,"name":"parse","url":"classes/address.html#parse","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"Address"},{"id":64,"kind":2048,"name":"fromAddressInfo","url":"classes/address.html#fromaddressinfo","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"Address"},{"id":65,"kind":2048,"name":"toString","url":"classes/address.html#tostring","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Address"},{"id":66,"kind":128,"name":"PeerInfo","url":"classes/peerinfo.html","classes":"tsd-kind-class"},{"id":67,"kind":1024,"name":"publicKey","url":"classes/peerinfo.html#publickey","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerInfo"},{"id":68,"kind":1024,"name":"addresses","url":"classes/peerinfo.html#addresses","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerInfo"},{"id":69,"kind":1024,"name":"connectedAddr","url":"classes/peerinfo.html#connectedaddr","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerInfo"},{"id":70,"kind":512,"name":"constructor","url":"classes/peerinfo.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"PeerInfo"},{"id":71,"kind":2048,"name":"connect","url":"classes/peerinfo.html#connect","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerInfo"},{"id":72,"kind":2048,"name":"disconnect","url":"classes/peerinfo.html#disconnect","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerInfo"},{"id":73,"kind":262144,"name":"AdressStringList","url":"classes/peerinfo.html#adressstringlist","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"PeerInfo"},{"id":74,"kind":128,"name":"Vault","url":"classes/vault.html","classes":"tsd-kind-class"},{"id":75,"kind":1024,"name":"name","url":"classes/vault.html#name","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Vault"},{"id":76,"kind":1024,"name":"vaultPath","url":"classes/vault.html#vaultpath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Vault"},{"id":77,"kind":512,"name":"constructor","url":"classes/vault.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"Vault"},{"id":78,"kind":262144,"name":"EncryptedFS","url":"classes/vault.html#encryptedfs","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"Vault"},{"id":79,"kind":2048,"name":"secretExists","url":"classes/vault.html#secretexists","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":80,"kind":2048,"name":"addSecret","url":"classes/vault.html#addsecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":81,"kind":2048,"name":"updateSecret","url":"classes/vault.html#updatesecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":82,"kind":2048,"name":"getSecret","url":"classes/vault.html#getsecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":83,"kind":2048,"name":"removeSecret","url":"classes/vault.html#removesecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":84,"kind":2048,"name":"listSecrets","url":"classes/vault.html#listsecrets","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":85,"kind":2048,"name":"tagVault","url":"classes/vault.html#tagvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":86,"kind":2048,"name":"untagVault","url":"classes/vault.html#untagvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":87,"kind":2048,"name":"shareVault","url":"classes/vault.html#sharevault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":88,"kind":2048,"name":"unshareVault","url":"classes/vault.html#unsharevault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":89,"kind":2048,"name":"peerCanAccess","url":"classes/vault.html#peercanaccess","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":90,"kind":2048,"name":"pullVault","url":"classes/vault.html#pullvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":91,"kind":2048,"name":"initRepository","url":"classes/vault.html#initrepository","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":92,"kind":4194304,"name":"VaultMetadata","url":"globals.html#vaultmetadata","classes":"tsd-kind-type-alias"},{"id":93,"kind":65536,"name":"__type","url":"globals.html#vaultmetadata.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"VaultMetadata"},{"id":94,"kind":32,"name":"sharedPubKeys","url":"globals.html#vaultmetadata.__type.sharedpubkeys","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"VaultMetadata.__type"},{"id":95,"kind":128,"name":"VaultManager","url":"classes/vaultmanager.html","classes":"tsd-kind-class"},{"id":96,"kind":1024,"name":"polykeyPath","url":"classes/vaultmanager.html#polykeypath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":97,"kind":1024,"name":"fileSystem","url":"classes/vaultmanager.html#filesystem","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":98,"kind":1024,"name":"keyManager","url":"classes/vaultmanager.html#keymanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":99,"kind":1024,"name":"metadataPath","url":"classes/vaultmanager.html#metadatapath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":100,"kind":1024,"name":"vaults","url":"classes/vaultmanager.html#vaults","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":101,"kind":1024,"name":"vaultKeys","url":"classes/vaultmanager.html#vaultkeys","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":102,"kind":512,"name":"constructor","url":"classes/vaultmanager.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"VaultManager"},{"id":103,"kind":2048,"name":"getVault","url":"classes/vaultmanager.html#getvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":104,"kind":2048,"name":"createVault","url":"classes/vaultmanager.html#createvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":105,"kind":2048,"name":"cloneVault","url":"classes/vaultmanager.html#clonevault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":106,"kind":2048,"name":"vaultExists","url":"classes/vaultmanager.html#vaultexists","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":107,"kind":2048,"name":"destroyVault","url":"classes/vaultmanager.html#destroyvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":108,"kind":2048,"name":"listVaults","url":"classes/vaultmanager.html#listvaults","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":109,"kind":64,"name":"randomString","url":"globals.html#randomstring","classes":"tsd-kind-function"},{"id":110,"kind":64,"name":"invertPromise","url":"globals.html#invertpromise","classes":"tsd-kind-function tsd-has-type-parameter"},{"id":111,"kind":64,"name":"firstPromiseFulfilled","url":"globals.html#firstpromisefulfilled","classes":"tsd-kind-function tsd-has-type-parameter"},{"id":112,"kind":128,"name":"MulticastBroadcaster","url":"classes/multicastbroadcaster.html","classes":"tsd-kind-class"},{"id":113,"kind":1024,"name":"addPeer","url":"classes/multicastbroadcaster.html#addpeer","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":114,"kind":65536,"name":"__type","url":"classes/multicastbroadcaster.html#addpeer.__type","classes":"tsd-kind-type-literal tsd-parent-kind-property","parent":"MulticastBroadcaster.addPeer"},{"id":115,"kind":1024,"name":"localPeerInfo","url":"classes/multicastbroadcaster.html#localpeerinfo","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":116,"kind":1024,"name":"keyManager","url":"classes/multicastbroadcaster.html#keymanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":117,"kind":1024,"name":"socket","url":"classes/multicastbroadcaster.html#socket","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":118,"kind":1024,"name":"interval","url":"classes/multicastbroadcaster.html#interval","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":119,"kind":1024,"name":"queryInterval","url":"classes/multicastbroadcaster.html#queryinterval","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":120,"kind":1024,"name":"peerPubKeyMessages","url":"classes/multicastbroadcaster.html#peerpubkeymessages","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":121,"kind":512,"name":"constructor","url":"classes/multicastbroadcaster.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class tsd-is-overwrite","parent":"MulticastBroadcaster"},{"id":122,"kind":2048,"name":"requestPeerContact","url":"classes/multicastbroadcaster.html#requestpeercontact","classes":"tsd-kind-method tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":123,"kind":2048,"name":"addListener","url":"classes/multicastbroadcaster.html#addlistener","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":124,"kind":2048,"name":"on","url":"classes/multicastbroadcaster.html#on","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":125,"kind":2048,"name":"once","url":"classes/multicastbroadcaster.html#once","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":126,"kind":2048,"name":"removeListener","url":"classes/multicastbroadcaster.html#removelistener","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":127,"kind":2048,"name":"off","url":"classes/multicastbroadcaster.html#off","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":128,"kind":2048,"name":"removeAllListeners","url":"classes/multicastbroadcaster.html#removealllisteners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":129,"kind":2048,"name":"setMaxListeners","url":"classes/multicastbroadcaster.html#setmaxlisteners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":130,"kind":2048,"name":"getMaxListeners","url":"classes/multicastbroadcaster.html#getmaxlisteners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":131,"kind":2048,"name":"listeners","url":"classes/multicastbroadcaster.html#listeners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":132,"kind":2048,"name":"rawListeners","url":"classes/multicastbroadcaster.html#rawlisteners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":133,"kind":2048,"name":"emit","url":"classes/multicastbroadcaster.html#emit","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":134,"kind":2048,"name":"listenerCount","url":"classes/multicastbroadcaster.html#listenercount","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":135,"kind":2048,"name":"prependListener","url":"classes/multicastbroadcaster.html#prependlistener","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":136,"kind":2048,"name":"prependOnceListener","url":"classes/multicastbroadcaster.html#prependoncelistener","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":137,"kind":2048,"name":"eventNames","url":"classes/multicastbroadcaster.html#eventnames","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":138,"kind":2048,"name":"listenerCount","url":"classes/multicastbroadcaster.html#listenercount-1","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited tsd-is-static","parent":"MulticastBroadcaster"},{"id":139,"kind":1024,"name":"defaultMaxListeners","url":"classes/multicastbroadcaster.html#defaultmaxlisteners","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-inherited tsd-is-static","parent":"MulticastBroadcaster"},{"id":140,"kind":32,"name":"HandshakeMessage","url":"globals.html#handshakemessage","classes":"tsd-kind-variable"},{"id":141,"kind":32,"name":"PeerInfoMessage","url":"globals.html#peerinfomessage","classes":"tsd-kind-variable"},{"id":142,"kind":32,"name":"UDP_MULTICAST_PORT","url":"globals.html#udp_multicast_port","classes":"tsd-kind-variable"},{"id":143,"kind":32,"name":"UDP_MULTICAST_ADDR","url":"globals.html#udp_multicast_addr","classes":"tsd-kind-variable"},{"id":144,"kind":4194304,"name":"PeerMessage","url":"globals.html#peermessage","classes":"tsd-kind-type-alias"},{"id":145,"kind":65536,"name":"__type","url":"globals.html#peermessage.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"PeerMessage"},{"id":146,"kind":32,"name":"encryptedLocalPubKey","url":"globals.html#peermessage.__type.encryptedlocalpubkey","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerMessage.__type"},{"id":147,"kind":32,"name":"encryptedPeerPubKey","url":"globals.html#peermessage.__type.encryptedpeerpubkey","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerMessage.__type"},{"id":148,"kind":32,"name":"rawRandomMessage","url":"globals.html#peermessage.__type.rawrandommessage","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerMessage.__type"},{"id":149,"kind":32,"name":"encryptedRandomMessage","url":"globals.html#peermessage.__type.encryptedrandommessage","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerMessage.__type"},{"id":150,"kind":256,"name":"SocialDiscovery","url":"interfaces/socialdiscovery.html","classes":"tsd-kind-interface"},{"id":151,"kind":1024,"name":"name","url":"interfaces/socialdiscovery.html#name","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"SocialDiscovery"},{"id":152,"kind":2048,"name":"findUser","url":"interfaces/socialdiscovery.html#finduser","classes":"tsd-kind-method tsd-parent-kind-interface","parent":"SocialDiscovery"},{"id":153,"kind":128,"name":"PeerManager","url":"classes/peermanager.html","classes":"tsd-kind-class"},{"id":154,"kind":1024,"name":"multicastBroadcaster","url":"classes/peermanager.html#multicastbroadcaster","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerManager"},{"id":155,"kind":1024,"name":"server","url":"classes/peermanager.html#server","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerManager"},{"id":156,"kind":1024,"name":"serverStarted","url":"classes/peermanager.html#serverstarted","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerManager"},{"id":157,"kind":512,"name":"constructor","url":"classes/peermanager.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"PeerManager"},{"id":158,"kind":2048,"name":"getLocalPeerInfo","url":"classes/peermanager.html#getlocalpeerinfo","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":159,"kind":2048,"name":"connectLocalPeerInfo","url":"classes/peermanager.html#connectlocalpeerinfo","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":160,"kind":2048,"name":"addPeer","url":"classes/peermanager.html#addpeer","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":161,"kind":2048,"name":"getPeer","url":"classes/peermanager.html#getpeer","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":162,"kind":2048,"name":"hasPeer","url":"classes/peermanager.html#haspeer","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":163,"kind":2048,"name":"findPubKey","url":"classes/peermanager.html#findpubkey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":164,"kind":2048,"name":"findSocialUser","url":"classes/peermanager.html#findsocialuser","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":165,"kind":2048,"name":"connectToPeer","url":"classes/peermanager.html#connecttopeer","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":166,"kind":2097152,"name":"keybaseDiscovery","url":"globals.html#keybasediscovery","classes":"tsd-kind-object-literal"},{"id":167,"kind":32,"name":"name","url":"globals.html#keybasediscovery.name","classes":"tsd-kind-variable tsd-parent-kind-object-literal","parent":"keybaseDiscovery"},{"id":168,"kind":64,"name":"findUser","url":"globals.html#keybasediscovery.finduser","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keybaseDiscovery"},{"id":169,"kind":4194304,"name":"PeerManagerMetadata","url":"globals.html#peermanagermetadata","classes":"tsd-kind-type-alias"},{"id":170,"kind":65536,"name":"__type","url":"globals.html#peermanagermetadata.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"PeerManagerMetadata"},{"id":171,"kind":32,"name":"localPeerInfo","url":"globals.html#peermanagermetadata.__type.localpeerinfo","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerManagerMetadata.__type"},{"id":172,"kind":128,"name":"PolykeyClient","url":"classes/polykeyclient.html","classes":"tsd-kind-class"},{"id":173,"kind":512,"name":"constructor","url":"classes/polykeyclient.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"PolykeyClient"},{"id":174,"kind":2048,"name":"sendRequestToAgent","url":"classes/polykeyclient.html#sendrequesttoagent","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":175,"kind":2048,"name":"registerNode","url":"classes/polykeyclient.html#registernode","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":176,"kind":2048,"name":"newNode","url":"classes/polykeyclient.html#newnode","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":177,"kind":2048,"name":"listNodes","url":"classes/polykeyclient.html#listnodes","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":178,"kind":2048,"name":"deriveKey","url":"classes/polykeyclient.html#derivekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":179,"kind":2048,"name":"signFile","url":"classes/polykeyclient.html#signfile","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":180,"kind":2048,"name":"verifyFile","url":"classes/polykeyclient.html#verifyfile","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":181,"kind":2048,"name":"listVaults","url":"classes/polykeyclient.html#listvaults","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":182,"kind":2048,"name":"newVault","url":"classes/polykeyclient.html#newvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":183,"kind":2048,"name":"destroyVault","url":"classes/polykeyclient.html#destroyvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":184,"kind":2048,"name":"listSecrets","url":"classes/polykeyclient.html#listsecrets","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":185,"kind":2048,"name":"createSecret","url":"classes/polykeyclient.html#createsecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":186,"kind":2048,"name":"destroySecret","url":"classes/polykeyclient.html#destroysecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":187,"kind":2048,"name":"getSecret","url":"classes/polykeyclient.html#getsecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":188,"kind":2048,"name":"getAgentStatus","url":"classes/polykeyclient.html#getagentstatus","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":189,"kind":2048,"name":"stopAgent","url":"classes/polykeyclient.html#stopagent","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":190,"kind":32,"name":"AgentMessage","url":"globals.html#agentmessage","classes":"tsd-kind-variable"},{"id":191,"kind":32,"name":"CreateSecretRequestMessage","url":"globals.html#createsecretrequestmessage","classes":"tsd-kind-variable"},{"id":192,"kind":32,"name":"CreateSecretResponseMessage","url":"globals.html#createsecretresponsemessage","classes":"tsd-kind-variable"},{"id":193,"kind":32,"name":"DeriveKeyRequestMessage","url":"globals.html#derivekeyrequestmessage","classes":"tsd-kind-variable"},{"id":194,"kind":32,"name":"DeriveKeyResponseMessage","url":"globals.html#derivekeyresponsemessage","classes":"tsd-kind-variable"},{"id":195,"kind":32,"name":"DestroySecretRequestMessage","url":"globals.html#destroysecretrequestmessage","classes":"tsd-kind-variable"},{"id":196,"kind":32,"name":"DestroySecretResponseMessage","url":"globals.html#destroysecretresponsemessage","classes":"tsd-kind-variable"},{"id":197,"kind":32,"name":"DestroyVaultRequestMessage","url":"globals.html#destroyvaultrequestmessage","classes":"tsd-kind-variable"},{"id":198,"kind":32,"name":"DestroyVaultResponseMessage","url":"globals.html#destroyvaultresponsemessage","classes":"tsd-kind-variable"},{"id":199,"kind":32,"name":"ErrorMessage","url":"globals.html#errormessage","classes":"tsd-kind-variable"},{"id":200,"kind":32,"name":"GetSecretRequestMessage","url":"globals.html#getsecretrequestmessage","classes":"tsd-kind-variable"},{"id":201,"kind":32,"name":"GetSecretResponseMessage","url":"globals.html#getsecretresponsemessage","classes":"tsd-kind-variable"},{"id":202,"kind":32,"name":"ListNodesRequestMessage","url":"globals.html#listnodesrequestmessage","classes":"tsd-kind-variable"},{"id":203,"kind":32,"name":"ListNodesResponseMessage","url":"globals.html#listnodesresponsemessage","classes":"tsd-kind-variable"},{"id":204,"kind":32,"name":"ListSecretsRequestMessage","url":"globals.html#listsecretsrequestmessage","classes":"tsd-kind-variable"},{"id":205,"kind":32,"name":"ListSecretsResponseMessage","url":"globals.html#listsecretsresponsemessage","classes":"tsd-kind-variable"},{"id":206,"kind":32,"name":"ListVaultsRequestMessage","url":"globals.html#listvaultsrequestmessage","classes":"tsd-kind-variable"},{"id":207,"kind":32,"name":"ListVaultsResponseMessage","url":"globals.html#listvaultsresponsemessage","classes":"tsd-kind-variable"},{"id":208,"kind":32,"name":"NewNodeRequestMessage","url":"globals.html#newnoderequestmessage","classes":"tsd-kind-variable"},{"id":209,"kind":32,"name":"NewNodeResponseMessage","url":"globals.html#newnoderesponsemessage","classes":"tsd-kind-variable"},{"id":210,"kind":32,"name":"NewVaultRequestMessage","url":"globals.html#newvaultrequestmessage","classes":"tsd-kind-variable"},{"id":211,"kind":32,"name":"NewVaultResponseMessage","url":"globals.html#newvaultresponsemessage","classes":"tsd-kind-variable"},{"id":212,"kind":32,"name":"RegisterNodeRequestMessage","url":"globals.html#registernoderequestmessage","classes":"tsd-kind-variable"},{"id":213,"kind":32,"name":"RegisterNodeResponseMessage","url":"globals.html#registernoderesponsemessage","classes":"tsd-kind-variable"},{"id":214,"kind":32,"name":"SignFileRequestMessage","url":"globals.html#signfilerequestmessage","classes":"tsd-kind-variable"},{"id":215,"kind":32,"name":"SignFileResponseMessage","url":"globals.html#signfileresponsemessage","classes":"tsd-kind-variable"},{"id":216,"kind":32,"name":"Type","url":"globals.html#type","classes":"tsd-kind-variable"},{"id":217,"kind":32,"name":"VerifyFileRequestMessage","url":"globals.html#verifyfilerequestmessage","classes":"tsd-kind-variable"},{"id":218,"kind":32,"name":"VerifyFileResponseMessage","url":"globals.html#verifyfileresponsemessage","classes":"tsd-kind-variable"},{"id":219,"kind":128,"name":"PolykeyAgent","url":"classes/polykeyagent.html","classes":"tsd-kind-class"},{"id":220,"kind":262144,"name":"AllNodePaths","url":"classes/polykeyagent.html#allnodepaths","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"PolykeyAgent"},{"id":221,"kind":262144,"name":"UnlockedNodePaths","url":"classes/polykeyagent.html#unlockednodepaths","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"PolykeyAgent"},{"id":222,"kind":512,"name":"constructor","url":"classes/polykeyagent.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"PolykeyAgent"},{"id":223,"kind":2048,"name":"stop","url":"classes/polykeyagent.html#stop","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyAgent"},{"id":224,"kind":2048,"name":"connectToAgent","url":"classes/polykeyagent.html#connecttoagent","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":225,"kind":262144,"name":"SocketPath","url":"classes/polykeyagent.html#socketpath","classes":"tsd-kind-get-signature tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":226,"kind":262144,"name":"LogPath","url":"classes/polykeyagent.html#logpath","classes":"tsd-kind-get-signature tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":227,"kind":1024,"name":"DAEMON_SCRIPT_PATH","url":"classes/polykeyagent.html#daemon_script_path","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":228,"kind":2048,"name":"startAgent","url":"classes/polykeyagent.html#startagent","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":229,"kind":128,"name":"Polykey","url":"classes/polykey.html","classes":"tsd-kind-class"},{"id":230,"kind":1024,"name":"polykeyPath","url":"classes/polykey.html#polykeypath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Polykey"},{"id":231,"kind":1024,"name":"vaultManager","url":"classes/polykey.html#vaultmanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Polykey"},{"id":232,"kind":1024,"name":"keyManager","url":"classes/polykey.html#keymanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Polykey"},{"id":233,"kind":1024,"name":"peerManager","url":"classes/polykey.html#peermanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Polykey"},{"id":234,"kind":512,"name":"constructor","url":"classes/polykey.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"Polykey"},{"id":235,"kind":128,"name":"PublicKeyInfrastructure","url":"classes/publickeyinfrastructure.html","classes":"tsd-kind-class"},{"id":236,"kind":1024,"name":"N_BITS","url":"classes/publickeyinfrastructure.html#n_bits","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-static","parent":"PublicKeyInfrastructure"},{"id":237,"kind":1024,"name":"COMMON_NAME","url":"classes/publickeyinfrastructure.html#common_name","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-static","parent":"PublicKeyInfrastructure"},{"id":238,"kind":1024,"name":"ORGANIZATION_NAME","url":"classes/publickeyinfrastructure.html#organization_name","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-static","parent":"PublicKeyInfrastructure"},{"id":239,"kind":2048,"name":"createX509Certificate","url":"classes/publickeyinfrastructure.html#createx509certificate","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"PublicKeyInfrastructure"},{"id":240,"kind":32,"name":"$protobuf","url":"globals.html#_protobuf","classes":"tsd-kind-variable"},{"id":241,"kind":32,"name":"$Reader","url":"globals.html#_reader","classes":"tsd-kind-variable"},{"id":242,"kind":32,"name":"$Writer","url":"globals.html#_writer","classes":"tsd-kind-variable"},{"id":243,"kind":32,"name":"$util","url":"globals.html#_util","classes":"tsd-kind-variable"},{"id":244,"kind":32,"name":"$root","url":"globals.html#_root","classes":"tsd-kind-variable"}],"index":{"version":"2.3.8","fields":["name","parent"],"fieldVectors":[["name/0",[0,36.335]],["parent/0",[]],["name/1",[1,45.89]],["parent/1",[0,3.191]],["name/2",[2,45.89]],["parent/2",[0,3.191]],["name/3",[3,45.89]],["parent/3",[0,3.191]],["name/4",[4,45.89]],["parent/4",[0,3.191]],["name/5",[0,36.335]],["parent/5",[]],["name/6",[5,18.81]],["parent/6",[]],["name/7",[6,42.526]],["parent/7",[5,1.652]],["name/8",[7,45.89]],["parent/8",[5,1.652]],["name/9",[8,45.89]],["parent/9",[9,3.735]],["name/10",[10,45.89]],["parent/10",[9,3.735]],["name/11",[11,45.89]],["parent/11",[9,3.735]],["name/12",[12,31.54]],["parent/12",[5,1.652]],["name/13",[13,50.999]],["parent/13",[5,1.652]],["name/14",[14,50.999]],["parent/14",[5,1.652]],["name/15",[15,50.999]],["parent/15",[5,1.652]],["name/16",[16,50.999]],["parent/16",[5,1.652]],["name/17",[17,50.999]],["parent/17",[5,1.652]],["name/18",[18,50.999]],["parent/18",[5,1.652]],["name/19",[19,50.999]],["parent/19",[5,1.652]],["name/20",[20,50.999]],["parent/20",[5,1.652]],["name/21",[21,50.999]],["parent/21",[5,1.652]],["name/22",[22,50.999]],["parent/22",[5,1.652]],["name/23",[23,50.999]],["parent/23",[5,1.652]],["name/24",[24,50.999]],["parent/24",[5,1.652]],["name/25",[25,50.999]],["parent/25",[5,1.652]],["name/26",[26,50.999]],["parent/26",[5,1.652]],["name/27",[27,50.999]],["parent/27",[5,1.652]],["name/28",[28,50.999]],["parent/28",[5,1.652]],["name/29",[29,50.999]],["parent/29",[5,1.652]],["name/30",[30,50.999]],["parent/30",[5,1.652]],["name/31",[31,50.999]],["parent/31",[5,1.652]],["name/32",[32,50.999]],["parent/32",[5,1.652]],["name/33",[1,45.89]],["parent/33",[5,1.652]],["name/34",[33,45.89]],["parent/34",[5,1.652]],["name/35",[2,45.89]],["parent/35",[5,1.652]],["name/36",[34,45.89]],["parent/36",[5,1.652]],["name/37",[3,45.89]],["parent/37",[5,1.652]],["name/38",[4,45.89]],["parent/38",[5,1.652]],["name/39",[7,45.89]],["parent/39",[5,1.652]],["name/40",[35,50.999]],["parent/40",[5,1.652]],["name/41",[36,50.999]],["parent/41",[5,1.652]],["name/42",[37,50.999]],["parent/42",[5,1.652]],["name/43",[38,45.89]],["parent/43",[]],["name/44",[39,34.904]],["parent/44",[38,4.03]],["name/45",[40,50.999]],["parent/45",[41,3.338]],["name/46",[42,50.999]],["parent/46",[41,3.338]],["name/47",[43,50.999]],["parent/47",[41,3.338]],["name/48",[44,50.999]],["parent/48",[41,3.338]],["name/49",[45,50.999]],["parent/49",[41,3.338]],["name/50",[46,45.89]],["parent/50",[]],["name/51",[39,34.904]],["parent/51",[46,4.03]],["name/52",[47,50.999]],["parent/52",[48,4.03]],["name/53",[49,50.999]],["parent/53",[48,4.03]],["name/54",[50,45.89]],["parent/54",[]],["name/55",[39,34.904]],["parent/55",[50,4.03]],["name/56",[8,45.89]],["parent/56",[51,3.735]],["name/57",[10,45.89]],["parent/57",[51,3.735]],["name/58",[11,45.89]],["parent/58",[51,3.735]],["name/59",[52,34.904]],["parent/59",[]],["name/60",[53,50.999]],["parent/60",[52,3.066]],["name/61",[54,50.999]],["parent/61",[52,3.066]],["name/62",[12,31.54]],["parent/62",[52,3.066]],["name/63",[55,50.999]],["parent/63",[52,3.066]],["name/64",[56,50.999]],["parent/64",[52,3.066]],["name/65",[57,50.999]],["parent/65",[52,3.066]],["name/66",[58,33.653]],["parent/66",[]],["name/67",[59,50.999]],["parent/67",[58,2.956]],["name/68",[60,50.999]],["parent/68",[58,2.956]],["name/69",[61,50.999]],["parent/69",[58,2.956]],["name/70",[12,31.54]],["parent/70",[58,2.956]],["name/71",[62,50.999]],["parent/71",[58,2.956]],["name/72",[63,50.999]],["parent/72",[58,2.956]],["name/73",[64,50.999]],["parent/73",[58,2.956]],["name/74",[65,25.876]],["parent/74",[]],["name/75",[66,42.526]],["parent/75",[65,2.273]],["name/76",[67,50.999]],["parent/76",[65,2.273]],["name/77",[12,31.54]],["parent/77",[65,2.273]],["name/78",[68,50.999]],["parent/78",[65,2.273]],["name/79",[69,50.999]],["parent/79",[65,2.273]],["name/80",[70,50.999]],["parent/80",[65,2.273]],["name/81",[71,50.999]],["parent/81",[65,2.273]],["name/82",[72,45.89]],["parent/82",[65,2.273]],["name/83",[73,50.999]],["parent/83",[65,2.273]],["name/84",[74,45.89]],["parent/84",[65,2.273]],["name/85",[75,50.999]],["parent/85",[65,2.273]],["name/86",[76,50.999]],["parent/86",[65,2.273]],["name/87",[77,50.999]],["parent/87",[65,2.273]],["name/88",[78,50.999]],["parent/88",[65,2.273]],["name/89",[79,50.999]],["parent/89",[65,2.273]],["name/90",[80,50.999]],["parent/90",[65,2.273]],["name/91",[81,50.999]],["parent/91",[65,2.273]],["name/92",[82,45.89]],["parent/92",[]],["name/93",[39,34.904]],["parent/93",[82,4.03]],["name/94",[83,50.999]],["parent/94",[84,4.479]],["name/95",[85,27.645]],["parent/95",[]],["name/96",[6,42.526]],["parent/96",[85,2.428]],["name/97",[86,50.999]],["parent/97",[85,2.428]],["name/98",[5,18.81]],["parent/98",[85,2.428]],["name/99",[87,50.999]],["parent/99",[85,2.428]],["name/100",[88,50.999]],["parent/100",[85,2.428]],["name/101",[89,50.999]],["parent/101",[85,2.428]],["name/102",[12,31.54]],["parent/102",[85,2.428]],["name/103",[90,50.999]],["parent/103",[85,2.428]],["name/104",[91,50.999]],["parent/104",[85,2.428]],["name/105",[92,50.999]],["parent/105",[85,2.428]],["name/106",[93,50.999]],["parent/106",[85,2.428]],["name/107",[94,45.89]],["parent/107",[85,2.428]],["name/108",[95,45.89]],["parent/108",[85,2.428]],["name/109",[96,50.999]],["parent/109",[]],["name/110",[97,50.999]],["parent/110",[]],["name/111",[98,50.999]],["parent/111",[]],["name/112",[99,21.554]],["parent/112",[]],["name/113",[100,45.89]],["parent/113",[99,1.893]],["name/114",[39,34.904]],["parent/114",[101,4.479]],["name/115",[102,45.89]],["parent/115",[99,1.893]],["name/116",[5,18.81]],["parent/116",[99,1.893]],["name/117",[103,50.999]],["parent/117",[99,1.893]],["name/118",[104,50.999]],["parent/118",[99,1.893]],["name/119",[105,50.999]],["parent/119",[99,1.893]],["name/120",[106,50.999]],["parent/120",[99,1.893]],["name/121",[12,31.54]],["parent/121",[99,1.893]],["name/122",[107,50.999]],["parent/122",[99,1.893]],["name/123",[108,50.999]],["parent/123",[99,1.893]],["name/124",[109,50.999]],["parent/124",[99,1.893]],["name/125",[110,50.999]],["parent/125",[99,1.893]],["name/126",[111,50.999]],["parent/126",[99,1.893]],["name/127",[112,50.999]],["parent/127",[99,1.893]],["name/128",[113,50.999]],["parent/128",[99,1.893]],["name/129",[114,50.999]],["parent/129",[99,1.893]],["name/130",[115,50.999]],["parent/130",[99,1.893]],["name/131",[116,50.999]],["parent/131",[99,1.893]],["name/132",[117,50.999]],["parent/132",[99,1.893]],["name/133",[118,50.999]],["parent/133",[99,1.893]],["name/134",[119,45.89]],["parent/134",[99,1.893]],["name/135",[120,50.999]],["parent/135",[99,1.893]],["name/136",[121,50.999]],["parent/136",[99,1.893]],["name/137",[122,50.999]],["parent/137",[99,1.893]],["name/138",[119,45.89]],["parent/138",[99,1.893]],["name/139",[123,50.999]],["parent/139",[99,1.893]],["name/140",[124,50.999]],["parent/140",[]],["name/141",[125,50.999]],["parent/141",[]],["name/142",[126,50.999]],["parent/142",[]],["name/143",[127,50.999]],["parent/143",[]],["name/144",[128,45.89]],["parent/144",[]],["name/145",[39,34.904]],["parent/145",[128,4.03]],["name/146",[129,50.999]],["parent/146",[130,3.514]],["name/147",[131,50.999]],["parent/147",[130,3.514]],["name/148",[132,50.999]],["parent/148",[130,3.514]],["name/149",[133,50.999]],["parent/149",[130,3.514]],["name/150",[134,42.526]],["parent/150",[]],["name/151",[66,42.526]],["parent/151",[134,3.735]],["name/152",[135,45.89]],["parent/152",[134,3.735]],["name/153",[136,28.312]],["parent/153",[]],["name/154",[99,21.554]],["parent/154",[136,2.487]],["name/155",[137,50.999]],["parent/155",[136,2.487]],["name/156",[138,50.999]],["parent/156",[136,2.487]],["name/157",[12,31.54]],["parent/157",[136,2.487]],["name/158",[139,50.999]],["parent/158",[136,2.487]],["name/159",[140,50.999]],["parent/159",[136,2.487]],["name/160",[100,45.89]],["parent/160",[136,2.487]],["name/161",[141,50.999]],["parent/161",[136,2.487]],["name/162",[142,50.999]],["parent/162",[136,2.487]],["name/163",[143,50.999]],["parent/163",[136,2.487]],["name/164",[144,50.999]],["parent/164",[136,2.487]],["name/165",[145,50.999]],["parent/165",[136,2.487]],["name/166",[146,42.526]],["parent/166",[]],["name/167",[66,42.526]],["parent/167",[146,3.735]],["name/168",[135,45.89]],["parent/168",[146,3.735]],["name/169",[147,45.89]],["parent/169",[]],["name/170",[39,34.904]],["parent/170",[147,4.03]],["name/171",[102,45.89]],["parent/171",[148,4.479]],["name/172",[149,25.876]],["parent/172",[]],["name/173",[12,31.54]],["parent/173",[149,2.273]],["name/174",[150,50.999]],["parent/174",[149,2.273]],["name/175",[151,50.999]],["parent/175",[149,2.273]],["name/176",[152,50.999]],["parent/176",[149,2.273]],["name/177",[153,50.999]],["parent/177",[149,2.273]],["name/178",[154,50.999]],["parent/178",[149,2.273]],["name/179",[33,45.89]],["parent/179",[149,2.273]],["name/180",[34,45.89]],["parent/180",[149,2.273]],["name/181",[95,45.89]],["parent/181",[149,2.273]],["name/182",[155,50.999]],["parent/182",[149,2.273]],["name/183",[94,45.89]],["parent/183",[149,2.273]],["name/184",[74,45.89]],["parent/184",[149,2.273]],["name/185",[156,50.999]],["parent/185",[149,2.273]],["name/186",[157,50.999]],["parent/186",[149,2.273]],["name/187",[72,45.89]],["parent/187",[149,2.273]],["name/188",[158,50.999]],["parent/188",[149,2.273]],["name/189",[159,50.999]],["parent/189",[149,2.273]],["name/190",[160,50.999]],["parent/190",[]],["name/191",[161,50.999]],["parent/191",[]],["name/192",[162,50.999]],["parent/192",[]],["name/193",[163,50.999]],["parent/193",[]],["name/194",[164,50.999]],["parent/194",[]],["name/195",[165,50.999]],["parent/195",[]],["name/196",[166,50.999]],["parent/196",[]],["name/197",[167,50.999]],["parent/197",[]],["name/198",[168,50.999]],["parent/198",[]],["name/199",[169,50.999]],["parent/199",[]],["name/200",[170,50.999]],["parent/200",[]],["name/201",[171,50.999]],["parent/201",[]],["name/202",[172,50.999]],["parent/202",[]],["name/203",[173,50.999]],["parent/203",[]],["name/204",[174,50.999]],["parent/204",[]],["name/205",[175,50.999]],["parent/205",[]],["name/206",[176,50.999]],["parent/206",[]],["name/207",[177,50.999]],["parent/207",[]],["name/208",[178,50.999]],["parent/208",[]],["name/209",[179,50.999]],["parent/209",[]],["name/210",[180,50.999]],["parent/210",[]],["name/211",[181,50.999]],["parent/211",[]],["name/212",[182,50.999]],["parent/212",[]],["name/213",[183,50.999]],["parent/213",[]],["name/214",[184,50.999]],["parent/214",[]],["name/215",[185,50.999]],["parent/215",[]],["name/216",[186,50.999]],["parent/216",[]],["name/217",[187,50.999]],["parent/217",[]],["name/218",[188,50.999]],["parent/218",[]],["name/219",[189,31.54]],["parent/219",[]],["name/220",[190,50.999]],["parent/220",[189,2.77]],["name/221",[191,50.999]],["parent/221",[189,2.77]],["name/222",[12,31.54]],["parent/222",[189,2.77]],["name/223",[192,50.999]],["parent/223",[189,2.77]],["name/224",[193,50.999]],["parent/224",[189,2.77]],["name/225",[194,50.999]],["parent/225",[189,2.77]],["name/226",[195,50.999]],["parent/226",[189,2.77]],["name/227",[196,50.999]],["parent/227",[189,2.77]],["name/228",[197,50.999]],["parent/228",[189,2.77]],["name/229",[198,36.335]],["parent/229",[]],["name/230",[6,42.526]],["parent/230",[198,3.191]],["name/231",[85,27.645]],["parent/231",[198,3.191]],["name/232",[5,18.81]],["parent/232",[198,3.191]],["name/233",[136,28.312]],["parent/233",[198,3.191]],["name/234",[12,31.54]],["parent/234",[198,3.191]],["name/235",[199,38.006]],["parent/235",[]],["name/236",[200,50.999]],["parent/236",[199,3.338]],["name/237",[201,50.999]],["parent/237",[199,3.338]],["name/238",[202,50.999]],["parent/238",[199,3.338]],["name/239",[203,50.999]],["parent/239",[199,3.338]],["name/240",[204,50.999]],["parent/240",[]],["name/241",[205,50.999]],["parent/241",[]],["name/242",[206,50.999]],["parent/242",[]],["name/243",[207,50.999]],["parent/243",[]],["name/244",[208,50.999]],["parent/244",[]]],"invertedIndex":[["__type",{"_index":39,"name":{"44":{},"51":{},"55":{},"93":{},"114":{},"145":{},"170":{}},"parent":{}}],["addlistener",{"_index":108,"name":{"123":{}},"parent":{}}],["addpeer",{"_index":100,"name":{"113":{},"160":{}},"parent":{}}],["address",{"_index":52,"name":{"59":{}},"parent":{"60":{},"61":{},"62":{},"63":{},"64":{},"65":{}}}],["addresses",{"_index":60,"name":{"68":{}},"parent":{}}],["addsecret",{"_index":70,"name":{"80":{}},"parent":{}}],["adressstringlist",{"_index":64,"name":{"73":{}},"parent":{}}],["agentmessage",{"_index":160,"name":{"190":{}},"parent":{}}],["allnodepaths",{"_index":190,"name":{"220":{}},"parent":{}}],["cacert",{"_index":11,"name":{"11":{},"58":{}},"parent":{}}],["cacertpath",{"_index":45,"name":{"49":{}},"parent":{}}],["cert",{"_index":10,"name":{"10":{},"57":{}},"parent":{}}],["clonevault",{"_index":92,"name":{"105":{}},"parent":{}}],["common_name",{"_index":201,"name":{"237":{}},"parent":{}}],["connect",{"_index":62,"name":{"71":{}},"parent":{}}],["connectedaddr",{"_index":61,"name":{"69":{}},"parent":{}}],["connectlocalpeerinfo",{"_index":140,"name":{"159":{}},"parent":{}}],["connecttoagent",{"_index":193,"name":{"224":{}},"parent":{}}],["connecttopeer",{"_index":145,"name":{"165":{}},"parent":{}}],["constructor",{"_index":12,"name":{"12":{},"62":{},"70":{},"77":{},"102":{},"121":{},"157":{},"173":{},"222":{},"234":{}},"parent":{}}],["createsecret",{"_index":156,"name":{"185":{}},"parent":{}}],["createsecretrequestmessage",{"_index":161,"name":{"191":{}},"parent":{}}],["createsecretresponsemessage",{"_index":162,"name":{"192":{}},"parent":{}}],["createvault",{"_index":91,"name":{"104":{}},"parent":{}}],["createx509certificate",{"_index":203,"name":{"239":{}},"parent":{}}],["daemon_script_path",{"_index":196,"name":{"227":{}},"parent":{}}],["decryptdata",{"_index":4,"name":{"4":{},"38":{}},"parent":{}}],["defaultmaxlisteners",{"_index":123,"name":{"139":{}},"parent":{}}],["derivekey",{"_index":154,"name":{"178":{}},"parent":{}}],["derivekeyrequestmessage",{"_index":163,"name":{"193":{}},"parent":{}}],["derivekeyresponsemessage",{"_index":164,"name":{"194":{}},"parent":{}}],["destroysecret",{"_index":157,"name":{"186":{}},"parent":{}}],["destroysecretrequestmessage",{"_index":165,"name":{"195":{}},"parent":{}}],["destroysecretresponsemessage",{"_index":166,"name":{"196":{}},"parent":{}}],["destroyvault",{"_index":94,"name":{"107":{},"183":{}},"parent":{}}],["destroyvaultrequestmessage",{"_index":167,"name":{"197":{}},"parent":{}}],["destroyvaultresponsemessage",{"_index":168,"name":{"198":{}},"parent":{}}],["disconnect",{"_index":63,"name":{"72":{}},"parent":{}}],["emit",{"_index":118,"name":{"133":{}},"parent":{}}],["encryptdata",{"_index":3,"name":{"3":{},"37":{}},"parent":{}}],["encryptedfs",{"_index":68,"name":{"78":{}},"parent":{}}],["encryptedlocalpubkey",{"_index":129,"name":{"146":{}},"parent":{}}],["encryptedpeerpubkey",{"_index":131,"name":{"147":{}},"parent":{}}],["encryptedrandommessage",{"_index":133,"name":{"149":{}},"parent":{}}],["errormessage",{"_index":169,"name":{"199":{}},"parent":{}}],["eventnames",{"_index":122,"name":{"137":{}},"parent":{}}],["exportkey",{"_index":30,"name":{"30":{}},"parent":{}}],["exportkeysync",{"_index":29,"name":{"29":{}},"parent":{}}],["exportprivatekey",{"_index":23,"name":{"23":{}},"parent":{}}],["exportpublickey",{"_index":24,"name":{"24":{}},"parent":{}}],["filesystem",{"_index":86,"name":{"97":{}},"parent":{}}],["findpubkey",{"_index":143,"name":{"163":{}},"parent":{}}],["findsocialuser",{"_index":144,"name":{"164":{}},"parent":{}}],["finduser",{"_index":135,"name":{"152":{},"168":{}},"parent":{}}],["firstpromisefulfilled",{"_index":98,"name":{"111":{}},"parent":{}}],["fromaddressinfo",{"_index":56,"name":{"64":{}},"parent":{}}],["generatekey",{"_index":26,"name":{"26":{}},"parent":{}}],["generatekeypair",{"_index":14,"name":{"14":{}},"parent":{}}],["generatekeysync",{"_index":25,"name":{"25":{}},"parent":{}}],["getagentstatus",{"_index":158,"name":{"188":{}},"parent":{}}],["getidentityfromprivatekey",{"_index":32,"name":{"32":{}},"parent":{}}],["getidentityfrompublickey",{"_index":31,"name":{"31":{}},"parent":{}}],["getkey",{"_index":36,"name":{"41":{}},"parent":{}}],["getkeypair",{"_index":15,"name":{"15":{}},"parent":{}}],["getlocalpeerinfo",{"_index":139,"name":{"158":{}},"parent":{}}],["getmaxlisteners",{"_index":115,"name":{"130":{}},"parent":{}}],["getpeer",{"_index":141,"name":{"161":{}},"parent":{}}],["getprivatekey",{"_index":18,"name":{"18":{}},"parent":{}}],["getpublickey",{"_index":17,"name":{"17":{}},"parent":{}}],["getsecret",{"_index":72,"name":{"82":{},"187":{}},"parent":{}}],["getsecretrequestmessage",{"_index":170,"name":{"200":{}},"parent":{}}],["getsecretresponsemessage",{"_index":171,"name":{"201":{}},"parent":{}}],["getvault",{"_index":90,"name":{"103":{}},"parent":{}}],["handshakemessage",{"_index":124,"name":{"140":{}},"parent":{}}],["haskey",{"_index":37,"name":{"42":{}},"parent":{}}],["haspeer",{"_index":142,"name":{"162":{}},"parent":{}}],["haspublickey",{"_index":16,"name":{"16":{}},"parent":{}}],["identityloaded",{"_index":13,"name":{"13":{}},"parent":{}}],["importkey",{"_index":28,"name":{"28":{}},"parent":{}}],["importkeysync",{"_index":27,"name":{"27":{}},"parent":{}}],["initrepository",{"_index":81,"name":{"91":{}},"parent":{}}],["interval",{"_index":104,"name":{"118":{}},"parent":{}}],["invertpromise",{"_index":97,"name":{"110":{}},"parent":{}}],["ip",{"_index":53,"name":{"60":{}},"parent":{}}],["key",{"_index":8,"name":{"9":{},"56":{}},"parent":{}}],["keybasediscovery",{"_index":146,"name":{"166":{}},"parent":{"167":{},"168":{}}}],["keymanager",{"_index":5,"name":{"6":{},"98":{},"116":{},"232":{}},"parent":{"7":{},"8":{},"12":{},"13":{},"14":{},"15":{},"16":{},"17":{},"18":{},"19":{},"20":{},"21":{},"22":{},"23":{},"24":{},"25":{},"26":{},"27":{},"28":{},"29":{},"30":{},"31":{},"32":{},"33":{},"34":{},"35":{},"36":{},"37":{},"38":{},"39":{},"40":{},"41":{},"42":{}}}],["keymanager.pkiinfo",{"_index":9,"name":{},"parent":{"9":{},"10":{},"11":{}}}],["keymanagermetadata",{"_index":38,"name":{"43":{}},"parent":{"44":{}}}],["keymanagermetadata.__type",{"_index":41,"name":{},"parent":{"45":{},"46":{},"47":{},"48":{},"49":{}}}],["keymanagerworker",{"_index":0,"name":{"0":{},"5":{}},"parent":{"1":{},"2":{},"3":{},"4":{}}}],["keypair",{"_index":46,"name":{"50":{}},"parent":{"51":{}}}],["keypair.__type",{"_index":48,"name":{},"parent":{"52":{},"53":{}}}],["listenercount",{"_index":119,"name":{"134":{},"138":{}},"parent":{}}],["listeners",{"_index":116,"name":{"131":{}},"parent":{}}],["listnodes",{"_index":153,"name":{"177":{}},"parent":{}}],["listnodesrequestmessage",{"_index":172,"name":{"202":{}},"parent":{}}],["listnodesresponsemessage",{"_index":173,"name":{"203":{}},"parent":{}}],["listsecrets",{"_index":74,"name":{"84":{},"184":{}},"parent":{}}],["listsecretsrequestmessage",{"_index":174,"name":{"204":{}},"parent":{}}],["listsecretsresponsemessage",{"_index":175,"name":{"205":{}},"parent":{}}],["listvaults",{"_index":95,"name":{"108":{},"181":{}},"parent":{}}],["listvaultsrequestmessage",{"_index":176,"name":{"206":{}},"parent":{}}],["listvaultsresponsemessage",{"_index":177,"name":{"207":{}},"parent":{}}],["loadkeypair",{"_index":19,"name":{"19":{}},"parent":{}}],["loadpkiinfo",{"_index":35,"name":{"40":{}},"parent":{}}],["loadprivatekey",{"_index":20,"name":{"20":{}},"parent":{}}],["loadpublickey",{"_index":21,"name":{"21":{}},"parent":{}}],["localpeerinfo",{"_index":102,"name":{"115":{},"171":{}},"parent":{}}],["logpath",{"_index":195,"name":{"226":{}},"parent":{}}],["metadatapath",{"_index":87,"name":{"99":{}},"parent":{}}],["multicastbroadcaster",{"_index":99,"name":{"112":{},"154":{}},"parent":{"113":{},"115":{},"116":{},"117":{},"118":{},"119":{},"120":{},"121":{},"122":{},"123":{},"124":{},"125":{},"126":{},"127":{},"128":{},"129":{},"130":{},"131":{},"132":{},"133":{},"134":{},"135":{},"136":{},"137":{},"138":{},"139":{}}}],["multicastbroadcaster.addpeer",{"_index":101,"name":{},"parent":{"114":{}}}],["n_bits",{"_index":200,"name":{"236":{}},"parent":{}}],["name",{"_index":66,"name":{"75":{},"151":{},"167":{}},"parent":{}}],["newnode",{"_index":152,"name":{"176":{}},"parent":{}}],["newnoderequestmessage",{"_index":178,"name":{"208":{}},"parent":{}}],["newnoderesponsemessage",{"_index":179,"name":{"209":{}},"parent":{}}],["newvault",{"_index":155,"name":{"182":{}},"parent":{}}],["newvaultrequestmessage",{"_index":180,"name":{"210":{}},"parent":{}}],["newvaultresponsemessage",{"_index":181,"name":{"211":{}},"parent":{}}],["off",{"_index":112,"name":{"127":{}},"parent":{}}],["on",{"_index":109,"name":{"124":{}},"parent":{}}],["once",{"_index":110,"name":{"125":{}},"parent":{}}],["organization_name",{"_index":202,"name":{"238":{}},"parent":{}}],["parse",{"_index":55,"name":{"63":{}},"parent":{}}],["peercanaccess",{"_index":79,"name":{"89":{}},"parent":{}}],["peerinfo",{"_index":58,"name":{"66":{}},"parent":{"67":{},"68":{},"69":{},"70":{},"71":{},"72":{},"73":{}}}],["peerinfomessage",{"_index":125,"name":{"141":{}},"parent":{}}],["peermanager",{"_index":136,"name":{"153":{},"233":{}},"parent":{"154":{},"155":{},"156":{},"157":{},"158":{},"159":{},"160":{},"161":{},"162":{},"163":{},"164":{},"165":{}}}],["peermanagermetadata",{"_index":147,"name":{"169":{}},"parent":{"170":{}}}],["peermanagermetadata.__type",{"_index":148,"name":{},"parent":{"171":{}}}],["peermessage",{"_index":128,"name":{"144":{}},"parent":{"145":{}}}],["peermessage.__type",{"_index":130,"name":{},"parent":{"146":{},"147":{},"148":{},"149":{}}}],["peerpubkeymessages",{"_index":106,"name":{"120":{}},"parent":{}}],["pkicertpath",{"_index":44,"name":{"48":{}},"parent":{}}],["pkiinfo",{"_index":7,"name":{"8":{},"39":{}},"parent":{}}],["pkikeypath",{"_index":43,"name":{"47":{}},"parent":{}}],["pkinfo",{"_index":50,"name":{"54":{}},"parent":{"55":{}}}],["pkinfo.__type",{"_index":51,"name":{},"parent":{"56":{},"57":{},"58":{}}}],["polykey",{"_index":198,"name":{"229":{}},"parent":{"230":{},"231":{},"232":{},"233":{},"234":{}}}],["polykeyagent",{"_index":189,"name":{"219":{}},"parent":{"220":{},"221":{},"222":{},"223":{},"224":{},"225":{},"226":{},"227":{},"228":{}}}],["polykeyclient",{"_index":149,"name":{"172":{}},"parent":{"173":{},"174":{},"175":{},"176":{},"177":{},"178":{},"179":{},"180":{},"181":{},"182":{},"183":{},"184":{},"185":{},"186":{},"187":{},"188":{},"189":{}}}],["polykeypath",{"_index":6,"name":{"7":{},"96":{},"230":{}},"parent":{}}],["port",{"_index":54,"name":{"61":{}},"parent":{}}],["prependlistener",{"_index":120,"name":{"135":{}},"parent":{}}],["prependoncelistener",{"_index":121,"name":{"136":{}},"parent":{}}],["private",{"_index":47,"name":{"52":{}},"parent":{}}],["privatekeypath",{"_index":40,"name":{"45":{}},"parent":{}}],["protobuf",{"_index":204,"name":{"240":{}},"parent":{}}],["public",{"_index":49,"name":{"53":{}},"parent":{}}],["publickey",{"_index":59,"name":{"67":{}},"parent":{}}],["publickeyinfrastructure",{"_index":199,"name":{"235":{}},"parent":{"236":{},"237":{},"238":{},"239":{}}}],["publickeypath",{"_index":42,"name":{"46":{}},"parent":{}}],["pullvault",{"_index":80,"name":{"90":{}},"parent":{}}],["queryinterval",{"_index":105,"name":{"119":{}},"parent":{}}],["randomstring",{"_index":96,"name":{"109":{}},"parent":{}}],["rawlisteners",{"_index":117,"name":{"132":{}},"parent":{}}],["rawrandommessage",{"_index":132,"name":{"148":{}},"parent":{}}],["reader",{"_index":205,"name":{"241":{}},"parent":{}}],["registernode",{"_index":151,"name":{"175":{}},"parent":{}}],["registernoderequestmessage",{"_index":182,"name":{"212":{}},"parent":{}}],["registernoderesponsemessage",{"_index":183,"name":{"213":{}},"parent":{}}],["removealllisteners",{"_index":113,"name":{"128":{}},"parent":{}}],["removelistener",{"_index":111,"name":{"126":{}},"parent":{}}],["removesecret",{"_index":73,"name":{"83":{}},"parent":{}}],["requestpeercontact",{"_index":107,"name":{"122":{}},"parent":{}}],["root",{"_index":208,"name":{"244":{}},"parent":{}}],["secretexists",{"_index":69,"name":{"79":{}},"parent":{}}],["sendrequesttoagent",{"_index":150,"name":{"174":{}},"parent":{}}],["server",{"_index":137,"name":{"155":{}},"parent":{}}],["serverstarted",{"_index":138,"name":{"156":{}},"parent":{}}],["setmaxlisteners",{"_index":114,"name":{"129":{}},"parent":{}}],["sharedpubkeys",{"_index":83,"name":{"94":{}},"parent":{}}],["sharevault",{"_index":77,"name":{"87":{}},"parent":{}}],["signdata",{"_index":1,"name":{"1":{},"33":{}},"parent":{}}],["signfile",{"_index":33,"name":{"34":{},"179":{}},"parent":{}}],["signfilerequestmessage",{"_index":184,"name":{"214":{}},"parent":{}}],["signfileresponsemessage",{"_index":185,"name":{"215":{}},"parent":{}}],["socialdiscovery",{"_index":134,"name":{"150":{}},"parent":{"151":{},"152":{}}}],["socket",{"_index":103,"name":{"117":{}},"parent":{}}],["socketpath",{"_index":194,"name":{"225":{}},"parent":{}}],["startagent",{"_index":197,"name":{"228":{}},"parent":{}}],["stop",{"_index":192,"name":{"223":{}},"parent":{}}],["stopagent",{"_index":159,"name":{"189":{}},"parent":{}}],["tagvault",{"_index":75,"name":{"85":{}},"parent":{}}],["tostring",{"_index":57,"name":{"65":{}},"parent":{}}],["type",{"_index":186,"name":{"216":{}},"parent":{}}],["udp_multicast_addr",{"_index":127,"name":{"143":{}},"parent":{}}],["udp_multicast_port",{"_index":126,"name":{"142":{}},"parent":{}}],["unlockednodepaths",{"_index":191,"name":{"221":{}},"parent":{}}],["unlockidentity",{"_index":22,"name":{"22":{}},"parent":{}}],["unsharevault",{"_index":78,"name":{"88":{}},"parent":{}}],["untagvault",{"_index":76,"name":{"86":{}},"parent":{}}],["updatesecret",{"_index":71,"name":{"81":{}},"parent":{}}],["util",{"_index":207,"name":{"243":{}},"parent":{}}],["vault",{"_index":65,"name":{"74":{}},"parent":{"75":{},"76":{},"77":{},"78":{},"79":{},"80":{},"81":{},"82":{},"83":{},"84":{},"85":{},"86":{},"87":{},"88":{},"89":{},"90":{},"91":{}}}],["vaultexists",{"_index":93,"name":{"106":{}},"parent":{}}],["vaultkeys",{"_index":89,"name":{"101":{}},"parent":{}}],["vaultmanager",{"_index":85,"name":{"95":{},"231":{}},"parent":{"96":{},"97":{},"98":{},"99":{},"100":{},"101":{},"102":{},"103":{},"104":{},"105":{},"106":{},"107":{},"108":{}}}],["vaultmetadata",{"_index":82,"name":{"92":{}},"parent":{"93":{}}}],["vaultmetadata.__type",{"_index":84,"name":{},"parent":{"94":{}}}],["vaultpath",{"_index":67,"name":{"76":{}},"parent":{}}],["vaults",{"_index":88,"name":{"100":{}},"parent":{}}],["verifydata",{"_index":2,"name":{"2":{},"35":{}},"parent":{}}],["verifyfile",{"_index":34,"name":{"36":{},"180":{}},"parent":{}}],["verifyfilerequestmessage",{"_index":187,"name":{"217":{}},"parent":{}}],["verifyfileresponsemessage",{"_index":188,"name":{"218":{}},"parent":{}}],["writer",{"_index":206,"name":{"242":{}},"parent":{}}]],"pipeline":[]}} \ No newline at end of file +{"kinds":{"32":"Variable","64":"Function","128":"Class","256":"Interface","512":"Constructor","1024":"Property","2048":"Method","65536":"Type literal","262144":"Accessor","2097152":"Object literal","4194304":"Type alias"},"rows":[{"id":0,"kind":2097152,"name":"keyManagerWorker","url":"globals.html#keymanagerworker","classes":"tsd-kind-object-literal"},{"id":1,"kind":64,"name":"signData","url":"globals.html#keymanagerworker.signdata","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keyManagerWorker"},{"id":2,"kind":64,"name":"verifyData","url":"globals.html#keymanagerworker.verifydata","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keyManagerWorker"},{"id":3,"kind":64,"name":"encryptData","url":"globals.html#keymanagerworker.encryptdata","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keyManagerWorker"},{"id":4,"kind":64,"name":"decryptData","url":"globals.html#keymanagerworker.decryptdata","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keyManagerWorker"},{"id":5,"kind":4194304,"name":"KeyManagerWorker","url":"globals.html#keymanagerworker","classes":"tsd-kind-type-alias"},{"id":6,"kind":128,"name":"KeyManager","url":"classes/keymanager.html","classes":"tsd-kind-class"},{"id":7,"kind":1024,"name":"polykeyPath","url":"classes/keymanager.html#polykeypath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"KeyManager"},{"id":8,"kind":2097152,"name":"pkiInfo","url":"classes/keymanager.html#pkiinfo-1","classes":"tsd-kind-object-literal tsd-parent-kind-class","parent":"KeyManager"},{"id":9,"kind":32,"name":"key","url":"classes/keymanager.html#pkiinfo-1.key","classes":"tsd-kind-variable tsd-parent-kind-object-literal","parent":"KeyManager.pkiInfo"},{"id":10,"kind":32,"name":"cert","url":"classes/keymanager.html#pkiinfo-1.cert","classes":"tsd-kind-variable tsd-parent-kind-object-literal","parent":"KeyManager.pkiInfo"},{"id":11,"kind":32,"name":"caCert","url":"classes/keymanager.html#pkiinfo-1.cacert","classes":"tsd-kind-variable tsd-parent-kind-object-literal","parent":"KeyManager.pkiInfo"},{"id":12,"kind":512,"name":"constructor","url":"classes/keymanager.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"KeyManager"},{"id":13,"kind":262144,"name":"identityLoaded","url":"classes/keymanager.html#identityloaded","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"KeyManager"},{"id":14,"kind":2048,"name":"generateKeyPair","url":"classes/keymanager.html#generatekeypair","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":15,"kind":2048,"name":"getKeyPair","url":"classes/keymanager.html#getkeypair","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":16,"kind":2048,"name":"hasPublicKey","url":"classes/keymanager.html#haspublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":17,"kind":2048,"name":"getPublicKey","url":"classes/keymanager.html#getpublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":18,"kind":2048,"name":"getPrivateKey","url":"classes/keymanager.html#getprivatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":19,"kind":2048,"name":"loadKeyPair","url":"classes/keymanager.html#loadkeypair","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":20,"kind":2048,"name":"loadPrivateKey","url":"classes/keymanager.html#loadprivatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":21,"kind":2048,"name":"loadPublicKey","url":"classes/keymanager.html#loadpublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":22,"kind":2048,"name":"unlockIdentity","url":"classes/keymanager.html#unlockidentity","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":23,"kind":2048,"name":"exportPrivateKey","url":"classes/keymanager.html#exportprivatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":24,"kind":2048,"name":"exportPublicKey","url":"classes/keymanager.html#exportpublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":25,"kind":2048,"name":"generateKeySync","url":"classes/keymanager.html#generatekeysync","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":26,"kind":2048,"name":"generateKey","url":"classes/keymanager.html#generatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":27,"kind":2048,"name":"importKeySync","url":"classes/keymanager.html#importkeysync","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":28,"kind":2048,"name":"importKey","url":"classes/keymanager.html#importkey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":29,"kind":2048,"name":"exportKeySync","url":"classes/keymanager.html#exportkeysync","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":30,"kind":2048,"name":"exportKey","url":"classes/keymanager.html#exportkey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":31,"kind":2048,"name":"getIdentityFromPublicKey","url":"classes/keymanager.html#getidentityfrompublickey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":32,"kind":2048,"name":"getIdentityFromPrivateKey","url":"classes/keymanager.html#getidentityfromprivatekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":33,"kind":2048,"name":"signData","url":"classes/keymanager.html#signdata","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":34,"kind":2048,"name":"signFile","url":"classes/keymanager.html#signfile","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":35,"kind":2048,"name":"verifyData","url":"classes/keymanager.html#verifydata","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":36,"kind":2048,"name":"verifyFile","url":"classes/keymanager.html#verifyfile","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":37,"kind":2048,"name":"encryptData","url":"classes/keymanager.html#encryptdata","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":38,"kind":2048,"name":"decryptData","url":"classes/keymanager.html#decryptdata","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":39,"kind":262144,"name":"PKIInfo","url":"classes/keymanager.html#pkiinfo","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"KeyManager"},{"id":40,"kind":2048,"name":"loadPKIInfo","url":"classes/keymanager.html#loadpkiinfo","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":41,"kind":2048,"name":"getKey","url":"classes/keymanager.html#getkey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":42,"kind":2048,"name":"hasKey","url":"classes/keymanager.html#haskey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"KeyManager"},{"id":43,"kind":4194304,"name":"KeyManagerMetadata","url":"globals.html#keymanagermetadata","classes":"tsd-kind-type-alias"},{"id":44,"kind":65536,"name":"__type","url":"globals.html#keymanagermetadata.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"KeyManagerMetadata"},{"id":45,"kind":32,"name":"privateKeyPath","url":"globals.html#keymanagermetadata.__type.privatekeypath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":46,"kind":32,"name":"publicKeyPath","url":"globals.html#keymanagermetadata.__type.publickeypath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":47,"kind":32,"name":"pkiKeyPath","url":"globals.html#keymanagermetadata.__type.pkikeypath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":48,"kind":32,"name":"pkiCertPath","url":"globals.html#keymanagermetadata.__type.pkicertpath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":49,"kind":32,"name":"caCertPath","url":"globals.html#keymanagermetadata.__type.cacertpath","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyManagerMetadata.__type"},{"id":50,"kind":4194304,"name":"KeyPair","url":"globals.html#keypair","classes":"tsd-kind-type-alias"},{"id":51,"kind":65536,"name":"__type","url":"globals.html#keypair.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"KeyPair"},{"id":52,"kind":32,"name":"private","url":"globals.html#keypair.__type.private","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyPair.__type"},{"id":53,"kind":32,"name":"public","url":"globals.html#keypair.__type.public","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"KeyPair.__type"},{"id":54,"kind":4194304,"name":"PKInfo","url":"globals.html#pkinfo","classes":"tsd-kind-type-alias"},{"id":55,"kind":65536,"name":"__type","url":"globals.html#pkinfo.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"PKInfo"},{"id":56,"kind":32,"name":"key","url":"globals.html#pkinfo.__type.key","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PKInfo.__type"},{"id":57,"kind":32,"name":"cert","url":"globals.html#pkinfo.__type.cert","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PKInfo.__type"},{"id":58,"kind":32,"name":"caCert","url":"globals.html#pkinfo.__type.cacert","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PKInfo.__type"},{"id":59,"kind":128,"name":"Address","url":"classes/address.html","classes":"tsd-kind-class"},{"id":60,"kind":1024,"name":"ip","url":"classes/address.html#ip","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Address"},{"id":61,"kind":1024,"name":"port","url":"classes/address.html#port","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Address"},{"id":62,"kind":512,"name":"constructor","url":"classes/address.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"Address"},{"id":63,"kind":2048,"name":"parse","url":"classes/address.html#parse","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"Address"},{"id":64,"kind":2048,"name":"fromAddressInfo","url":"classes/address.html#fromaddressinfo","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"Address"},{"id":65,"kind":2048,"name":"toString","url":"classes/address.html#tostring","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Address"},{"id":66,"kind":128,"name":"PeerInfo","url":"classes/peerinfo.html","classes":"tsd-kind-class"},{"id":67,"kind":1024,"name":"publicKey","url":"classes/peerinfo.html#publickey","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerInfo"},{"id":68,"kind":1024,"name":"addresses","url":"classes/peerinfo.html#addresses","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerInfo"},{"id":69,"kind":1024,"name":"connectedAddr","url":"classes/peerinfo.html#connectedaddr","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerInfo"},{"id":70,"kind":512,"name":"constructor","url":"classes/peerinfo.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"PeerInfo"},{"id":71,"kind":2048,"name":"connect","url":"classes/peerinfo.html#connect","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerInfo"},{"id":72,"kind":2048,"name":"disconnect","url":"classes/peerinfo.html#disconnect","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerInfo"},{"id":73,"kind":262144,"name":"AdressStringList","url":"classes/peerinfo.html#adressstringlist","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"PeerInfo"},{"id":74,"kind":128,"name":"Vault","url":"classes/vault.html","classes":"tsd-kind-class"},{"id":75,"kind":1024,"name":"name","url":"classes/vault.html#name","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Vault"},{"id":76,"kind":1024,"name":"vaultPath","url":"classes/vault.html#vaultpath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Vault"},{"id":77,"kind":512,"name":"constructor","url":"classes/vault.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"Vault"},{"id":78,"kind":262144,"name":"EncryptedFS","url":"classes/vault.html#encryptedfs","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"Vault"},{"id":79,"kind":2048,"name":"secretExists","url":"classes/vault.html#secretexists","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":80,"kind":2048,"name":"addSecret","url":"classes/vault.html#addsecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":81,"kind":2048,"name":"updateSecret","url":"classes/vault.html#updatesecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":82,"kind":2048,"name":"getSecret","url":"classes/vault.html#getsecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":83,"kind":2048,"name":"removeSecret","url":"classes/vault.html#removesecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":84,"kind":2048,"name":"listSecrets","url":"classes/vault.html#listsecrets","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":85,"kind":2048,"name":"tagVault","url":"classes/vault.html#tagvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":86,"kind":2048,"name":"untagVault","url":"classes/vault.html#untagvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":87,"kind":2048,"name":"shareVault","url":"classes/vault.html#sharevault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":88,"kind":2048,"name":"unshareVault","url":"classes/vault.html#unsharevault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":89,"kind":2048,"name":"peerCanAccess","url":"classes/vault.html#peercanaccess","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":90,"kind":2048,"name":"pullVault","url":"classes/vault.html#pullvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":91,"kind":2048,"name":"getVaultHistory","url":"classes/vault.html#getvaulthistory","classes":"tsd-kind-method tsd-parent-kind-class","parent":"Vault"},{"id":92,"kind":4194304,"name":"VaultMetadata","url":"globals.html#vaultmetadata","classes":"tsd-kind-type-alias"},{"id":93,"kind":65536,"name":"__type","url":"globals.html#vaultmetadata.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"VaultMetadata"},{"id":94,"kind":32,"name":"sharedPubKeys","url":"globals.html#vaultmetadata.__type.sharedpubkeys","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"VaultMetadata.__type"},{"id":95,"kind":128,"name":"VaultManager","url":"classes/vaultmanager.html","classes":"tsd-kind-class"},{"id":96,"kind":1024,"name":"polykeyPath","url":"classes/vaultmanager.html#polykeypath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":97,"kind":1024,"name":"fileSystem","url":"classes/vaultmanager.html#filesystem","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":98,"kind":1024,"name":"keyManager","url":"classes/vaultmanager.html#keymanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":99,"kind":1024,"name":"metadataPath","url":"classes/vaultmanager.html#metadatapath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":100,"kind":1024,"name":"vaults","url":"classes/vaultmanager.html#vaults","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":101,"kind":1024,"name":"vaultKeys","url":"classes/vaultmanager.html#vaultkeys","classes":"tsd-kind-property tsd-parent-kind-class","parent":"VaultManager"},{"id":102,"kind":512,"name":"constructor","url":"classes/vaultmanager.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"VaultManager"},{"id":103,"kind":2048,"name":"getVault","url":"classes/vaultmanager.html#getvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":104,"kind":2048,"name":"createVault","url":"classes/vaultmanager.html#createvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":105,"kind":2048,"name":"cloneVault","url":"classes/vaultmanager.html#clonevault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":106,"kind":2048,"name":"vaultExists","url":"classes/vaultmanager.html#vaultexists","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":107,"kind":2048,"name":"destroyVault","url":"classes/vaultmanager.html#destroyvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":108,"kind":2048,"name":"listVaults","url":"classes/vaultmanager.html#listvaults","classes":"tsd-kind-method tsd-parent-kind-class","parent":"VaultManager"},{"id":109,"kind":64,"name":"randomString","url":"globals.html#randomstring","classes":"tsd-kind-function"},{"id":110,"kind":64,"name":"invertPromise","url":"globals.html#invertpromise","classes":"tsd-kind-function tsd-has-type-parameter"},{"id":111,"kind":64,"name":"firstPromiseFulfilled","url":"globals.html#firstpromisefulfilled","classes":"tsd-kind-function tsd-has-type-parameter"},{"id":112,"kind":128,"name":"MulticastBroadcaster","url":"classes/multicastbroadcaster.html","classes":"tsd-kind-class"},{"id":113,"kind":1024,"name":"addPeer","url":"classes/multicastbroadcaster.html#addpeer","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":114,"kind":65536,"name":"__type","url":"classes/multicastbroadcaster.html#addpeer.__type","classes":"tsd-kind-type-literal tsd-parent-kind-property","parent":"MulticastBroadcaster.addPeer"},{"id":115,"kind":1024,"name":"localPeerInfo","url":"classes/multicastbroadcaster.html#localpeerinfo","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":116,"kind":1024,"name":"keyManager","url":"classes/multicastbroadcaster.html#keymanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":117,"kind":1024,"name":"socket","url":"classes/multicastbroadcaster.html#socket","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":118,"kind":1024,"name":"interval","url":"classes/multicastbroadcaster.html#interval","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":119,"kind":1024,"name":"queryInterval","url":"classes/multicastbroadcaster.html#queryinterval","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":120,"kind":1024,"name":"peerPubKeyMessages","url":"classes/multicastbroadcaster.html#peerpubkeymessages","classes":"tsd-kind-property tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":121,"kind":512,"name":"constructor","url":"classes/multicastbroadcaster.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class tsd-is-overwrite","parent":"MulticastBroadcaster"},{"id":122,"kind":2048,"name":"requestPeerContact","url":"classes/multicastbroadcaster.html#requestpeercontact","classes":"tsd-kind-method tsd-parent-kind-class","parent":"MulticastBroadcaster"},{"id":123,"kind":2048,"name":"addListener","url":"classes/multicastbroadcaster.html#addlistener","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":124,"kind":2048,"name":"on","url":"classes/multicastbroadcaster.html#on","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":125,"kind":2048,"name":"once","url":"classes/multicastbroadcaster.html#once","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":126,"kind":2048,"name":"removeListener","url":"classes/multicastbroadcaster.html#removelistener","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":127,"kind":2048,"name":"off","url":"classes/multicastbroadcaster.html#off","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":128,"kind":2048,"name":"removeAllListeners","url":"classes/multicastbroadcaster.html#removealllisteners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":129,"kind":2048,"name":"setMaxListeners","url":"classes/multicastbroadcaster.html#setmaxlisteners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":130,"kind":2048,"name":"getMaxListeners","url":"classes/multicastbroadcaster.html#getmaxlisteners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":131,"kind":2048,"name":"listeners","url":"classes/multicastbroadcaster.html#listeners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":132,"kind":2048,"name":"rawListeners","url":"classes/multicastbroadcaster.html#rawlisteners","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":133,"kind":2048,"name":"emit","url":"classes/multicastbroadcaster.html#emit","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":134,"kind":2048,"name":"listenerCount","url":"classes/multicastbroadcaster.html#listenercount","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":135,"kind":2048,"name":"prependListener","url":"classes/multicastbroadcaster.html#prependlistener","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":136,"kind":2048,"name":"prependOnceListener","url":"classes/multicastbroadcaster.html#prependoncelistener","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":137,"kind":2048,"name":"eventNames","url":"classes/multicastbroadcaster.html#eventnames","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited","parent":"MulticastBroadcaster"},{"id":138,"kind":2048,"name":"listenerCount","url":"classes/multicastbroadcaster.html#listenercount-1","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-inherited tsd-is-static","parent":"MulticastBroadcaster"},{"id":139,"kind":1024,"name":"defaultMaxListeners","url":"classes/multicastbroadcaster.html#defaultmaxlisteners","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-inherited tsd-is-static","parent":"MulticastBroadcaster"},{"id":140,"kind":32,"name":"HandshakeMessage","url":"globals.html#handshakemessage","classes":"tsd-kind-variable"},{"id":141,"kind":32,"name":"PeerInfoMessage","url":"globals.html#peerinfomessage","classes":"tsd-kind-variable"},{"id":142,"kind":32,"name":"UDP_MULTICAST_PORT","url":"globals.html#udp_multicast_port","classes":"tsd-kind-variable"},{"id":143,"kind":32,"name":"UDP_MULTICAST_ADDR","url":"globals.html#udp_multicast_addr","classes":"tsd-kind-variable"},{"id":144,"kind":4194304,"name":"PeerMessage","url":"globals.html#peermessage","classes":"tsd-kind-type-alias"},{"id":145,"kind":65536,"name":"__type","url":"globals.html#peermessage.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"PeerMessage"},{"id":146,"kind":32,"name":"encryptedLocalPubKey","url":"globals.html#peermessage.__type.encryptedlocalpubkey","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerMessage.__type"},{"id":147,"kind":32,"name":"encryptedPeerPubKey","url":"globals.html#peermessage.__type.encryptedpeerpubkey","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerMessage.__type"},{"id":148,"kind":32,"name":"rawRandomMessage","url":"globals.html#peermessage.__type.rawrandommessage","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerMessage.__type"},{"id":149,"kind":32,"name":"encryptedRandomMessage","url":"globals.html#peermessage.__type.encryptedrandommessage","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerMessage.__type"},{"id":150,"kind":256,"name":"SocialDiscovery","url":"interfaces/socialdiscovery.html","classes":"tsd-kind-interface"},{"id":151,"kind":1024,"name":"name","url":"interfaces/socialdiscovery.html#name","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"SocialDiscovery"},{"id":152,"kind":2048,"name":"findUser","url":"interfaces/socialdiscovery.html#finduser","classes":"tsd-kind-method tsd-parent-kind-interface","parent":"SocialDiscovery"},{"id":153,"kind":128,"name":"PeerManager","url":"classes/peermanager.html","classes":"tsd-kind-class"},{"id":154,"kind":1024,"name":"multicastBroadcaster","url":"classes/peermanager.html#multicastbroadcaster","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerManager"},{"id":155,"kind":1024,"name":"server","url":"classes/peermanager.html#server","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerManager"},{"id":156,"kind":1024,"name":"serverStarted","url":"classes/peermanager.html#serverstarted","classes":"tsd-kind-property tsd-parent-kind-class","parent":"PeerManager"},{"id":157,"kind":512,"name":"constructor","url":"classes/peermanager.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"PeerManager"},{"id":158,"kind":2048,"name":"getLocalPeerInfo","url":"classes/peermanager.html#getlocalpeerinfo","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":159,"kind":2048,"name":"connectLocalPeerInfo","url":"classes/peermanager.html#connectlocalpeerinfo","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":160,"kind":2048,"name":"addPeer","url":"classes/peermanager.html#addpeer","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":161,"kind":2048,"name":"getPeer","url":"classes/peermanager.html#getpeer","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":162,"kind":2048,"name":"hasPeer","url":"classes/peermanager.html#haspeer","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":163,"kind":2048,"name":"findPubKey","url":"classes/peermanager.html#findpubkey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":164,"kind":2048,"name":"findSocialUser","url":"classes/peermanager.html#findsocialuser","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":165,"kind":2048,"name":"connectToPeer","url":"classes/peermanager.html#connecttopeer","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PeerManager"},{"id":166,"kind":2097152,"name":"keybaseDiscovery","url":"globals.html#keybasediscovery","classes":"tsd-kind-object-literal"},{"id":167,"kind":32,"name":"name","url":"globals.html#keybasediscovery.name","classes":"tsd-kind-variable tsd-parent-kind-object-literal","parent":"keybaseDiscovery"},{"id":168,"kind":64,"name":"findUser","url":"globals.html#keybasediscovery.finduser","classes":"tsd-kind-function tsd-parent-kind-object-literal","parent":"keybaseDiscovery"},{"id":169,"kind":4194304,"name":"PeerManagerMetadata","url":"globals.html#peermanagermetadata","classes":"tsd-kind-type-alias"},{"id":170,"kind":65536,"name":"__type","url":"globals.html#peermanagermetadata.__type","classes":"tsd-kind-type-literal tsd-parent-kind-type-alias","parent":"PeerManagerMetadata"},{"id":171,"kind":32,"name":"localPeerInfo","url":"globals.html#peermanagermetadata.__type.localpeerinfo","classes":"tsd-kind-variable tsd-parent-kind-type-literal","parent":"PeerManagerMetadata.__type"},{"id":172,"kind":128,"name":"PolykeyClient","url":"classes/polykeyclient.html","classes":"tsd-kind-class"},{"id":173,"kind":512,"name":"constructor","url":"classes/polykeyclient.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"PolykeyClient"},{"id":174,"kind":2048,"name":"sendRequestToAgent","url":"classes/polykeyclient.html#sendrequesttoagent","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":175,"kind":2048,"name":"registerNode","url":"classes/polykeyclient.html#registernode","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":176,"kind":2048,"name":"newNode","url":"classes/polykeyclient.html#newnode","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":177,"kind":2048,"name":"listNodes","url":"classes/polykeyclient.html#listnodes","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":178,"kind":2048,"name":"deriveKey","url":"classes/polykeyclient.html#derivekey","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":179,"kind":2048,"name":"signFile","url":"classes/polykeyclient.html#signfile","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":180,"kind":2048,"name":"verifyFile","url":"classes/polykeyclient.html#verifyfile","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":181,"kind":2048,"name":"listVaults","url":"classes/polykeyclient.html#listvaults","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":182,"kind":2048,"name":"newVault","url":"classes/polykeyclient.html#newvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":183,"kind":2048,"name":"destroyVault","url":"classes/polykeyclient.html#destroyvault","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":184,"kind":2048,"name":"listSecrets","url":"classes/polykeyclient.html#listsecrets","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":185,"kind":2048,"name":"createSecret","url":"classes/polykeyclient.html#createsecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":186,"kind":2048,"name":"destroySecret","url":"classes/polykeyclient.html#destroysecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":187,"kind":2048,"name":"getSecret","url":"classes/polykeyclient.html#getsecret","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":188,"kind":2048,"name":"getAgentStatus","url":"classes/polykeyclient.html#getagentstatus","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":189,"kind":2048,"name":"stopAgent","url":"classes/polykeyclient.html#stopagent","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyClient"},{"id":190,"kind":32,"name":"AgentMessage","url":"globals.html#agentmessage","classes":"tsd-kind-variable"},{"id":191,"kind":32,"name":"CreateSecretRequestMessage","url":"globals.html#createsecretrequestmessage","classes":"tsd-kind-variable"},{"id":192,"kind":32,"name":"CreateSecretResponseMessage","url":"globals.html#createsecretresponsemessage","classes":"tsd-kind-variable"},{"id":193,"kind":32,"name":"DeriveKeyRequestMessage","url":"globals.html#derivekeyrequestmessage","classes":"tsd-kind-variable"},{"id":194,"kind":32,"name":"DeriveKeyResponseMessage","url":"globals.html#derivekeyresponsemessage","classes":"tsd-kind-variable"},{"id":195,"kind":32,"name":"DestroySecretRequestMessage","url":"globals.html#destroysecretrequestmessage","classes":"tsd-kind-variable"},{"id":196,"kind":32,"name":"DestroySecretResponseMessage","url":"globals.html#destroysecretresponsemessage","classes":"tsd-kind-variable"},{"id":197,"kind":32,"name":"DestroyVaultRequestMessage","url":"globals.html#destroyvaultrequestmessage","classes":"tsd-kind-variable"},{"id":198,"kind":32,"name":"DestroyVaultResponseMessage","url":"globals.html#destroyvaultresponsemessage","classes":"tsd-kind-variable"},{"id":199,"kind":32,"name":"ErrorMessage","url":"globals.html#errormessage","classes":"tsd-kind-variable"},{"id":200,"kind":32,"name":"GetSecretRequestMessage","url":"globals.html#getsecretrequestmessage","classes":"tsd-kind-variable"},{"id":201,"kind":32,"name":"GetSecretResponseMessage","url":"globals.html#getsecretresponsemessage","classes":"tsd-kind-variable"},{"id":202,"kind":32,"name":"ListNodesRequestMessage","url":"globals.html#listnodesrequestmessage","classes":"tsd-kind-variable"},{"id":203,"kind":32,"name":"ListNodesResponseMessage","url":"globals.html#listnodesresponsemessage","classes":"tsd-kind-variable"},{"id":204,"kind":32,"name":"ListSecretsRequestMessage","url":"globals.html#listsecretsrequestmessage","classes":"tsd-kind-variable"},{"id":205,"kind":32,"name":"ListSecretsResponseMessage","url":"globals.html#listsecretsresponsemessage","classes":"tsd-kind-variable"},{"id":206,"kind":32,"name":"ListVaultsRequestMessage","url":"globals.html#listvaultsrequestmessage","classes":"tsd-kind-variable"},{"id":207,"kind":32,"name":"ListVaultsResponseMessage","url":"globals.html#listvaultsresponsemessage","classes":"tsd-kind-variable"},{"id":208,"kind":32,"name":"NewNodeRequestMessage","url":"globals.html#newnoderequestmessage","classes":"tsd-kind-variable"},{"id":209,"kind":32,"name":"NewNodeResponseMessage","url":"globals.html#newnoderesponsemessage","classes":"tsd-kind-variable"},{"id":210,"kind":32,"name":"NewVaultRequestMessage","url":"globals.html#newvaultrequestmessage","classes":"tsd-kind-variable"},{"id":211,"kind":32,"name":"NewVaultResponseMessage","url":"globals.html#newvaultresponsemessage","classes":"tsd-kind-variable"},{"id":212,"kind":32,"name":"RegisterNodeRequestMessage","url":"globals.html#registernoderequestmessage","classes":"tsd-kind-variable"},{"id":213,"kind":32,"name":"RegisterNodeResponseMessage","url":"globals.html#registernoderesponsemessage","classes":"tsd-kind-variable"},{"id":214,"kind":32,"name":"SignFileRequestMessage","url":"globals.html#signfilerequestmessage","classes":"tsd-kind-variable"},{"id":215,"kind":32,"name":"SignFileResponseMessage","url":"globals.html#signfileresponsemessage","classes":"tsd-kind-variable"},{"id":216,"kind":32,"name":"Type","url":"globals.html#type","classes":"tsd-kind-variable"},{"id":217,"kind":32,"name":"VerifyFileRequestMessage","url":"globals.html#verifyfilerequestmessage","classes":"tsd-kind-variable"},{"id":218,"kind":32,"name":"VerifyFileResponseMessage","url":"globals.html#verifyfileresponsemessage","classes":"tsd-kind-variable"},{"id":219,"kind":128,"name":"PolykeyAgent","url":"classes/polykeyagent.html","classes":"tsd-kind-class"},{"id":220,"kind":262144,"name":"AllNodePaths","url":"classes/polykeyagent.html#allnodepaths","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"PolykeyAgent"},{"id":221,"kind":262144,"name":"UnlockedNodePaths","url":"classes/polykeyagent.html#unlockednodepaths","classes":"tsd-kind-get-signature tsd-parent-kind-class","parent":"PolykeyAgent"},{"id":222,"kind":512,"name":"constructor","url":"classes/polykeyagent.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"PolykeyAgent"},{"id":223,"kind":2048,"name":"stop","url":"classes/polykeyagent.html#stop","classes":"tsd-kind-method tsd-parent-kind-class","parent":"PolykeyAgent"},{"id":224,"kind":2048,"name":"connectToAgent","url":"classes/polykeyagent.html#connecttoagent","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":225,"kind":262144,"name":"SocketPath","url":"classes/polykeyagent.html#socketpath","classes":"tsd-kind-get-signature tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":226,"kind":262144,"name":"LogPath","url":"classes/polykeyagent.html#logpath","classes":"tsd-kind-get-signature tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":227,"kind":1024,"name":"DAEMON_SCRIPT_PATH","url":"classes/polykeyagent.html#daemon_script_path","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":228,"kind":2048,"name":"startAgent","url":"classes/polykeyagent.html#startagent","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"PolykeyAgent"},{"id":229,"kind":128,"name":"Polykey","url":"classes/polykey.html","classes":"tsd-kind-class"},{"id":230,"kind":1024,"name":"polykeyPath","url":"classes/polykey.html#polykeypath","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Polykey"},{"id":231,"kind":1024,"name":"vaultManager","url":"classes/polykey.html#vaultmanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Polykey"},{"id":232,"kind":1024,"name":"keyManager","url":"classes/polykey.html#keymanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Polykey"},{"id":233,"kind":1024,"name":"peerManager","url":"classes/polykey.html#peermanager","classes":"tsd-kind-property tsd-parent-kind-class","parent":"Polykey"},{"id":234,"kind":512,"name":"constructor","url":"classes/polykey.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class","parent":"Polykey"},{"id":235,"kind":128,"name":"PublicKeyInfrastructure","url":"classes/publickeyinfrastructure.html","classes":"tsd-kind-class"},{"id":236,"kind":1024,"name":"N_BITS","url":"classes/publickeyinfrastructure.html#n_bits","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-static","parent":"PublicKeyInfrastructure"},{"id":237,"kind":1024,"name":"COMMON_NAME","url":"classes/publickeyinfrastructure.html#common_name","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-static","parent":"PublicKeyInfrastructure"},{"id":238,"kind":1024,"name":"ORGANIZATION_NAME","url":"classes/publickeyinfrastructure.html#organization_name","classes":"tsd-kind-property tsd-parent-kind-class tsd-is-static","parent":"PublicKeyInfrastructure"},{"id":239,"kind":2048,"name":"createX509Certificate","url":"classes/publickeyinfrastructure.html#createx509certificate","classes":"tsd-kind-method tsd-parent-kind-class tsd-is-static","parent":"PublicKeyInfrastructure"},{"id":240,"kind":32,"name":"$protobuf","url":"globals.html#_protobuf","classes":"tsd-kind-variable"},{"id":241,"kind":32,"name":"$Reader","url":"globals.html#_reader","classes":"tsd-kind-variable"},{"id":242,"kind":32,"name":"$Writer","url":"globals.html#_writer","classes":"tsd-kind-variable"},{"id":243,"kind":32,"name":"$util","url":"globals.html#_util","classes":"tsd-kind-variable"},{"id":244,"kind":32,"name":"$root","url":"globals.html#_root","classes":"tsd-kind-variable"}],"index":{"version":"2.3.8","fields":["name","parent"],"fieldVectors":[["name/0",[0,36.335]],["parent/0",[]],["name/1",[1,45.89]],["parent/1",[0,3.191]],["name/2",[2,45.89]],["parent/2",[0,3.191]],["name/3",[3,45.89]],["parent/3",[0,3.191]],["name/4",[4,45.89]],["parent/4",[0,3.191]],["name/5",[0,36.335]],["parent/5",[]],["name/6",[5,18.81]],["parent/6",[]],["name/7",[6,42.526]],["parent/7",[5,1.652]],["name/8",[7,45.89]],["parent/8",[5,1.652]],["name/9",[8,45.89]],["parent/9",[9,3.735]],["name/10",[10,45.89]],["parent/10",[9,3.735]],["name/11",[11,45.89]],["parent/11",[9,3.735]],["name/12",[12,31.54]],["parent/12",[5,1.652]],["name/13",[13,50.999]],["parent/13",[5,1.652]],["name/14",[14,50.999]],["parent/14",[5,1.652]],["name/15",[15,50.999]],["parent/15",[5,1.652]],["name/16",[16,50.999]],["parent/16",[5,1.652]],["name/17",[17,50.999]],["parent/17",[5,1.652]],["name/18",[18,50.999]],["parent/18",[5,1.652]],["name/19",[19,50.999]],["parent/19",[5,1.652]],["name/20",[20,50.999]],["parent/20",[5,1.652]],["name/21",[21,50.999]],["parent/21",[5,1.652]],["name/22",[22,50.999]],["parent/22",[5,1.652]],["name/23",[23,50.999]],["parent/23",[5,1.652]],["name/24",[24,50.999]],["parent/24",[5,1.652]],["name/25",[25,50.999]],["parent/25",[5,1.652]],["name/26",[26,50.999]],["parent/26",[5,1.652]],["name/27",[27,50.999]],["parent/27",[5,1.652]],["name/28",[28,50.999]],["parent/28",[5,1.652]],["name/29",[29,50.999]],["parent/29",[5,1.652]],["name/30",[30,50.999]],["parent/30",[5,1.652]],["name/31",[31,50.999]],["parent/31",[5,1.652]],["name/32",[32,50.999]],["parent/32",[5,1.652]],["name/33",[1,45.89]],["parent/33",[5,1.652]],["name/34",[33,45.89]],["parent/34",[5,1.652]],["name/35",[2,45.89]],["parent/35",[5,1.652]],["name/36",[34,45.89]],["parent/36",[5,1.652]],["name/37",[3,45.89]],["parent/37",[5,1.652]],["name/38",[4,45.89]],["parent/38",[5,1.652]],["name/39",[7,45.89]],["parent/39",[5,1.652]],["name/40",[35,50.999]],["parent/40",[5,1.652]],["name/41",[36,50.999]],["parent/41",[5,1.652]],["name/42",[37,50.999]],["parent/42",[5,1.652]],["name/43",[38,45.89]],["parent/43",[]],["name/44",[39,34.904]],["parent/44",[38,4.03]],["name/45",[40,50.999]],["parent/45",[41,3.338]],["name/46",[42,50.999]],["parent/46",[41,3.338]],["name/47",[43,50.999]],["parent/47",[41,3.338]],["name/48",[44,50.999]],["parent/48",[41,3.338]],["name/49",[45,50.999]],["parent/49",[41,3.338]],["name/50",[46,45.89]],["parent/50",[]],["name/51",[39,34.904]],["parent/51",[46,4.03]],["name/52",[47,50.999]],["parent/52",[48,4.03]],["name/53",[49,50.999]],["parent/53",[48,4.03]],["name/54",[50,45.89]],["parent/54",[]],["name/55",[39,34.904]],["parent/55",[50,4.03]],["name/56",[8,45.89]],["parent/56",[51,3.735]],["name/57",[10,45.89]],["parent/57",[51,3.735]],["name/58",[11,45.89]],["parent/58",[51,3.735]],["name/59",[52,34.904]],["parent/59",[]],["name/60",[53,50.999]],["parent/60",[52,3.066]],["name/61",[54,50.999]],["parent/61",[52,3.066]],["name/62",[12,31.54]],["parent/62",[52,3.066]],["name/63",[55,50.999]],["parent/63",[52,3.066]],["name/64",[56,50.999]],["parent/64",[52,3.066]],["name/65",[57,50.999]],["parent/65",[52,3.066]],["name/66",[58,33.653]],["parent/66",[]],["name/67",[59,50.999]],["parent/67",[58,2.956]],["name/68",[60,50.999]],["parent/68",[58,2.956]],["name/69",[61,50.999]],["parent/69",[58,2.956]],["name/70",[12,31.54]],["parent/70",[58,2.956]],["name/71",[62,50.999]],["parent/71",[58,2.956]],["name/72",[63,50.999]],["parent/72",[58,2.956]],["name/73",[64,50.999]],["parent/73",[58,2.956]],["name/74",[65,25.876]],["parent/74",[]],["name/75",[66,42.526]],["parent/75",[65,2.273]],["name/76",[67,50.999]],["parent/76",[65,2.273]],["name/77",[12,31.54]],["parent/77",[65,2.273]],["name/78",[68,50.999]],["parent/78",[65,2.273]],["name/79",[69,50.999]],["parent/79",[65,2.273]],["name/80",[70,50.999]],["parent/80",[65,2.273]],["name/81",[71,50.999]],["parent/81",[65,2.273]],["name/82",[72,45.89]],["parent/82",[65,2.273]],["name/83",[73,50.999]],["parent/83",[65,2.273]],["name/84",[74,45.89]],["parent/84",[65,2.273]],["name/85",[75,50.999]],["parent/85",[65,2.273]],["name/86",[76,50.999]],["parent/86",[65,2.273]],["name/87",[77,50.999]],["parent/87",[65,2.273]],["name/88",[78,50.999]],["parent/88",[65,2.273]],["name/89",[79,50.999]],["parent/89",[65,2.273]],["name/90",[80,50.999]],["parent/90",[65,2.273]],["name/91",[81,50.999]],["parent/91",[65,2.273]],["name/92",[82,45.89]],["parent/92",[]],["name/93",[39,34.904]],["parent/93",[82,4.03]],["name/94",[83,50.999]],["parent/94",[84,4.479]],["name/95",[85,27.645]],["parent/95",[]],["name/96",[6,42.526]],["parent/96",[85,2.428]],["name/97",[86,50.999]],["parent/97",[85,2.428]],["name/98",[5,18.81]],["parent/98",[85,2.428]],["name/99",[87,50.999]],["parent/99",[85,2.428]],["name/100",[88,50.999]],["parent/100",[85,2.428]],["name/101",[89,50.999]],["parent/101",[85,2.428]],["name/102",[12,31.54]],["parent/102",[85,2.428]],["name/103",[90,50.999]],["parent/103",[85,2.428]],["name/104",[91,50.999]],["parent/104",[85,2.428]],["name/105",[92,50.999]],["parent/105",[85,2.428]],["name/106",[93,50.999]],["parent/106",[85,2.428]],["name/107",[94,45.89]],["parent/107",[85,2.428]],["name/108",[95,45.89]],["parent/108",[85,2.428]],["name/109",[96,50.999]],["parent/109",[]],["name/110",[97,50.999]],["parent/110",[]],["name/111",[98,50.999]],["parent/111",[]],["name/112",[99,21.554]],["parent/112",[]],["name/113",[100,45.89]],["parent/113",[99,1.893]],["name/114",[39,34.904]],["parent/114",[101,4.479]],["name/115",[102,45.89]],["parent/115",[99,1.893]],["name/116",[5,18.81]],["parent/116",[99,1.893]],["name/117",[103,50.999]],["parent/117",[99,1.893]],["name/118",[104,50.999]],["parent/118",[99,1.893]],["name/119",[105,50.999]],["parent/119",[99,1.893]],["name/120",[106,50.999]],["parent/120",[99,1.893]],["name/121",[12,31.54]],["parent/121",[99,1.893]],["name/122",[107,50.999]],["parent/122",[99,1.893]],["name/123",[108,50.999]],["parent/123",[99,1.893]],["name/124",[109,50.999]],["parent/124",[99,1.893]],["name/125",[110,50.999]],["parent/125",[99,1.893]],["name/126",[111,50.999]],["parent/126",[99,1.893]],["name/127",[112,50.999]],["parent/127",[99,1.893]],["name/128",[113,50.999]],["parent/128",[99,1.893]],["name/129",[114,50.999]],["parent/129",[99,1.893]],["name/130",[115,50.999]],["parent/130",[99,1.893]],["name/131",[116,50.999]],["parent/131",[99,1.893]],["name/132",[117,50.999]],["parent/132",[99,1.893]],["name/133",[118,50.999]],["parent/133",[99,1.893]],["name/134",[119,45.89]],["parent/134",[99,1.893]],["name/135",[120,50.999]],["parent/135",[99,1.893]],["name/136",[121,50.999]],["parent/136",[99,1.893]],["name/137",[122,50.999]],["parent/137",[99,1.893]],["name/138",[119,45.89]],["parent/138",[99,1.893]],["name/139",[123,50.999]],["parent/139",[99,1.893]],["name/140",[124,50.999]],["parent/140",[]],["name/141",[125,50.999]],["parent/141",[]],["name/142",[126,50.999]],["parent/142",[]],["name/143",[127,50.999]],["parent/143",[]],["name/144",[128,45.89]],["parent/144",[]],["name/145",[39,34.904]],["parent/145",[128,4.03]],["name/146",[129,50.999]],["parent/146",[130,3.514]],["name/147",[131,50.999]],["parent/147",[130,3.514]],["name/148",[132,50.999]],["parent/148",[130,3.514]],["name/149",[133,50.999]],["parent/149",[130,3.514]],["name/150",[134,42.526]],["parent/150",[]],["name/151",[66,42.526]],["parent/151",[134,3.735]],["name/152",[135,45.89]],["parent/152",[134,3.735]],["name/153",[136,28.312]],["parent/153",[]],["name/154",[99,21.554]],["parent/154",[136,2.487]],["name/155",[137,50.999]],["parent/155",[136,2.487]],["name/156",[138,50.999]],["parent/156",[136,2.487]],["name/157",[12,31.54]],["parent/157",[136,2.487]],["name/158",[139,50.999]],["parent/158",[136,2.487]],["name/159",[140,50.999]],["parent/159",[136,2.487]],["name/160",[100,45.89]],["parent/160",[136,2.487]],["name/161",[141,50.999]],["parent/161",[136,2.487]],["name/162",[142,50.999]],["parent/162",[136,2.487]],["name/163",[143,50.999]],["parent/163",[136,2.487]],["name/164",[144,50.999]],["parent/164",[136,2.487]],["name/165",[145,50.999]],["parent/165",[136,2.487]],["name/166",[146,42.526]],["parent/166",[]],["name/167",[66,42.526]],["parent/167",[146,3.735]],["name/168",[135,45.89]],["parent/168",[146,3.735]],["name/169",[147,45.89]],["parent/169",[]],["name/170",[39,34.904]],["parent/170",[147,4.03]],["name/171",[102,45.89]],["parent/171",[148,4.479]],["name/172",[149,25.876]],["parent/172",[]],["name/173",[12,31.54]],["parent/173",[149,2.273]],["name/174",[150,50.999]],["parent/174",[149,2.273]],["name/175",[151,50.999]],["parent/175",[149,2.273]],["name/176",[152,50.999]],["parent/176",[149,2.273]],["name/177",[153,50.999]],["parent/177",[149,2.273]],["name/178",[154,50.999]],["parent/178",[149,2.273]],["name/179",[33,45.89]],["parent/179",[149,2.273]],["name/180",[34,45.89]],["parent/180",[149,2.273]],["name/181",[95,45.89]],["parent/181",[149,2.273]],["name/182",[155,50.999]],["parent/182",[149,2.273]],["name/183",[94,45.89]],["parent/183",[149,2.273]],["name/184",[74,45.89]],["parent/184",[149,2.273]],["name/185",[156,50.999]],["parent/185",[149,2.273]],["name/186",[157,50.999]],["parent/186",[149,2.273]],["name/187",[72,45.89]],["parent/187",[149,2.273]],["name/188",[158,50.999]],["parent/188",[149,2.273]],["name/189",[159,50.999]],["parent/189",[149,2.273]],["name/190",[160,50.999]],["parent/190",[]],["name/191",[161,50.999]],["parent/191",[]],["name/192",[162,50.999]],["parent/192",[]],["name/193",[163,50.999]],["parent/193",[]],["name/194",[164,50.999]],["parent/194",[]],["name/195",[165,50.999]],["parent/195",[]],["name/196",[166,50.999]],["parent/196",[]],["name/197",[167,50.999]],["parent/197",[]],["name/198",[168,50.999]],["parent/198",[]],["name/199",[169,50.999]],["parent/199",[]],["name/200",[170,50.999]],["parent/200",[]],["name/201",[171,50.999]],["parent/201",[]],["name/202",[172,50.999]],["parent/202",[]],["name/203",[173,50.999]],["parent/203",[]],["name/204",[174,50.999]],["parent/204",[]],["name/205",[175,50.999]],["parent/205",[]],["name/206",[176,50.999]],["parent/206",[]],["name/207",[177,50.999]],["parent/207",[]],["name/208",[178,50.999]],["parent/208",[]],["name/209",[179,50.999]],["parent/209",[]],["name/210",[180,50.999]],["parent/210",[]],["name/211",[181,50.999]],["parent/211",[]],["name/212",[182,50.999]],["parent/212",[]],["name/213",[183,50.999]],["parent/213",[]],["name/214",[184,50.999]],["parent/214",[]],["name/215",[185,50.999]],["parent/215",[]],["name/216",[186,50.999]],["parent/216",[]],["name/217",[187,50.999]],["parent/217",[]],["name/218",[188,50.999]],["parent/218",[]],["name/219",[189,31.54]],["parent/219",[]],["name/220",[190,50.999]],["parent/220",[189,2.77]],["name/221",[191,50.999]],["parent/221",[189,2.77]],["name/222",[12,31.54]],["parent/222",[189,2.77]],["name/223",[192,50.999]],["parent/223",[189,2.77]],["name/224",[193,50.999]],["parent/224",[189,2.77]],["name/225",[194,50.999]],["parent/225",[189,2.77]],["name/226",[195,50.999]],["parent/226",[189,2.77]],["name/227",[196,50.999]],["parent/227",[189,2.77]],["name/228",[197,50.999]],["parent/228",[189,2.77]],["name/229",[198,36.335]],["parent/229",[]],["name/230",[6,42.526]],["parent/230",[198,3.191]],["name/231",[85,27.645]],["parent/231",[198,3.191]],["name/232",[5,18.81]],["parent/232",[198,3.191]],["name/233",[136,28.312]],["parent/233",[198,3.191]],["name/234",[12,31.54]],["parent/234",[198,3.191]],["name/235",[199,38.006]],["parent/235",[]],["name/236",[200,50.999]],["parent/236",[199,3.338]],["name/237",[201,50.999]],["parent/237",[199,3.338]],["name/238",[202,50.999]],["parent/238",[199,3.338]],["name/239",[203,50.999]],["parent/239",[199,3.338]],["name/240",[204,50.999]],["parent/240",[]],["name/241",[205,50.999]],["parent/241",[]],["name/242",[206,50.999]],["parent/242",[]],["name/243",[207,50.999]],["parent/243",[]],["name/244",[208,50.999]],["parent/244",[]]],"invertedIndex":[["__type",{"_index":39,"name":{"44":{},"51":{},"55":{},"93":{},"114":{},"145":{},"170":{}},"parent":{}}],["addlistener",{"_index":108,"name":{"123":{}},"parent":{}}],["addpeer",{"_index":100,"name":{"113":{},"160":{}},"parent":{}}],["address",{"_index":52,"name":{"59":{}},"parent":{"60":{},"61":{},"62":{},"63":{},"64":{},"65":{}}}],["addresses",{"_index":60,"name":{"68":{}},"parent":{}}],["addsecret",{"_index":70,"name":{"80":{}},"parent":{}}],["adressstringlist",{"_index":64,"name":{"73":{}},"parent":{}}],["agentmessage",{"_index":160,"name":{"190":{}},"parent":{}}],["allnodepaths",{"_index":190,"name":{"220":{}},"parent":{}}],["cacert",{"_index":11,"name":{"11":{},"58":{}},"parent":{}}],["cacertpath",{"_index":45,"name":{"49":{}},"parent":{}}],["cert",{"_index":10,"name":{"10":{},"57":{}},"parent":{}}],["clonevault",{"_index":92,"name":{"105":{}},"parent":{}}],["common_name",{"_index":201,"name":{"237":{}},"parent":{}}],["connect",{"_index":62,"name":{"71":{}},"parent":{}}],["connectedaddr",{"_index":61,"name":{"69":{}},"parent":{}}],["connectlocalpeerinfo",{"_index":140,"name":{"159":{}},"parent":{}}],["connecttoagent",{"_index":193,"name":{"224":{}},"parent":{}}],["connecttopeer",{"_index":145,"name":{"165":{}},"parent":{}}],["constructor",{"_index":12,"name":{"12":{},"62":{},"70":{},"77":{},"102":{},"121":{},"157":{},"173":{},"222":{},"234":{}},"parent":{}}],["createsecret",{"_index":156,"name":{"185":{}},"parent":{}}],["createsecretrequestmessage",{"_index":161,"name":{"191":{}},"parent":{}}],["createsecretresponsemessage",{"_index":162,"name":{"192":{}},"parent":{}}],["createvault",{"_index":91,"name":{"104":{}},"parent":{}}],["createx509certificate",{"_index":203,"name":{"239":{}},"parent":{}}],["daemon_script_path",{"_index":196,"name":{"227":{}},"parent":{}}],["decryptdata",{"_index":4,"name":{"4":{},"38":{}},"parent":{}}],["defaultmaxlisteners",{"_index":123,"name":{"139":{}},"parent":{}}],["derivekey",{"_index":154,"name":{"178":{}},"parent":{}}],["derivekeyrequestmessage",{"_index":163,"name":{"193":{}},"parent":{}}],["derivekeyresponsemessage",{"_index":164,"name":{"194":{}},"parent":{}}],["destroysecret",{"_index":157,"name":{"186":{}},"parent":{}}],["destroysecretrequestmessage",{"_index":165,"name":{"195":{}},"parent":{}}],["destroysecretresponsemessage",{"_index":166,"name":{"196":{}},"parent":{}}],["destroyvault",{"_index":94,"name":{"107":{},"183":{}},"parent":{}}],["destroyvaultrequestmessage",{"_index":167,"name":{"197":{}},"parent":{}}],["destroyvaultresponsemessage",{"_index":168,"name":{"198":{}},"parent":{}}],["disconnect",{"_index":63,"name":{"72":{}},"parent":{}}],["emit",{"_index":118,"name":{"133":{}},"parent":{}}],["encryptdata",{"_index":3,"name":{"3":{},"37":{}},"parent":{}}],["encryptedfs",{"_index":68,"name":{"78":{}},"parent":{}}],["encryptedlocalpubkey",{"_index":129,"name":{"146":{}},"parent":{}}],["encryptedpeerpubkey",{"_index":131,"name":{"147":{}},"parent":{}}],["encryptedrandommessage",{"_index":133,"name":{"149":{}},"parent":{}}],["errormessage",{"_index":169,"name":{"199":{}},"parent":{}}],["eventnames",{"_index":122,"name":{"137":{}},"parent":{}}],["exportkey",{"_index":30,"name":{"30":{}},"parent":{}}],["exportkeysync",{"_index":29,"name":{"29":{}},"parent":{}}],["exportprivatekey",{"_index":23,"name":{"23":{}},"parent":{}}],["exportpublickey",{"_index":24,"name":{"24":{}},"parent":{}}],["filesystem",{"_index":86,"name":{"97":{}},"parent":{}}],["findpubkey",{"_index":143,"name":{"163":{}},"parent":{}}],["findsocialuser",{"_index":144,"name":{"164":{}},"parent":{}}],["finduser",{"_index":135,"name":{"152":{},"168":{}},"parent":{}}],["firstpromisefulfilled",{"_index":98,"name":{"111":{}},"parent":{}}],["fromaddressinfo",{"_index":56,"name":{"64":{}},"parent":{}}],["generatekey",{"_index":26,"name":{"26":{}},"parent":{}}],["generatekeypair",{"_index":14,"name":{"14":{}},"parent":{}}],["generatekeysync",{"_index":25,"name":{"25":{}},"parent":{}}],["getagentstatus",{"_index":158,"name":{"188":{}},"parent":{}}],["getidentityfromprivatekey",{"_index":32,"name":{"32":{}},"parent":{}}],["getidentityfrompublickey",{"_index":31,"name":{"31":{}},"parent":{}}],["getkey",{"_index":36,"name":{"41":{}},"parent":{}}],["getkeypair",{"_index":15,"name":{"15":{}},"parent":{}}],["getlocalpeerinfo",{"_index":139,"name":{"158":{}},"parent":{}}],["getmaxlisteners",{"_index":115,"name":{"130":{}},"parent":{}}],["getpeer",{"_index":141,"name":{"161":{}},"parent":{}}],["getprivatekey",{"_index":18,"name":{"18":{}},"parent":{}}],["getpublickey",{"_index":17,"name":{"17":{}},"parent":{}}],["getsecret",{"_index":72,"name":{"82":{},"187":{}},"parent":{}}],["getsecretrequestmessage",{"_index":170,"name":{"200":{}},"parent":{}}],["getsecretresponsemessage",{"_index":171,"name":{"201":{}},"parent":{}}],["getvault",{"_index":90,"name":{"103":{}},"parent":{}}],["getvaulthistory",{"_index":81,"name":{"91":{}},"parent":{}}],["handshakemessage",{"_index":124,"name":{"140":{}},"parent":{}}],["haskey",{"_index":37,"name":{"42":{}},"parent":{}}],["haspeer",{"_index":142,"name":{"162":{}},"parent":{}}],["haspublickey",{"_index":16,"name":{"16":{}},"parent":{}}],["identityloaded",{"_index":13,"name":{"13":{}},"parent":{}}],["importkey",{"_index":28,"name":{"28":{}},"parent":{}}],["importkeysync",{"_index":27,"name":{"27":{}},"parent":{}}],["interval",{"_index":104,"name":{"118":{}},"parent":{}}],["invertpromise",{"_index":97,"name":{"110":{}},"parent":{}}],["ip",{"_index":53,"name":{"60":{}},"parent":{}}],["key",{"_index":8,"name":{"9":{},"56":{}},"parent":{}}],["keybasediscovery",{"_index":146,"name":{"166":{}},"parent":{"167":{},"168":{}}}],["keymanager",{"_index":5,"name":{"6":{},"98":{},"116":{},"232":{}},"parent":{"7":{},"8":{},"12":{},"13":{},"14":{},"15":{},"16":{},"17":{},"18":{},"19":{},"20":{},"21":{},"22":{},"23":{},"24":{},"25":{},"26":{},"27":{},"28":{},"29":{},"30":{},"31":{},"32":{},"33":{},"34":{},"35":{},"36":{},"37":{},"38":{},"39":{},"40":{},"41":{},"42":{}}}],["keymanager.pkiinfo",{"_index":9,"name":{},"parent":{"9":{},"10":{},"11":{}}}],["keymanagermetadata",{"_index":38,"name":{"43":{}},"parent":{"44":{}}}],["keymanagermetadata.__type",{"_index":41,"name":{},"parent":{"45":{},"46":{},"47":{},"48":{},"49":{}}}],["keymanagerworker",{"_index":0,"name":{"0":{},"5":{}},"parent":{"1":{},"2":{},"3":{},"4":{}}}],["keypair",{"_index":46,"name":{"50":{}},"parent":{"51":{}}}],["keypair.__type",{"_index":48,"name":{},"parent":{"52":{},"53":{}}}],["listenercount",{"_index":119,"name":{"134":{},"138":{}},"parent":{}}],["listeners",{"_index":116,"name":{"131":{}},"parent":{}}],["listnodes",{"_index":153,"name":{"177":{}},"parent":{}}],["listnodesrequestmessage",{"_index":172,"name":{"202":{}},"parent":{}}],["listnodesresponsemessage",{"_index":173,"name":{"203":{}},"parent":{}}],["listsecrets",{"_index":74,"name":{"84":{},"184":{}},"parent":{}}],["listsecretsrequestmessage",{"_index":174,"name":{"204":{}},"parent":{}}],["listsecretsresponsemessage",{"_index":175,"name":{"205":{}},"parent":{}}],["listvaults",{"_index":95,"name":{"108":{},"181":{}},"parent":{}}],["listvaultsrequestmessage",{"_index":176,"name":{"206":{}},"parent":{}}],["listvaultsresponsemessage",{"_index":177,"name":{"207":{}},"parent":{}}],["loadkeypair",{"_index":19,"name":{"19":{}},"parent":{}}],["loadpkiinfo",{"_index":35,"name":{"40":{}},"parent":{}}],["loadprivatekey",{"_index":20,"name":{"20":{}},"parent":{}}],["loadpublickey",{"_index":21,"name":{"21":{}},"parent":{}}],["localpeerinfo",{"_index":102,"name":{"115":{},"171":{}},"parent":{}}],["logpath",{"_index":195,"name":{"226":{}},"parent":{}}],["metadatapath",{"_index":87,"name":{"99":{}},"parent":{}}],["multicastbroadcaster",{"_index":99,"name":{"112":{},"154":{}},"parent":{"113":{},"115":{},"116":{},"117":{},"118":{},"119":{},"120":{},"121":{},"122":{},"123":{},"124":{},"125":{},"126":{},"127":{},"128":{},"129":{},"130":{},"131":{},"132":{},"133":{},"134":{},"135":{},"136":{},"137":{},"138":{},"139":{}}}],["multicastbroadcaster.addpeer",{"_index":101,"name":{},"parent":{"114":{}}}],["n_bits",{"_index":200,"name":{"236":{}},"parent":{}}],["name",{"_index":66,"name":{"75":{},"151":{},"167":{}},"parent":{}}],["newnode",{"_index":152,"name":{"176":{}},"parent":{}}],["newnoderequestmessage",{"_index":178,"name":{"208":{}},"parent":{}}],["newnoderesponsemessage",{"_index":179,"name":{"209":{}},"parent":{}}],["newvault",{"_index":155,"name":{"182":{}},"parent":{}}],["newvaultrequestmessage",{"_index":180,"name":{"210":{}},"parent":{}}],["newvaultresponsemessage",{"_index":181,"name":{"211":{}},"parent":{}}],["off",{"_index":112,"name":{"127":{}},"parent":{}}],["on",{"_index":109,"name":{"124":{}},"parent":{}}],["once",{"_index":110,"name":{"125":{}},"parent":{}}],["organization_name",{"_index":202,"name":{"238":{}},"parent":{}}],["parse",{"_index":55,"name":{"63":{}},"parent":{}}],["peercanaccess",{"_index":79,"name":{"89":{}},"parent":{}}],["peerinfo",{"_index":58,"name":{"66":{}},"parent":{"67":{},"68":{},"69":{},"70":{},"71":{},"72":{},"73":{}}}],["peerinfomessage",{"_index":125,"name":{"141":{}},"parent":{}}],["peermanager",{"_index":136,"name":{"153":{},"233":{}},"parent":{"154":{},"155":{},"156":{},"157":{},"158":{},"159":{},"160":{},"161":{},"162":{},"163":{},"164":{},"165":{}}}],["peermanagermetadata",{"_index":147,"name":{"169":{}},"parent":{"170":{}}}],["peermanagermetadata.__type",{"_index":148,"name":{},"parent":{"171":{}}}],["peermessage",{"_index":128,"name":{"144":{}},"parent":{"145":{}}}],["peermessage.__type",{"_index":130,"name":{},"parent":{"146":{},"147":{},"148":{},"149":{}}}],["peerpubkeymessages",{"_index":106,"name":{"120":{}},"parent":{}}],["pkicertpath",{"_index":44,"name":{"48":{}},"parent":{}}],["pkiinfo",{"_index":7,"name":{"8":{},"39":{}},"parent":{}}],["pkikeypath",{"_index":43,"name":{"47":{}},"parent":{}}],["pkinfo",{"_index":50,"name":{"54":{}},"parent":{"55":{}}}],["pkinfo.__type",{"_index":51,"name":{},"parent":{"56":{},"57":{},"58":{}}}],["polykey",{"_index":198,"name":{"229":{}},"parent":{"230":{},"231":{},"232":{},"233":{},"234":{}}}],["polykeyagent",{"_index":189,"name":{"219":{}},"parent":{"220":{},"221":{},"222":{},"223":{},"224":{},"225":{},"226":{},"227":{},"228":{}}}],["polykeyclient",{"_index":149,"name":{"172":{}},"parent":{"173":{},"174":{},"175":{},"176":{},"177":{},"178":{},"179":{},"180":{},"181":{},"182":{},"183":{},"184":{},"185":{},"186":{},"187":{},"188":{},"189":{}}}],["polykeypath",{"_index":6,"name":{"7":{},"96":{},"230":{}},"parent":{}}],["port",{"_index":54,"name":{"61":{}},"parent":{}}],["prependlistener",{"_index":120,"name":{"135":{}},"parent":{}}],["prependoncelistener",{"_index":121,"name":{"136":{}},"parent":{}}],["private",{"_index":47,"name":{"52":{}},"parent":{}}],["privatekeypath",{"_index":40,"name":{"45":{}},"parent":{}}],["protobuf",{"_index":204,"name":{"240":{}},"parent":{}}],["public",{"_index":49,"name":{"53":{}},"parent":{}}],["publickey",{"_index":59,"name":{"67":{}},"parent":{}}],["publickeyinfrastructure",{"_index":199,"name":{"235":{}},"parent":{"236":{},"237":{},"238":{},"239":{}}}],["publickeypath",{"_index":42,"name":{"46":{}},"parent":{}}],["pullvault",{"_index":80,"name":{"90":{}},"parent":{}}],["queryinterval",{"_index":105,"name":{"119":{}},"parent":{}}],["randomstring",{"_index":96,"name":{"109":{}},"parent":{}}],["rawlisteners",{"_index":117,"name":{"132":{}},"parent":{}}],["rawrandommessage",{"_index":132,"name":{"148":{}},"parent":{}}],["reader",{"_index":205,"name":{"241":{}},"parent":{}}],["registernode",{"_index":151,"name":{"175":{}},"parent":{}}],["registernoderequestmessage",{"_index":182,"name":{"212":{}},"parent":{}}],["registernoderesponsemessage",{"_index":183,"name":{"213":{}},"parent":{}}],["removealllisteners",{"_index":113,"name":{"128":{}},"parent":{}}],["removelistener",{"_index":111,"name":{"126":{}},"parent":{}}],["removesecret",{"_index":73,"name":{"83":{}},"parent":{}}],["requestpeercontact",{"_index":107,"name":{"122":{}},"parent":{}}],["root",{"_index":208,"name":{"244":{}},"parent":{}}],["secretexists",{"_index":69,"name":{"79":{}},"parent":{}}],["sendrequesttoagent",{"_index":150,"name":{"174":{}},"parent":{}}],["server",{"_index":137,"name":{"155":{}},"parent":{}}],["serverstarted",{"_index":138,"name":{"156":{}},"parent":{}}],["setmaxlisteners",{"_index":114,"name":{"129":{}},"parent":{}}],["sharedpubkeys",{"_index":83,"name":{"94":{}},"parent":{}}],["sharevault",{"_index":77,"name":{"87":{}},"parent":{}}],["signdata",{"_index":1,"name":{"1":{},"33":{}},"parent":{}}],["signfile",{"_index":33,"name":{"34":{},"179":{}},"parent":{}}],["signfilerequestmessage",{"_index":184,"name":{"214":{}},"parent":{}}],["signfileresponsemessage",{"_index":185,"name":{"215":{}},"parent":{}}],["socialdiscovery",{"_index":134,"name":{"150":{}},"parent":{"151":{},"152":{}}}],["socket",{"_index":103,"name":{"117":{}},"parent":{}}],["socketpath",{"_index":194,"name":{"225":{}},"parent":{}}],["startagent",{"_index":197,"name":{"228":{}},"parent":{}}],["stop",{"_index":192,"name":{"223":{}},"parent":{}}],["stopagent",{"_index":159,"name":{"189":{}},"parent":{}}],["tagvault",{"_index":75,"name":{"85":{}},"parent":{}}],["tostring",{"_index":57,"name":{"65":{}},"parent":{}}],["type",{"_index":186,"name":{"216":{}},"parent":{}}],["udp_multicast_addr",{"_index":127,"name":{"143":{}},"parent":{}}],["udp_multicast_port",{"_index":126,"name":{"142":{}},"parent":{}}],["unlockednodepaths",{"_index":191,"name":{"221":{}},"parent":{}}],["unlockidentity",{"_index":22,"name":{"22":{}},"parent":{}}],["unsharevault",{"_index":78,"name":{"88":{}},"parent":{}}],["untagvault",{"_index":76,"name":{"86":{}},"parent":{}}],["updatesecret",{"_index":71,"name":{"81":{}},"parent":{}}],["util",{"_index":207,"name":{"243":{}},"parent":{}}],["vault",{"_index":65,"name":{"74":{}},"parent":{"75":{},"76":{},"77":{},"78":{},"79":{},"80":{},"81":{},"82":{},"83":{},"84":{},"85":{},"86":{},"87":{},"88":{},"89":{},"90":{},"91":{}}}],["vaultexists",{"_index":93,"name":{"106":{}},"parent":{}}],["vaultkeys",{"_index":89,"name":{"101":{}},"parent":{}}],["vaultmanager",{"_index":85,"name":{"95":{},"231":{}},"parent":{"96":{},"97":{},"98":{},"99":{},"100":{},"101":{},"102":{},"103":{},"104":{},"105":{},"106":{},"107":{},"108":{}}}],["vaultmetadata",{"_index":82,"name":{"92":{}},"parent":{"93":{}}}],["vaultmetadata.__type",{"_index":84,"name":{},"parent":{"94":{}}}],["vaultpath",{"_index":67,"name":{"76":{}},"parent":{}}],["vaults",{"_index":88,"name":{"100":{}},"parent":{}}],["verifydata",{"_index":2,"name":{"2":{},"35":{}},"parent":{}}],["verifyfile",{"_index":34,"name":{"36":{},"180":{}},"parent":{}}],["verifyfilerequestmessage",{"_index":187,"name":{"217":{}},"parent":{}}],["verifyfileresponsemessage",{"_index":188,"name":{"218":{}},"parent":{}}],["writer",{"_index":206,"name":{"242":{}},"parent":{}}]],"pipeline":[]}} \ No newline at end of file diff --git a/docs/classes/address.html b/docs/classes/address.html index cf254b508b..7ed1035ffe 100644 --- a/docs/classes/address.html +++ b/docs/classes/address.html @@ -110,7 +110,7 @@

constructor

  • Parameters

    @@ -135,7 +135,7 @@

    ip

    ip: string
    @@ -145,7 +145,7 @@

    port

    port: string
    @@ -162,7 +162,7 @@

    toString

  • @@ -184,7 +184,7 @@

    Static fromAddressInfo
  • @@ -215,7 +215,7 @@

    Static parse

  • diff --git a/docs/classes/keymanager.html b/docs/classes/keymanager.html index cc51432456..037a86c229 100644 --- a/docs/classes/keymanager.html +++ b/docs/classes/keymanager.html @@ -147,7 +147,7 @@

    constructor

  • Parameters

    @@ -178,7 +178,7 @@

    polykeyPath

    polykeyPath: string
    @@ -195,7 +195,7 @@

    PKIInfo

  • Returns PKInfo

    @@ -212,7 +212,7 @@

    identityLoaded

  • Returns boolean

    @@ -232,7 +232,7 @@

    decryptData

  • @@ -275,7 +275,7 @@

    encryptData

  • @@ -312,7 +312,7 @@

    exportKey

  • @@ -355,7 +355,7 @@

    exportKeySync

  • @@ -398,7 +398,7 @@

    exportPrivateKey

  • @@ -429,7 +429,7 @@

    exportPublicKey

  • @@ -460,7 +460,7 @@

    generateKey

  • @@ -497,7 +497,7 @@

    generateKeyPair

  • @@ -558,7 +558,7 @@

    generateKeySync

  • @@ -595,7 +595,7 @@

    getIdentityFromPrivateKey

  • @@ -626,7 +626,7 @@

    getIdentityFromPublicKey

  • @@ -657,7 +657,7 @@

    getKey

  • @@ -688,7 +688,7 @@

    getKeyPair

  • @@ -710,7 +710,7 @@

    getPrivateKey

  • @@ -732,7 +732,7 @@

    getPublicKey

  • @@ -754,7 +754,7 @@

    hasKey

  • @@ -785,7 +785,7 @@

    hasPublicKey

  • @@ -807,7 +807,7 @@

    importKey

  • @@ -844,7 +844,7 @@

    importKeySync

  • @@ -881,7 +881,7 @@

    loadKeyPair

  • @@ -918,7 +918,7 @@

    loadPKIInfo

  • Parameters

    @@ -950,7 +950,7 @@

    loadPrivateKey

  • @@ -981,7 +981,7 @@

    loadPublicKey

  • @@ -1012,7 +1012,7 @@

    signData

  • @@ -1055,7 +1055,7 @@

    signFile

  • @@ -1098,7 +1098,7 @@

    unlockIdentity

  • @@ -1129,7 +1129,7 @@

    verifyData

  • @@ -1172,7 +1172,7 @@

    verifyFile

  • @@ -1214,7 +1214,7 @@

    pkiInfo

    pkiInfo: object
    @@ -1223,7 +1223,7 @@

    caCert

    caCert: null = null
    @@ -1233,7 +1233,7 @@

    cert

    cert: null = null
    @@ -1243,7 +1243,7 @@

    key

    key: null = null
    diff --git a/docs/classes/multicastbroadcaster.html b/docs/classes/multicastbroadcaster.html index 2e7dc60547..a19628e59a 100644 --- a/docs/classes/multicastbroadcaster.html +++ b/docs/classes/multicastbroadcaster.html @@ -136,7 +136,7 @@

    constructor

    Parameters

    @@ -182,7 +182,7 @@

    addPeer

    addPeer: (peerInfo: PeerInfo) => void
    @@ -213,7 +213,7 @@

    interval

    interval: number
    @@ -223,7 +223,7 @@

    keyManager

    keyManager: KeyManager
    @@ -233,7 +233,7 @@

    localPeerInfo

    localPeerInfo: PeerInfo
    @@ -243,7 +243,7 @@

    peerPubKeyMessages

    peerPubKeyMessages: Map<string, PeerMessage> = new Map()
    @@ -253,7 +253,7 @@

    queryInterval

    queryInterval: Timeout | null
    @@ -263,7 +263,7 @@

    socket

    socket: Socket
    @@ -765,7 +765,7 @@

    requestPeerContact

  • diff --git a/docs/classes/peerinfo.html b/docs/classes/peerinfo.html index e50c37ba4e..74eb837a67 100644 --- a/docs/classes/peerinfo.html +++ b/docs/classes/peerinfo.html @@ -116,7 +116,7 @@

    constructor

  • Parameters

    @@ -144,7 +144,7 @@

    addresses

    addresses: Set<Address>
    @@ -154,7 +154,7 @@

    Optional connectedAddrconnectedAddr: Address

  • @@ -164,7 +164,7 @@

    publicKey

    publicKey: string
    @@ -181,7 +181,7 @@

    AdressStringList

  • Returns string[]

    @@ -201,7 +201,7 @@

    connect

  • @@ -232,7 +232,7 @@

    disconnect

  • diff --git a/docs/classes/peermanager.html b/docs/classes/peermanager.html index 09d9e6eca3..744a17b523 100644 --- a/docs/classes/peermanager.html +++ b/docs/classes/peermanager.html @@ -116,7 +116,7 @@

    constructor

  • Parameters

    @@ -153,7 +153,7 @@

    multicastBroadcaster

    multicastBroadcaster: MulticastBroadcaster
    @@ -163,7 +163,7 @@

    server

    server: Server
    @@ -173,7 +173,7 @@

    serverStarted

    serverStarted: boolean = false
    @@ -190,7 +190,7 @@

    addPeer

  • @@ -221,7 +221,7 @@

    connectLocalPeerInfo

  • @@ -249,7 +249,7 @@

    connectToPeer

  • @@ -280,7 +280,7 @@

    findPubKey

  • @@ -311,7 +311,7 @@

    findSocialUser

  • @@ -348,7 +348,7 @@

    getLocalPeerInfo

  • @@ -370,7 +370,7 @@

    getPeer

  • @@ -401,7 +401,7 @@

    hasPeer

  • diff --git a/docs/classes/polykey.html b/docs/classes/polykey.html index e1641e8fce..dcf34440b8 100644 --- a/docs/classes/polykey.html +++ b/docs/classes/polykey.html @@ -104,7 +104,7 @@

    constructor

  • Parameters

    @@ -138,7 +138,7 @@

    keyManager

    keyManager: KeyManager
    @@ -148,7 +148,7 @@

    peerManager

    peerManager: PeerManager
    @@ -158,7 +158,7 @@

    polykeyPath

    polykeyPath: string
    @@ -168,7 +168,7 @@

    vaultManager

    vaultManager: VaultManager
    diff --git a/docs/classes/polykeyagent.html b/docs/classes/polykeyagent.html index 3cabc67ec2..287f27c7fc 100644 --- a/docs/classes/polykeyagent.html +++ b/docs/classes/polykeyagent.html @@ -118,7 +118,7 @@

    constructor

  • Returns PolykeyAgent

    @@ -134,7 +134,7 @@

    Static DAEMON_SCRIPT_P
    DAEMON_SCRIPT_PATH: string = path.join(__dirname, 'internal', 'daemon-script.js')
    @@ -151,7 +151,7 @@

    AllNodePaths

  • Returns string[]

    @@ -168,7 +168,7 @@

    UnlockedNodePaths

  • Returns string[]

    @@ -185,7 +185,7 @@

    Static LogPath

  • Returns string

    @@ -202,7 +202,7 @@

    Static SocketPath

  • Returns string

    @@ -222,7 +222,7 @@

    stop

  • Returns void

    @@ -233,19 +233,19 @@

    Returns void

    Static connectToAgent

      -
    • connectToAgent(getStream?: undefined | (() => PassThrough)): PolykeyClient
    • +
    • connectToAgent(getStream?: undefined | (() => Duplex)): PolykeyClient
    • Parameters

      • -
        Optional getStream: undefined | (() => PassThrough)
        +
        Optional getStream: undefined | (() => Duplex)

      Returns PolykeyClient

      @@ -262,7 +262,7 @@

      Static startAgent

    • Parameters

      diff --git a/docs/classes/polykeyclient.html b/docs/classes/polykeyclient.html index b57eca0f7e..42fa6adf73 100644 --- a/docs/classes/polykeyclient.html +++ b/docs/classes/polykeyclient.html @@ -110,27 +110,27 @@

      Constructors

      constructor

      • Parameters

        • -
          getStream: () => PassThrough
          +
          getStream: () => Duplex
            • -
            • (): PassThrough
            • +
            • (): Duplex
            • -

              Returns PassThrough

              +

              Returns Duplex

          • @@ -148,13 +148,13 @@

            Methods

            createSecret

              -
            • createSecret(nodePath: string, vaultName: string, secretName: string, secretPath: string): Promise<boolean>
            • +
            • createSecret(nodePath: string, vaultName: string, secretName: string, secret: string | Buffer): Promise<boolean>

            Returns Promise<boolean>

            @@ -186,7 +186,7 @@

            deriveKey

          • Parameters

            @@ -215,7 +215,7 @@

            destroySecret

          • Parameters

            @@ -244,7 +244,7 @@

            destroyVault

          • Parameters

            @@ -270,7 +270,7 @@

            getAgentStatus

          • Returns Promise<string>

            @@ -287,7 +287,7 @@

            getSecret

          • Parameters

            @@ -316,7 +316,7 @@

            listNodes

          • Parameters

            @@ -339,7 +339,7 @@

            listSecrets

          • Parameters

            @@ -365,7 +365,7 @@

            listVaults

          • Parameters

            @@ -388,7 +388,7 @@

            newNode

          • Parameters

            @@ -423,7 +423,7 @@

            newVault

          • Parameters

            @@ -449,7 +449,7 @@

            registerNode

          • Parameters

            @@ -475,7 +475,7 @@

            sendRequestToAgent

          • Parameters

            @@ -498,7 +498,7 @@

            signFile

          • Parameters

            @@ -530,7 +530,7 @@

            stopAgent

          • Returns Promise<boolean>

            @@ -547,7 +547,7 @@

            verifyFile

          • Parameters

            diff --git a/docs/classes/publickeyinfrastructure.html b/docs/classes/publickeyinfrastructure.html index 51fdc3c1a6..1a896eaca0 100644 --- a/docs/classes/publickeyinfrastructure.html +++ b/docs/classes/publickeyinfrastructure.html @@ -106,7 +106,7 @@

            Static COMMON_NAME

            COMMON_NAME: string = "localhost"
            @@ -116,7 +116,7 @@

            Static N_BITS

            N_BITS: number = 2048
            @@ -126,7 +126,7 @@

            Static ORGANIZATION_NAMEORGANIZATION_NAME: string = "MatrixAI" @@ -143,7 +143,7 @@

            Static createX509Certi
          • diff --git a/docs/classes/vault.html b/docs/classes/vault.html index 99f5917101..0c604e7102 100644 --- a/docs/classes/vault.html +++ b/docs/classes/vault.html @@ -98,7 +98,7 @@

            Methods

            • addSecret
            • getSecret
            • -
            • initRepository
            • +
            • getVaultHistory
            • listSecrets
            • peerCanAccess
            • pullVault
            • @@ -126,7 +126,7 @@

              constructor

            • Parameters

              @@ -154,7 +154,7 @@

              name

              name: string
              @@ -164,7 +164,7 @@

              vaultPath

              vaultPath: string
              @@ -181,7 +181,7 @@

              EncryptedFS

            • @@ -206,7 +206,7 @@

              addSecret

            • @@ -243,7 +243,7 @@

              getSecret

            • @@ -265,24 +265,25 @@

              Returns Buffer
              - -

              initRepository

              + +

              getVaultHistory

                -
              • initRepository(): Promise<void>
              • +
              • getVaultHistory(depth?: undefined | number): Promise<string[]>
              @@ -296,7 +297,7 @@

              listSecrets

            • @@ -318,7 +319,7 @@

              peerCanAccess

            • @@ -349,7 +350,7 @@

              pullVault

            • @@ -377,7 +378,7 @@

              removeSecret

            • @@ -408,7 +409,7 @@

              secretExists

            • @@ -439,7 +440,7 @@

              shareVault

            • @@ -470,7 +471,7 @@

              tagVault

            • Returns void

              @@ -487,7 +488,7 @@

              unshareVault

            • @@ -518,7 +519,7 @@

              untagVault

            • Returns void

              @@ -535,7 +536,7 @@

              updateSecret

            • @@ -598,7 +599,7 @@

              Returns PromisegetSecret

            • - initRepository + getVaultHistory
            • listSecrets diff --git a/docs/classes/vaultmanager.html b/docs/classes/vaultmanager.html index b8ec82899b..abaf2a32d1 100644 --- a/docs/classes/vaultmanager.html +++ b/docs/classes/vaultmanager.html @@ -117,7 +117,7 @@

              constructor

            • Parameters

              @@ -145,7 +145,7 @@

              fileSystem

              fileSystem: typeof fs
              @@ -155,7 +155,7 @@

              keyManager

              keyManager: KeyManager
              @@ -165,7 +165,7 @@

              metadataPath

              metadataPath: string
              @@ -175,7 +175,7 @@

              polykeyPath

              polykeyPath: string
              @@ -185,7 +185,7 @@

              vaultKeys

              vaultKeys: Map<string, Buffer>
              @@ -195,7 +195,7 @@

              vaults

              vaults: Map<string, Vault>
              @@ -212,7 +212,7 @@

              cloneVault

            • @@ -246,7 +246,7 @@

              createVault

            • @@ -283,7 +283,7 @@

              destroyVault

            • @@ -314,7 +314,7 @@

              getVault

            • @@ -345,7 +345,7 @@

              listVaults

            • @@ -367,7 +367,7 @@

              vaultExists

            • diff --git a/docs/globals.html b/docs/globals.html index 249f918479..bd92c325e2 100644 --- a/docs/globals.html +++ b/docs/globals.html @@ -166,7 +166,7 @@

              KeyManagerMetadata

              KeyManagerMetadata: { caCertPath: string | null; pkiCertPath: string | null; pkiKeyPath: string | null; privateKeyPath: string | null; publicKeyPath: string | null }
              @@ -196,7 +196,7 @@

              KeyManagerWorker

              KeyManagerWorker: typeof keyManagerWorker
              @@ -206,7 +206,7 @@

              KeyPair

              KeyPair: { private: string | null; public: string | null }
              @@ -227,7 +227,7 @@

              PKInfo

              PKInfo: { caCert: Buffer | null; cert: Buffer | null; key: Buffer | null }
              @@ -251,7 +251,7 @@

              PeerManagerMetadata

              PeerManagerMetadata: { localPeerInfo: PeerInfo | null }
              @@ -269,7 +269,7 @@

              PeerMessage

              PeerMessage: { encryptedLocalPubKey: Buffer; encryptedPeerPubKey: Buffer; encryptedRandomMessage: Buffer; rawRandomMessage: Buffer }
              @@ -296,7 +296,7 @@

              VaultMetadata

              VaultMetadata: { sharedPubKeys: string[] }
              @@ -317,9 +317,9 @@

              $Reader

              $Reader: Reader = $protobuf.Reader
              @@ -329,9 +329,9 @@

              $Writer

              $Writer: Writer = $protobuf.Writer
              @@ -341,9 +341,9 @@

              $protobuf

              $protobuf: "/home/robbie/Documents/github/js-polykey/node_modules/protobufjs/minimal" = require("protobufjs/minimal")
              @@ -353,9 +353,9 @@

              $root

              $root: Root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {})
              @@ -365,9 +365,9 @@

              $util

              $util: util = $protobuf.util
              @@ -377,8 +377,8 @@

              AgentMessage

              AgentMessage: AgentMessage
              @@ -388,8 +388,8 @@

              CreateSecretRequestMessage

              CreateSecretRequestMessage: CreateSecretRequestMessage
              @@ -399,8 +399,8 @@

              CreateSecretResponseMessage

              CreateSecretResponseMessage: CreateSecretResponseMessage
              @@ -410,8 +410,8 @@

              DeriveKeyRequestMessage

              DeriveKeyRequestMessage: DeriveKeyRequestMessage
              @@ -421,8 +421,8 @@

              DeriveKeyResponseMessage

              DeriveKeyResponseMessage: DeriveKeyResponseMessage
              @@ -432,8 +432,8 @@

              DestroySecretRequestMessage

              DestroySecretRequestMessage: DestroySecretRequestMessage
              @@ -443,8 +443,8 @@

              DestroySecretResponseMessage

              DestroySecretResponseMessage: DestroySecretResponseMessage
              @@ -454,8 +454,8 @@

              DestroyVaultRequestMessage

              DestroyVaultRequestMessage: DestroyVaultRequestMessage
              @@ -465,8 +465,8 @@

              DestroyVaultResponseMessage

              DestroyVaultResponseMessage: DestroyVaultResponseMessage
              @@ -476,8 +476,8 @@

              ErrorMessage

              ErrorMessage: ErrorMessage
              @@ -487,8 +487,8 @@

              GetSecretRequestMessage

              GetSecretRequestMessage: GetSecretRequestMessage
              @@ -498,8 +498,8 @@

              GetSecretResponseMessage

              GetSecretResponseMessage: GetSecretResponseMessage
              @@ -509,7 +509,7 @@

              HandshakeMessage

              HandshakeMessage: HandshakeMessage
              @@ -519,8 +519,8 @@

              ListNodesRequestMessage

              ListNodesRequestMessage: ListNodesRequestMessage
              @@ -530,8 +530,8 @@

              ListNodesResponseMessage

              ListNodesResponseMessage: ListNodesResponseMessage
              @@ -541,8 +541,8 @@

              ListSecretsRequestMessage

              ListSecretsRequestMessage: ListSecretsRequestMessage
              @@ -552,8 +552,8 @@

              ListSecretsResponseMessage

              ListSecretsResponseMessage: ListSecretsResponseMessage
              @@ -563,8 +563,8 @@

              ListVaultsRequestMessage

              ListVaultsRequestMessage: ListVaultsRequestMessage
              @@ -574,8 +574,8 @@

              ListVaultsResponseMessage

              ListVaultsResponseMessage: ListVaultsResponseMessage
              @@ -585,8 +585,8 @@

              NewNodeRequestMessage

              NewNodeRequestMessage: NewNodeRequestMessage
              @@ -596,8 +596,8 @@

              NewNodeResponseMessage

              NewNodeResponseMessage: NewNodeResponseMessage
              @@ -607,8 +607,8 @@

              NewVaultRequestMessage

              NewVaultRequestMessage: NewVaultRequestMessage
              @@ -618,8 +618,8 @@

              NewVaultResponseMessage

              NewVaultResponseMessage: NewVaultResponseMessage
              @@ -629,7 +629,7 @@

              PeerInfoMessage

              PeerInfoMessage: PeerInfoMessage
              @@ -639,8 +639,8 @@

              RegisterNodeRequestMessage

              RegisterNodeRequestMessage: RegisterNodeRequestMessage
              @@ -650,8 +650,8 @@

              RegisterNodeResponseMessage

              RegisterNodeResponseMessage: RegisterNodeResponseMessage
              @@ -661,8 +661,8 @@

              SignFileRequestMessage

              SignFileRequestMessage: SignFileRequestMessage
              @@ -672,8 +672,8 @@

              SignFileResponseMessage

              SignFileResponseMessage: SignFileResponseMessage
              @@ -683,18 +683,18 @@

              Type

              Type: Type

              Const UDP_MULTICAST_ADDR

              -
              UDP_MULTICAST_ADDR: string = process.env.UDP_MULTICAST_ADDR ?? "224.0.0.251"
              +
              UDP_MULTICAST_ADDR: string = process.env.UDP_MULTICAST_ADDR ?? '224.0.0.251'
              @@ -704,7 +704,7 @@

              Const UDP_MULTICAST_POR
              UDP_MULTICAST_PORT: number = parseInt(process.env.UDP_MULTICAST_PORT ?? '5353')
              @@ -714,8 +714,8 @@

              VerifyFileRequestMessage

              VerifyFileRequestMessage: VerifyFileRequestMessage
              @@ -725,8 +725,8 @@

              VerifyFileResponseMessage

              VerifyFileResponseMessage: VerifyFileResponseMessage
              @@ -743,7 +743,7 @@

              firstPromiseFulfilled

            • @@ -780,7 +780,7 @@

              invertPromise

            • @@ -817,7 +817,7 @@

              randomString

            • @@ -838,7 +838,7 @@

              Const keyManagerWorker<
              keyManagerWorker: object
              @@ -851,7 +851,7 @@

              decryptData

            • @@ -888,7 +888,7 @@

              encryptData

            • @@ -925,7 +925,7 @@

              signData

            • @@ -962,7 +962,7 @@

              verifyData

            • @@ -1002,7 +1002,7 @@

              Const keybaseDiscovery

              keybaseDiscovery: object
              @@ -1011,7 +1011,7 @@

              name

              name: string = "Keybase"
              @@ -1025,7 +1025,7 @@

              findUser

            • Parameters

              diff --git a/docs/interfaces/socialdiscovery.html b/docs/interfaces/socialdiscovery.html index e9f5d2575c..9b9439f602 100644 --- a/docs/interfaces/socialdiscovery.html +++ b/docs/interfaces/socialdiscovery.html @@ -97,7 +97,7 @@

              name

              name: string
            • @@ -114,7 +114,7 @@

              findUser

            • Parameters

              diff --git a/nix/node-packages.nix b/nix/node-packages.nix index 197dd1c4e4..fda240d683 100644 --- a/nix/node-packages.nix +++ b/nix/node-packages.nix @@ -346,6 +346,15 @@ let sha512 = "UBQJC2pbeyGutIfYmErGc9RaJYnpZ1FHaxuKwb0ahvGiiCkPUf3p67Io+YLPmmv3RHY+mF6JEtNW8FlHsraAaA=="; }; }; + "async-mutex-0.2.4" = { + name = "async-mutex"; + packageName = "async-mutex"; + version = "0.2.4"; + src = fetchurl { + url = "https://registry.npmjs.org/async-mutex/-/async-mutex-0.2.4.tgz"; + sha512 = "fcQKOXUKMQc57JlmjBCHtkKNrfGpHyR7vu18RfuLfeTAf4hK9PgOadPR5cDrBQ682zasrLUhJFe7EKAHJOduDg=="; + }; + }; "auto-bind-proxy-1.0.1" = { name = "auto-bind-proxy"; packageName = "auto-bind-proxy"; @@ -706,13 +715,13 @@ let sha512 = "MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="; }; }; - "encryptedfs-1.0.0" = { + "encryptedfs-1.0.2" = { name = "encryptedfs"; packageName = "encryptedfs"; - version = "1.0.0"; + version = "1.0.2"; src = fetchurl { - url = "https://registry.npmjs.org/encryptedfs/-/encryptedfs-1.0.0.tgz"; - sha512 = "O1q3yNNDSHfb8yN4FJ1lcVPhjYbNUJnhZqZgy21tOUdGxkYF4hD8YHXryg8eqdLeTs4aFNAQzoet3qGfMx7WiQ=="; + url = "https://registry.npmjs.org/encryptedfs/-/encryptedfs-1.0.2.tgz"; + sha512 = "o6YpNMDD1MmCYDWXIKLJ62fo/dHcTMLKyTMQEaR0vaDBIek91UAj61aRm0FdErXcJZGDIXSAqzwPuwz+kmQITg=="; }; }; "enquirer-2.3.5" = { @@ -1318,6 +1327,15 @@ let sha512 = "8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A=="; }; }; + "lodash-4.17.19" = { + name = "lodash"; + packageName = "lodash"; + version = "4.17.19"; + src = fetchurl { + url = "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz"; + sha512 = "JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ=="; + }; + }; "long-4.0.0" = { name = "long"; packageName = "long"; @@ -2011,6 +2029,15 @@ let sha512 = "aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA=="; }; }; + "tslib-2.0.0" = { + name = "tslib"; + packageName = "tslib"; + version = "2.0.0"; + src = fetchurl { + url = "https://registry.npmjs.org/tslib/-/tslib-2.0.0.tgz"; + sha512 = "lTqkx847PI7xEDYJntxZH89L2/aXInsyF2luSafe/+0fHOMjlBNXdH6th7f70qxLDhul7KZK0zC8V5ZIyHl0/g=="; + }; + }; "tsutils-3.17.1" = { name = "tsutils"; packageName = "tsutils"; @@ -2244,7 +2271,7 @@ let dependencies = [ sources."debug-4.1.1" sources."glob-7.1.6" - sources."lodash-4.17.15" + sources."lodash-4.17.19" sources."ms-2.1.2" sources."semver-7.3.2" ]; @@ -2255,6 +2282,11 @@ let sources."argparse-1.0.10" sources."astral-regex-1.0.0" sources."async-lock-1.2.4" + (sources."async-mutex-0.2.4" // { + dependencies = [ + sources."tslib-2.0.0" + ]; + }) sources."auto-bind-proxy-1.0.1" (sources."babel-runtime-6.26.0" // { dependencies = [ @@ -2300,7 +2332,7 @@ let sources."doctrine-3.0.0" sources."dom-walk-0.1.1" sources."dot-prop-5.2.0" - (sources."encryptedfs-1.0.0" // { + (sources."encryptedfs-1.0.2" // { dependencies = [ sources."debug-4.1.1" sources."ms-2.1.2" diff --git a/package-lock.json b/package-lock.json index 8ea29613d0..9539541712 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1764,9 +1764,9 @@ } }, "lodash": { - "version": "4.17.15", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", - "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" + "version": "4.17.19", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz", + "integrity": "sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ==" }, "ms": { "version": "2.1.2", @@ -2576,6 +2576,21 @@ "resolved": "https://registry.npmjs.org/async-lock/-/async-lock-1.2.4.tgz", "integrity": "sha512-UBQJC2pbeyGutIfYmErGc9RaJYnpZ1FHaxuKwb0ahvGiiCkPUf3p67Io+YLPmmv3RHY+mF6JEtNW8FlHsraAaA==" }, + "async-mutex": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.2.4.tgz", + "integrity": "sha512-fcQKOXUKMQc57JlmjBCHtkKNrfGpHyR7vu18RfuLfeTAf4hK9PgOadPR5cDrBQ682zasrLUhJFe7EKAHJOduDg==", + "requires": { + "tslib": "^2.0.0" + }, + "dependencies": { + "tslib": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.0.0.tgz", + "integrity": "sha512-lTqkx847PI7xEDYJntxZH89L2/aXInsyF2luSafe/+0fHOMjlBNXdH6th7f70qxLDhul7KZK0zC8V5ZIyHl0/g==" + } + } + }, "asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -6314,9 +6329,9 @@ } }, "encryptedfs": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/encryptedfs/-/encryptedfs-1.0.0.tgz", - "integrity": "sha512-O1q3yNNDSHfb8yN4FJ1lcVPhjYbNUJnhZqZgy21tOUdGxkYF4hD8YHXryg8eqdLeTs4aFNAQzoet3qGfMx7WiQ==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encryptedfs/-/encryptedfs-1.0.2.tgz", + "integrity": "sha512-o6YpNMDD1MmCYDWXIKLJ62fo/dHcTMLKyTMQEaR0vaDBIek91UAj61aRm0FdErXcJZGDIXSAqzwPuwz+kmQITg==", "requires": { "@types/readable-stream": "2.3.5", "@typescript-eslint/eslint-plugin": "^2.34.0", diff --git a/package.json b/package.json index 9d851ad784..bf02b8b2b3 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,8 @@ "build:documentation": "typedoc", "build:all": "npm run build:proto && npm run build:webpack && npm run build:documentation", "generate:sslcerts": "./scripts/generate_ssl_certs.sh", - "test": "jest" + "test": "jest", + "lint": "eslint '{src,tests}/**/*.{js,ts}' --quiet --fix" }, "jest": { "verbose": true, @@ -48,11 +49,12 @@ "@types/commander": "^2.12.2", "@types/configstore": "^4.0.0", "@types/inquirer": "^6.5.0", + "async-mutex": "^0.2.4", "chalk": "^4.0.0", "cli-progress": "^3.8.2", "commander": "^5.1.0", "configstore": "^5.0.1", - "encryptedfs": "^1.0.0", + "encryptedfs": "^1.0.2", "futoin-hkdf": "^1.3.2", "isomorphic-git": "^1.5.0", "kbpgp": "^2.0.82", diff --git a/proto/Agent.proto b/proto/Agent.proto index f03d61fe47..6b93990de3 100644 --- a/proto/Agent.proto +++ b/proto/Agent.proto @@ -112,6 +112,7 @@ message CreateSecretRequestMessage { string vault_name = 1; string secret_name = 2; string secret_path = 3; + bytes secret_content = 4; } message CreateSecretResponseMessage { bool successful = 1; diff --git a/proto/js/Agent.d.ts b/proto/js/Agent.d.ts index 534133c34d..21c3d7f350 100644 --- a/proto/js/Agent.d.ts +++ b/proto/js/Agent.d.ts @@ -981,6 +981,9 @@ export namespace agent { /** CreateSecretRequestMessage secretPath */ secretPath?: (string|null); + + /** CreateSecretRequestMessage secretContent */ + secretContent?: (Uint8Array|null); } /** Represents a CreateSecretRequestMessage. */ @@ -1001,6 +1004,9 @@ export namespace agent { /** CreateSecretRequestMessage secretPath. */ public secretPath: string; + /** CreateSecretRequestMessage secretContent. */ + public secretContent: Uint8Array; + /** * Creates a new CreateSecretRequestMessage instance using the specified properties. * @param [properties] Properties to set diff --git a/proto/js/Agent.js b/proto/js/Agent.js index 04c6bd7da1..b87f87c1d2 100644 --- a/proto/js/Agent.js +++ b/proto/js/Agent.js @@ -2056,6 +2056,7 @@ $root.agent = (function() { * @property {string|null} [vaultName] CreateSecretRequestMessage vaultName * @property {string|null} [secretName] CreateSecretRequestMessage secretName * @property {string|null} [secretPath] CreateSecretRequestMessage secretPath + * @property {Uint8Array|null} [secretContent] CreateSecretRequestMessage secretContent */ /** @@ -2097,6 +2098,14 @@ $root.agent = (function() { */ CreateSecretRequestMessage.prototype.secretPath = ""; + /** + * CreateSecretRequestMessage secretContent. + * @member {Uint8Array} secretContent + * @memberof agent.CreateSecretRequestMessage + * @instance + */ + CreateSecretRequestMessage.prototype.secretContent = $util.newBuffer([]); + /** * Creates a new CreateSecretRequestMessage instance using the specified properties. * @function create @@ -2127,6 +2136,8 @@ $root.agent = (function() { w.uint32(18).string(m.secretName); if (m.secretPath != null && Object.hasOwnProperty.call(m, "secretPath")) w.uint32(26).string(m.secretPath); + if (m.secretContent != null && Object.hasOwnProperty.call(m, "secretContent")) + w.uint32(34).bytes(m.secretContent); return w; }; @@ -2157,6 +2168,9 @@ $root.agent = (function() { case 3: m.secretPath = r.string(); break; + case 4: + m.secretContent = r.bytes(); + break; default: r.skipType(t & 7); break; diff --git a/src/cli/Agent.ts b/src/cli/Agent.ts index feda567c47..f4aa0f023a 100644 --- a/src/cli/Agent.ts +++ b/src/cli/Agent.ts @@ -1,4 +1,4 @@ -import fs from 'fs' +import fs from 'fs'; import commander from 'commander'; import { PolykeyAgent } from '../lib/Polykey'; import { actionRunner, pkLogger, PKMessageType, determineNodePath } from '.'; @@ -7,72 +7,78 @@ function makeStartAgentCommand() { return new commander.Command('start') .description('start the agent') .option('-d, --daemon', 'start the agent as a daemon process') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - // Tell agent to stop - const status = await client.getAgentStatus() - if (status == 'online') { - pkLogger('agent is already running', PKMessageType.INFO) - } else { - const daemon: boolean = options.daemon - const pid = await PolykeyAgent.startAgent(daemon) - pkLogger(`agent has started with pid of ${pid}`, PKMessageType.SUCCESS) - } - process.exit() - })) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + // Tell agent to stop + const status = await client.getAgentStatus(); + if (status == 'online') { + pkLogger('agent is already running', PKMessageType.INFO); + } else { + const daemon: boolean = options.daemon; + const pid = await PolykeyAgent.startAgent(daemon); + pkLogger(`agent has started with pid of ${pid}`, PKMessageType.SUCCESS); + } + process.exit(); + }), + ); } function makeRestartAgentCommand() { return new commander.Command('restart') .description('restart the agent') .option('-d, --daemon', 'start the agent as a daemon process') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - // Tell agent to stop - client.stopAgent() - const daemon: boolean = options.daemon - const pid = await PolykeyAgent.startAgent(daemon) - pkLogger(`agent has restarted with pid of ${pid}`, PKMessageType.SUCCESS) - process.exit() - })) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + // Tell agent to stop + client.stopAgent(); + const daemon: boolean = options.daemon; + const pid = await PolykeyAgent.startAgent(daemon); + pkLogger(`agent has restarted with pid of ${pid}`, PKMessageType.SUCCESS); + process.exit(); + }), + ); } function makeAgentStatusCommand() { - return new commander.Command('status') - .description('retrieve the status of the agent') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const status = await client.getAgentStatus() - pkLogger(`agent status is: '${status}'`, PKMessageType.INFO) - process.exit() - })) + return new commander.Command('status').description('retrieve the status of the agent').action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + pkLogger(`agent status is: '${status}'`, PKMessageType.INFO); + process.exit(); + }), + ); } function makeStopAgentCommand() { return new commander.Command('stop') .description('stop the agent') .option('-f, --force', 'forcibly stop the agent') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const status = await client.getAgentStatus() - if (status == 'stopped') { - pkLogger('agent is already stopped', PKMessageType.INFO) - } else { - const force = (options.force) ? true : false - // Tell agent to stop - client.stopAgent() - if (force) { - fs.unlinkSync(PolykeyAgent.SocketPath) - } - const status = await client.getAgentStatus() - if (status != 'online') { - pkLogger('agent has successfully stopped', PKMessageType.SUCCESS) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + if (status == 'stopped') { + pkLogger('agent is already stopped', PKMessageType.INFO); } else { - throw Error('agent failed to stop') + const force = options.force ? true : false; + // Tell agent to stop + client.stopAgent(); + if (force) { + fs.unlinkSync(PolykeyAgent.SocketPath); + } + const status = await client.getAgentStatus(); + if (status != 'online') { + pkLogger('agent has successfully stopped', PKMessageType.SUCCESS); + } else { + throw Error('agent failed to stop'); + } } - } - process.exit() - })) + process.exit(); + }), + ); } function makeListNodesCommand() { @@ -80,19 +86,21 @@ function makeListNodesCommand() { .alias('ls') .description('list all the nodes controlled by the node') .option('-u, --unlocked-only, only list the nodes that are unlocked') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const unlockedOnly = (options.unlockedOnly) ? true : false - const nodes = await client.listNodes(unlockedOnly) - if (nodes.length == 0) { - pkLogger('no nodes were listed', PKMessageType.INFO) - } else { - for (const node of nodes) { - pkLogger(node, PKMessageType.INFO) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const unlockedOnly = options.unlockedOnly ? true : false; + const nodes = await client.listNodes(unlockedOnly); + if (nodes.length == 0) { + pkLogger('no nodes were listed', PKMessageType.INFO); + } else { + for (const node of nodes) { + pkLogger(node, PKMessageType.INFO); + } } - } - process.exit() - })) + process.exit(); + }), + ); } function makeNewNodeCommand() { @@ -104,23 +112,25 @@ function makeNewNodeCommand() { .requiredOption('-p, --private-passphrase ', 'provide the passphrase to the private key') .option('-b, --number-of-bits ', 'number of bits to use for key pair generation') .option('-v, --verbose', 'increase verbosity by one level') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const nodePath = determineNodePath(options) - const fullName = options.fullName - const email = options.email - const privatePassphrase = options.privatePassphrase - const numberOfBits = parseInt(options.numberOfBits) - const successful = await client.newNode(nodePath, fullName, email, privatePassphrase, numberOfBits) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const nodePath = determineNodePath(options); + const fullName = options.fullName; + const email = options.email; + const privatePassphrase = options.privatePassphrase; + const numberOfBits = parseInt(options.numberOfBits); + const successful = await client.newNode(nodePath, fullName, email, privatePassphrase, numberOfBits); - if (successful) { - pkLogger(`node was successfully generated at: '${nodePath}'`, PKMessageType.SUCCESS) - } else { - throw Error('something went wrong with node creation') - } + if (successful) { + pkLogger(`node was successfully generated at: '${nodePath}'`, PKMessageType.SUCCESS); + } else { + throw Error('something went wrong with node creation'); + } - process.exit() - })) + process.exit(); + }), + ); } function makeLoadNodeCommand() { @@ -128,20 +138,22 @@ function makeLoadNodeCommand() { .description('load an existing polykey node') .option('-k, --node-path ', 'provide the polykey path. defaults to ~/.polykey') .requiredOption('-p, --private-passphrase ', 'provide the passphrase to the private key') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const nodePath = determineNodePath(options) - const privatePassphrase = options.privatePassphrase - const successful = await client.registerNode(nodePath, privatePassphrase) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const nodePath = determineNodePath(options); + const privatePassphrase = options.privatePassphrase; + const successful = await client.registerNode(nodePath, privatePassphrase); - if (successful) { - pkLogger(`node was successfully loaded at: '${nodePath}'`, PKMessageType.SUCCESS) - } else { - throw Error('something went wrong when loading node') - } + if (successful) { + pkLogger(`node was successfully loaded at: '${nodePath}'`, PKMessageType.SUCCESS); + } else { + throw Error('something went wrong when loading node'); + } - process.exit() - })) + process.exit(); + }), + ); } function makeAgentCommand() { @@ -153,7 +165,7 @@ function makeAgentCommand() { .addCommand(makeStopAgentCommand()) .addCommand(makeListNodesCommand()) .addCommand(makeNewNodeCommand()) - .addCommand(makeLoadNodeCommand()) + .addCommand(makeLoadNodeCommand()); } -export default makeAgentCommand +export default makeAgentCommand; diff --git a/src/cli/Crypto.ts b/src/cli/Crypto.ts index 1c9b156ba6..02e4906174 100644 --- a/src/cli/Crypto.ts +++ b/src/cli/Crypto.ts @@ -1,6 +1,6 @@ -import commander from 'commander' +import commander from 'commander'; import { PolykeyAgent } from '../lib/Polykey'; -import { actionRunner, pkLogger, PKMessageType, determineNodePath } from '.' +import { actionRunner, pkLogger, PKMessageType, determineNodePath } from '.'; function makeSignCommand() { return new commander.Command('sign') @@ -10,69 +10,73 @@ function makeSignCommand() { .option('-p, --key-passphrase ', 'passphrase to unlock the provided signing key') .arguments('file(s) to be signed') .action(async (options) => { - const client = PolykeyAgent.connectToAgent() - const status = await client.getAgentStatus() + const client = PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); if (status != 'online') { - throw Error(`agent status is: ${status}`) + throw Error(`agent status is: ${status}`); } - const nodePath = determineNodePath(options) - const signingKeyPath = options.signingKey - const keyPassphrase = options.keyPassphrase + const nodePath = determineNodePath(options); + const signingKeyPath = options.signingKey; + const keyPassphrase = options.keyPassphrase; if ((signingKeyPath || keyPassphrase) && !(signingKeyPath && keyPassphrase)) { - throw Error('signing key and passphrase must be specified together') + throw Error('signing key and passphrase must be specified together'); } - const filePathList = options.args.values() + const filePathList = options.args.values(); if (filePathList.length == 0) { - throw Error('no files provided') + throw Error('no files provided'); } for (const filePath of filePathList) { try { - const signaturePath = await client.signFile(nodePath, filePath, signingKeyPath, keyPassphrase) - pkLogger(`file '${filePath}' successfully signed at '${signaturePath}'`, PKMessageType.SUCCESS) + const signaturePath = await client.signFile(nodePath, filePath, signingKeyPath, keyPassphrase); + pkLogger(`file '${filePath}' successfully signed at '${signaturePath}'`, PKMessageType.SUCCESS); } catch (err) { - throw new Error(`failed to sign '${filePath}': ${err}`) + throw Error(`failed to sign '${filePath}': ${err}`); } } - }) + }); } function makeVerifyCommand() { return new commander.Command('verify') .description('verification operations') .option('--node-path ', 'node path') - .option('-k, --verifying-key ', 'path to public key that will be used to verify files, defaults to primary key') + .option( + '-k, --verifying-key ', + 'path to public key that will be used to verify files, defaults to primary key', + ) .option('-s, --detach-sig ', 'path to detached signature for file, defaults to [filename].sig') .requiredOption('-f, --signed-file ', 'file to be signed') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const status = await client.getAgentStatus() - if (status != 'online') { - throw Error(`agent status is: ${status}`) - } - - const nodePath = determineNodePath(options) - const verifyingKeyPath = options.verifyingKey - const filePath = options.signedFile - const signaturePath = options.detachSig ?? (filePath + '.sig') + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + if (status != 'online') { + throw Error(`agent status is: ${status}`); + } + const nodePath = determineNodePath(options); + const verifyingKeyPath = options.verifyingKey; + const filePath = options.signedFile; + const signaturePath = options.detachSig ?? filePath + '.sig'; - const verified = await client.verifyFile(nodePath, filePath, signaturePath) - if (verified) { - pkLogger(`file '${filePath}' was successfully verified`, PKMessageType.SUCCESS) - } else { - pkLogger(`file '${filePath}' was not verified`, PKMessageType.WARNING) - } - })) + const verified = await client.verifyFile(nodePath, filePath, signaturePath); + if (verified) { + pkLogger(`file '${filePath}' was successfully verified`, PKMessageType.SUCCESS); + } else { + pkLogger(`file '${filePath}' was not verified`, PKMessageType.WARNING); + } + }), + ); } function makeCryptoCommand() { return new commander.Command('crypto') .description('crypto operations') .addCommand(makeVerifyCommand()) - .addCommand(makeSignCommand()) + .addCommand(makeSignCommand()); } -export default makeCryptoCommand +export default makeCryptoCommand; diff --git a/src/cli/KeyManager.ts b/src/cli/KeyManager.ts index 642e9520d6..b9fd8b9891 100644 --- a/src/cli/KeyManager.ts +++ b/src/cli/KeyManager.ts @@ -2,29 +2,30 @@ import commander from 'commander'; import { PolykeyAgent } from '../lib/Polykey'; import { actionRunner, pkLogger, PKMessageType, determineNodePath } from '.'; - function makeDeriveKeyCommand() { return new commander.Command('derive') .description('manipulate the keymanager') .option('--node-path ', 'node path') .requiredOption('-n, --key-name ', 'the name of the new key') .requiredOption('-p, --key-passphrase ', 'the passphrase for the new key') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const nodePath = determineNodePath(options) - const keyName = options.keyName - const keyPassphrase = options.keyPassphrase + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const nodePath = determineNodePath(options); + const keyName = options.keyName; + const keyPassphrase = options.keyPassphrase; - await client.deriveKey(nodePath, keyName, keyPassphrase) - pkLogger(`'${keyName}' was added to the Key Manager`, PKMessageType.SUCCESS) - })) + await client.deriveKey(nodePath, keyName, keyPassphrase); + pkLogger(`'${keyName}' was added to the Key Manager`, PKMessageType.SUCCESS); + }), + ); } function makeKeyManagerCommand() { return new commander.Command('keymanager') .alias('km') .description('manipulate the keymanager') - .addCommand(makeDeriveKeyCommand()) + .addCommand(makeDeriveKeyCommand()); } -export default makeKeyManagerCommand +export default makeKeyManagerCommand; diff --git a/src/cli/Secrets.ts b/src/cli/Secrets.ts index fec1916eda..fd0dc93f6b 100644 --- a/src/cli/Secrets.ts +++ b/src/cli/Secrets.ts @@ -1,5 +1,5 @@ -import commander from 'commander' -import { actionRunner, pkLogger, PKMessageType, determineNodePath } from '.' +import commander from 'commander'; +import { actionRunner, pkLogger, PKMessageType, determineNodePath } from '.'; import { PolykeyAgent } from '../lib/Polykey'; function makeListSecretsCommand() { @@ -9,27 +9,29 @@ function makeListSecretsCommand() { .requiredOption('-n, --vault-name ', 'the vault name') .option('--node-path ', 'node path') .option('--verbose', 'increase verbosity level by one') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); - const nodePath = determineNodePath(options) - const isVerbose: boolean = options.verbose ?? false - const vaultName: string = options.vaultName - // Get list of secrets from pk - const secretNames = await client.listSecrets(nodePath, vaultName) + const nodePath = determineNodePath(options); + const isVerbose: boolean = options.verbose ?? false; + const vaultName: string = options.vaultName; + // Get list of secrets from pk + const secretNames = await client.listSecrets(nodePath, vaultName); - // List secrets - if (secretNames.length == 0) { - pkLogger(`no secrets found for vault '${vaultName}'`, PKMessageType.INFO) - } else { - if (isVerbose) { - pkLogger(`secrets contained within the ${vaultName} vault:`, PKMessageType.INFO) + // List secrets + if (secretNames.length == 0) { + pkLogger(`no secrets found for vault '${vaultName}'`, PKMessageType.INFO); + } else { + if (isVerbose) { + pkLogger(`secrets contained within the ${vaultName} vault:`, PKMessageType.INFO); + } + secretNames.forEach((secretName) => { + pkLogger(secretName, PKMessageType.INFO); + }); } - secretNames.forEach((secretName) => { - pkLogger(secretName, PKMessageType.INFO) - }) - } - })) + }), + ); } function makeAddSecretCommand() { @@ -40,22 +42,27 @@ function makeAddSecretCommand() { .requiredOption('-p, --secret-path ', 'path to the secret to be added') .option('--node-path ', 'node path') .option('--verbose', 'increase verbosity level by one') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const nodePath = determineNodePath(options) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const nodePath = determineNodePath(options); - const isVerbose: boolean = options.verbose ?? false - const vaultName: string = options.vaultName - const secretName: string = options.secretName - const secretPath: string = options.secretPath - try { - // Add the secret - const successful = await client.createSecret(nodePath, vaultName, secretName, secretPath) - pkLogger(`secret '${secretName}' was ${(successful) ? '' : 'un-'}sucessfully added to vault '${vaultName}'`, PKMessageType.SUCCESS) - } catch (err) { - throw new Error(`Error when adding secret: ${err.message}`) - } - })) + const isVerbose: boolean = options.verbose ?? false; + const vaultName: string = options.vaultName; + const secretName: string = options.secretName; + const secretPath: string = options.secretPath; + try { + // Add the secret + const successful = await client.createSecret(nodePath, vaultName, secretName, secretPath); + pkLogger( + `secret '${secretName}' was ${successful ? '' : 'un-'}sucessfully added to vault '${vaultName}'`, + PKMessageType.SUCCESS, + ); + } catch (err) { + throw Error(`Error when adding secret: ${err.message}`); + } + }), + ); } function makeRemoveSecretCommand() { @@ -64,21 +71,26 @@ function makeRemoveSecretCommand() { .requiredOption('-n, --vault-name ', 'the vault name') .requiredOption('-s, --secret-name ', 'the new secret name') .option('--verbose', 'increase verbosity level by one') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const nodePath = determineNodePath(options) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const nodePath = determineNodePath(options); - const isVerbose: boolean = options.verbose ?? false - const vaultName: string = options.vaultName - const secretName: string = options.secretName - try { - // Remove secret - const successful = await client.destroySecret(nodePath, vaultName, secretName) - pkLogger(`secret '${secretName}' was ${(successful) ? '' : 'un-'}sucessfully removed from vault '${vaultName}'`, PKMessageType.SUCCESS) - } catch (err) { - throw new Error(`Error when removing secret: ${err.message}`) - } - })) + const isVerbose: boolean = options.verbose ?? false; + const vaultName: string = options.vaultName; + const secretName: string = options.secretName; + try { + // Remove secret + const successful = await client.destroySecret(nodePath, vaultName, secretName); + pkLogger( + `secret '${secretName}' was ${successful ? '' : 'un-'}sucessfully removed from vault '${vaultName}'`, + PKMessageType.SUCCESS, + ); + } catch (err) { + throw Error(`Error when removing secret: ${err.message}`); + } + }), + ); } function makeGetSecretCommand() { @@ -87,22 +99,24 @@ function makeGetSecretCommand() { .requiredOption('-n, --vault-name ', 'the vault name') .requiredOption('-s, --secret-name ', 'the new secret name') .option('--verbose', 'increase verbosity level by one') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const nodePath = determineNodePath(options) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const nodePath = determineNodePath(options); - const isVerbose: boolean = options.verbose ?? false - const vaultName: string = options.vaultName - const secretName: string = options.secretName - try { - // Remove secret - const secret = await client.getSecret(nodePath, vaultName, secretName) - pkLogger(`secret '${secretName}' from vault '${vaultName}':`, PKMessageType.SUCCESS) - pkLogger(secret.toString(), PKMessageType.none) - } catch (err) { - throw new Error(`Error when retrieving secret: ${err.message}`) - } - })) + const isVerbose: boolean = options.verbose ?? false; + const vaultName: string = options.vaultName; + const secretName: string = options.secretName; + try { + // Remove secret + const secret = await client.getSecret(nodePath, vaultName, secretName); + pkLogger(`secret '${secretName}' from vault '${vaultName}':`, PKMessageType.SUCCESS); + pkLogger(secret.toString(), PKMessageType.none); + } catch (err) { + throw Error(`Error when retrieving secret: ${err.message}`); + } + }), + ); } function makeSecretsCommand() { @@ -111,7 +125,7 @@ function makeSecretsCommand() { .addCommand(makeListSecretsCommand()) .addCommand(makeAddSecretCommand()) .addCommand(makeRemoveSecretCommand()) - .addCommand(makeGetSecretCommand()) + .addCommand(makeGetSecretCommand()); } -export default makeSecretsCommand +export default makeSecretsCommand; diff --git a/src/cli/Vaults.ts b/src/cli/Vaults.ts index 2ea43cc000..3b69036fc7 100644 --- a/src/cli/Vaults.ts +++ b/src/cli/Vaults.ts @@ -1,6 +1,6 @@ -import chalk from 'chalk' -import commander from 'commander' -import { actionRunner, pkLogger, PKMessageType, determineNodePath } from '.' +import chalk from 'chalk'; +import commander from 'commander'; +import { actionRunner, pkLogger, PKMessageType, determineNodePath } from '.'; import { PolykeyAgent } from '../lib/Polykey'; function makeListVaultsCommand() { @@ -9,23 +9,25 @@ function makeListVaultsCommand() { .alias('ls') .option('--node-path ', 'node path') .option('-v, --verbose', 'increase verbosity level by one') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const status = await client.getAgentStatus() - if (status != 'online') { - throw Error(`agent status is: ${status}`) - } + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const status = await client.getAgentStatus(); + if (status != 'online') { + throw Error(`agent status is: ${status}`); + } - const nodePath = determineNodePath(options) - const vaultNames = await client.listVaults(nodePath) - if (vaultNames === undefined || vaultNames.length == 0) { - pkLogger('no vaults found', PKMessageType.INFO) - } else { - vaultNames.forEach((vaultName: string) => { - pkLogger(vaultName, PKMessageType.INFO) - }) - } - })) + const nodePath = determineNodePath(options); + const vaultNames = await client.listVaults(nodePath); + if (vaultNames === undefined || vaultNames.length == 0) { + pkLogger('no vaults found', PKMessageType.INFO); + } else { + vaultNames.forEach((vaultName: string) => { + pkLogger(vaultName, PKMessageType.INFO); + }); + } + }), + ); } function makeAddVaultCommand() { @@ -33,15 +35,17 @@ function makeAddVaultCommand() { .description('create new vault(s)') .option('--node-path ', 'node path') .arguments('vault name(s)') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const nodePath = determineNodePath(options) - const vaultNames = options.args.values() - for (const vaultName of vaultNames) { - await client.newVault(nodePath, vaultName) - pkLogger(`vault created at '${nodePath}/${vaultName}'`, PKMessageType.SUCCESS) - } - })) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const nodePath = determineNodePath(options); + const vaultNames = options.args.values(); + for (const vaultName of vaultNames) { + await client.newVault(nodePath, vaultName); + pkLogger(`vault created at '${nodePath}/${vaultName}'`, PKMessageType.SUCCESS); + } + }), + ); } function makeRemoveVaultCommand() { @@ -50,34 +54,36 @@ function makeRemoveVaultCommand() { .option('-n, --vault-name ', 'name of vault') .option('-a, --all', 'remove all vaults') .option('-v, --verbose', 'increase verbosity by one level') - .action(actionRunner(async (options) => { - const client = PolykeyAgent.connectToAgent() - const nodePath = determineNodePath(options) - const verbose: boolean = options.verbose ?? false - const deleteAll: boolean = options.all ?? false - if (deleteAll) { - const vaultNames = await client.listVaults(nodePath) - if (vaultNames === undefined || vaultNames.length == 0) { - pkLogger('no vaults found', PKMessageType.INFO) - } else { - for (const vaultName of vaultNames) { - await client.destroyVault(nodePath, vaultName) - if (verbose) { - pkLogger(`destroyed ${vaultName}`, PKMessageType.SUCCESS) + .action( + actionRunner(async (options) => { + const client = PolykeyAgent.connectToAgent(); + const nodePath = determineNodePath(options); + const verbose: boolean = options.verbose ?? false; + const deleteAll: boolean = options.all ?? false; + if (deleteAll) { + const vaultNames = await client.listVaults(nodePath); + if (vaultNames === undefined || vaultNames.length == 0) { + pkLogger('no vaults found', PKMessageType.INFO); + } else { + for (const vaultName of vaultNames) { + await client.destroyVault(nodePath, vaultName); + if (verbose) { + pkLogger(`destroyed ${vaultName}`, PKMessageType.SUCCESS); + } } + pkLogger('all vaults destroyed successfully', PKMessageType.SUCCESS); } - pkLogger('all vaults destroyed successfully', PKMessageType.SUCCESS) + return; + } + const vaultName = options.vaultName; + if (!vaultName) { + throw Error(chalk.red('error: did not receive vault name')); } - return - } - const vaultName = options.vaultName - if (!vaultName) { - throw new Error(chalk.red('error: did not receive vault name')) - } - const successful = await client.destroyVault(nodePath, vaultName) - pkLogger(`vault '${vaultName}' destroyed ${(successful) ? 'un-' : ''}successfully`, PKMessageType.SUCCESS) - })) + const successful = await client.destroyVault(nodePath, vaultName); + pkLogger(`vault '${vaultName}' destroyed ${successful ? 'un-' : ''}successfully`, PKMessageType.SUCCESS); + }), + ); } function makeVaultsCommand() { @@ -85,7 +91,7 @@ function makeVaultsCommand() { .description('manipulate vaults') .addCommand(makeListVaultsCommand()) .addCommand(makeAddVaultCommand()) - .addCommand(makeRemoveVaultCommand()) + .addCommand(makeRemoveVaultCommand()); } -export default makeVaultsCommand +export default makeVaultsCommand; diff --git a/src/cli/index.ts b/src/cli/index.ts index 08786a686a..f7f2dd39a6 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -1,4 +1,4 @@ -import os from 'os' +import os from 'os'; import chalk from 'chalk'; import { program } from 'commander'; import makeAgentCommand from './Agent'; @@ -21,7 +21,7 @@ function resolveTilde(filePath: string) { if (filePath[0] === '~' && (filePath[1] === '/' || filePath.length === 1)) { filePath = filePath.replace('~', os.homedir()); } - return filePath + return filePath; } /*******************************************/ @@ -30,47 +30,48 @@ enum PKMessageType { SUCCESS, INFO, WARNING, - none + none, } function pkLogger(message: string, type?: PKMessageType) { switch (type) { case PKMessageType.SUCCESS: - console.log(chalk.green(message)) - break + console.log(chalk.green(message)); + break; case PKMessageType.INFO: - console.log(chalk.blue(message)) - break + console.log(chalk.blue(message)); + break; case PKMessageType.WARNING: - console.log(chalk.yellow(message)) - break + console.log(chalk.yellow(message)); + break; default: - console.log(message) - break + console.log(message); + break; } } function determineNodePath(options: any) { - const nodePath = options.nodePath ?? process.env.KEYNODE_PATH + const nodePath = options.nodePath ?? process.env.KEYNODE_PATH; if (!nodePath) { - throw Error("no keynode path given, you can set it as an environment variable with \"export KEYNODE_PATH=''\"") + throw Error( + 'no keynode path given, you can set it as an environment variable with "export KEYNODE_PATH=\'\'"', + ); } - return resolveTilde(nodePath) + return resolveTilde(nodePath); } /*******************************************/ -const polykey = new program.Command() +const polykey = new program.Command(); polykey .version(require('../../package.json').version, '--version', 'output the current version') .addCommand(makeKeyManagerCommand()) .addCommand(makeSecretsCommand()) .addCommand(makeVaultsCommand()) .addCommand(makeCryptoCommand()) - .addCommand(makeAgentCommand()) + .addCommand(makeAgentCommand()); - -export { pkLogger, actionRunner, PKMessageType, determineNodePath, resolveTilde } +export { pkLogger, actionRunner, PKMessageType, determineNodePath, resolveTilde }; module.exports = function (argv: any[]) { - polykey.parse(argv) -} + polykey.parse(argv); +}; diff --git a/src/lib/Polykey.ts b/src/lib/Polykey.ts index 0001098e87..10c8ca54f9 100644 --- a/src/lib/Polykey.ts +++ b/src/lib/Polykey.ts @@ -7,36 +7,31 @@ import PolykeyAgent from './agent/PolykeyAgent'; import PolykeyClient from './agent/PolykeyClient'; class Polykey { - polykeyPath: string + polykeyPath: string; - vaultManager: VaultManager - keyManager: KeyManager - peerManager: PeerManager + vaultManager: VaultManager; + keyManager: KeyManager; + peerManager: PeerManager; constructor( polykeyPath: string = `${os.homedir()}/.polykey`, fileSystem: typeof fs, keyManager?: KeyManager, vaultManager?: VaultManager, - peerManager?: PeerManager + peerManager?: PeerManager, ) { - this.polykeyPath = polykeyPath + this.polykeyPath = polykeyPath; // Set key manager - this.keyManager = keyManager ?? new KeyManager(this.polykeyPath, fileSystem) + this.keyManager = keyManager ?? new KeyManager(this.polykeyPath, fileSystem); // Set or Initialize vaultManager - this.vaultManager = vaultManager ?? new VaultManager(this.polykeyPath, fileSystem, this.keyManager) + this.vaultManager = vaultManager ?? new VaultManager(this.polykeyPath, fileSystem, this.keyManager); // Initialize peer store and peer discovery classes - this.peerManager = peerManager ?? new PeerManager( - this.polykeyPath, - fileSystem, - this.keyManager, - this.vaultManager - ) + this.peerManager = peerManager ?? new PeerManager(this.polykeyPath, fileSystem, this.keyManager, this.vaultManager); } } -export default Polykey -export { KeyManager, VaultManager, PeerManager, PolykeyAgent, PolykeyClient } +export default Polykey; +export { KeyManager, VaultManager, PeerManager, PolykeyAgent, PolykeyClient }; diff --git a/src/lib/agent/PolykeyAgent.ts b/src/lib/agent/PolykeyAgent.ts index 438ac748d7..753c75c0a6 100644 --- a/src/lib/agent/PolykeyAgent.ts +++ b/src/lib/agent/PolykeyAgent.ts @@ -7,8 +7,8 @@ import { fork, ForkOptions } from 'child_process'; import Polykey, { KeyManager } from '../Polykey'; import Configstore from 'configstore'; import PolykeyClient from './PolykeyClient'; -import { agent } from '../../../proto/js/Agent' -import { PassThrough } from 'readable-stream'; +import { agent } from '../../../proto/js/Agent'; +import { Duplex } from 'readable-stream'; const { AgentMessage, CreateSecretRequestMessage, @@ -38,398 +38,403 @@ const { SignFileResponseMessage, Type, VerifyFileRequestMessage, - VerifyFileResponseMessage -} = agent + VerifyFileResponseMessage, +} = agent; class PolykeyAgent { - private socketPath: string - private server: net.Server - private persistentStore: Configstore = new Configstore('polykey') + private socketPath: string; + private server: net.Server; + private persistentStore: Configstore = new Configstore('polykey'); // For storing the state of each polykey node // Keys are the paths to the polykey node, e.g. '~/.polykey' - private polykeyMap: Map = new Map() - + private polykeyMap: Map = new Map(); public get AllNodePaths(): string[] { return Array.from(this.polykeyMap.keys()).filter((nodePath) => { try { - this.getPolykey(nodePath) - return true + this.getPolykey(nodePath); + return true; } catch { - return false + return false; } - }) + }); } public get UnlockedNodePaths(): string[] { return this.AllNodePaths.filter((nodePath) => { try { - return this.getPolykey(nodePath).keyManager.identityLoaded + return this.getPolykey(nodePath).keyManager.identityLoaded; } catch { - return false + return false; } - }) + }); } constructor() { - this.socketPath = PolykeyAgent.SocketPath + this.socketPath = PolykeyAgent.SocketPath; // Make sure the socket file doesn't already exist (agent is already running) if (fs.existsSync(this.socketPath)) { - fs.unlinkSync(this.socketPath) + fs.unlinkSync(this.socketPath); } // Make the socket path if it doesn't exist if (!fs.existsSync(path.dirname(this.socketPath))) { - fs.promises.mkdir(path.dirname(this.socketPath)) + fs.promises.mkdir(path.dirname(this.socketPath)); } // Load polykeys - const nodePaths: string[] | undefined = this.persistentStore.get('nodePaths') - if (nodePaths) { + const nodePaths: string[] | undefined = this.persistentStore.get('nodePaths'); + if (nodePaths?.values) { for (const path of nodePaths) { if (fs.existsSync(path)) { - this.polykeyMap.set(path, new Polykey(path, fs)) + this.polykeyMap.set(path, new Polykey(path, fs)); } else { - this.removeFromNodePaths(path) + this.removeFromNodePaths(path); } } } else { - this.persistentStore.set('nodePaths', []) + this.persistentStore.set('nodePaths', []); } // Start the server - this.server = net.createServer().listen(this.socketPath) + this.server = net.createServer().listen(this.socketPath); this.server.on('connection', (socket) => { - this.handleClientCommunication(socket) - }) + this.handleClientCommunication(socket); + }); } stop() { - this.server.close() + this.server.close(); } private addToNodePaths(nodePath: string, pk: Polykey) { - this.polykeyMap.set(nodePath, pk) - const nodePathSet = new Set(this.persistentStore.get('nodePaths')) - nodePathSet.add(nodePath) - this.persistentStore.set('nodePaths', Array.from(nodePathSet.values())) + this.polykeyMap.set(nodePath, pk); + const nodePathSet = new Set(this.persistentStore.get('nodePaths')); + nodePathSet.add(nodePath); + this.persistentStore.set('nodePaths', Array.from(nodePathSet.values())); } private removeFromNodePaths(nodePath: string) { - this.polykeyMap.delete(nodePath) - const nodePathSet = new Set(this.persistentStore.get('nodePaths')) - nodePathSet.delete(nodePath) - this.persistentStore.set('nodePaths', Array.from(nodePathSet.values())) + this.polykeyMap.delete(nodePath); + const nodePathSet = new Set(this.persistentStore.get('nodePaths')); + nodePathSet.delete(nodePath); + this.persistentStore.set('nodePaths', Array.from(nodePathSet.values())); } private handleClientCommunication(socket: net.Socket) { socket.on('data', async (encodedMessage: Uint8Array) => { try { - const { type, nodePath, subMessage } = AgentMessage.decode(encodedMessage) - let response: Uint8Array | undefined = undefined + const { type, nodePath, subMessage } = AgentMessage.decode(encodedMessage); + let response: Uint8Array | undefined = undefined; switch (type) { case Type.STATUS: - response = Buffer.from('online') + response = Buffer.from('online'); break; case Type.STOP_AGENT: - this.stop() - process.exit() + this.stop(); + process.exit(); + // eslint-disable-next-line case Type.REGISTER_NODE: - response = await this.registerNode(nodePath, subMessage) + response = await this.registerNode(nodePath, subMessage); break; case Type.NEW_NODE: - response = await this.newNode(nodePath, subMessage) + response = await this.newNode(nodePath, subMessage); break; case Type.LIST_NODES: - response = this.listNodes(subMessage) + response = this.listNodes(subMessage); break; case Type.DERIVE_KEY: - response = await this.deriveKey(nodePath, subMessage) + response = await this.deriveKey(nodePath, subMessage); break; case Type.SIGN_FILE: - response = await this.signFile(nodePath, subMessage) + response = await this.signFile(nodePath, subMessage); break; case Type.VERIFY_FILE: - response = await this.verifyFile(nodePath, subMessage) + response = await this.verifyFile(nodePath, subMessage); break; case Type.LIST_VAULTS: - response = await this.listVaults(nodePath) + response = await this.listVaults(nodePath); break; case Type.NEW_VAULT: - response = await this.newVault(nodePath, subMessage) + response = await this.newVault(nodePath, subMessage); break; case Type.DESTROY_VAULT: - response = await this.destroyVault(nodePath, subMessage) + response = await this.destroyVault(nodePath, subMessage); break; case Type.LIST_SECRETS: - response = await this.listSecrets(nodePath, subMessage) + response = await this.listSecrets(nodePath, subMessage); break; case Type.CREATE_SECRET: - response = await this.createSecret(nodePath, subMessage) + response = await this.createSecret(nodePath, subMessage); break; case Type.DESTROY_SECRET: - response = await this.destroySecret(nodePath, subMessage) + response = await this.destroySecret(nodePath, subMessage); break; case Type.GET_SECRET: - response = await this.getSecret(nodePath, subMessage) + response = await this.getSecret(nodePath, subMessage); break; default: - throw Error(`message type not supported: ${type}`) + throw Error(`message type not supported: ${type}`); } if (response) { - const encodedResponse = AgentMessage.encode({ type: type, isResponse: true, nodePath: nodePath, subMessage: response }).finish() - socket.write(encodedResponse) + const encodedResponse = AgentMessage.encode({ + type: type, + isResponse: true, + nodePath: nodePath, + subMessage: response, + }).finish(); + socket.write(encodedResponse); } else { - throw Error('something went wrong') + throw Error('something went wrong'); } } catch (err) { - const errorResponse = AgentMessage.encode({ type: Type.ERROR, isResponse: true, nodePath: undefined, subMessage: ErrorMessage.encode({ error: (err).message ?? err }).finish() }).finish() - socket.write(errorResponse) + const errorResponse = AgentMessage.encode({ + type: Type.ERROR, + isResponse: true, + nodePath: undefined, + subMessage: ErrorMessage.encode({ error: (err).message ?? err }).finish(), + }).finish(); + socket.write(errorResponse); } // Close connection - socket.end() - }) + socket.end(); + }); } // Register an existing polykey agent private async registerNode(nodePath: string, request: Uint8Array) { - const { passphrase } = RegisterNodeRequestMessage.decode(request) + const { passphrase } = RegisterNodeRequestMessage.decode(request); - let pk: Polykey | undefined = this.polykeyMap.get(nodePath) + let pk: Polykey | undefined = this.polykeyMap.get(nodePath); if (pk) { if (pk.keyManager.identityLoaded) { - throw Error(`node path is already loaded and unlocked: '${nodePath}'`) + throw Error(`node path is already loaded and unlocked: '${nodePath}'`); } - await pk.keyManager.unlockIdentity(passphrase) + await pk.keyManager.unlockIdentity(passphrase); } else { - const km = new KeyManager(nodePath, fs) - await km.unlockIdentity(passphrase) + const km = new KeyManager(nodePath, fs); + await km.unlockIdentity(passphrase); // Create polykey class - pk = new Polykey(nodePath, fs, km) + pk = new Polykey(nodePath, fs, km); } // Set polykey class - this.addToNodePaths(nodePath, pk) + this.addToNodePaths(nodePath, pk); // Encode and send response - const response = NewNodeResponseMessage.encode({ successful: pk.keyManager.identityLoaded && this.polykeyMap.has(nodePath) }).finish() + const response = NewNodeResponseMessage.encode({ + successful: pk.keyManager.identityLoaded && this.polykeyMap.has(nodePath), + }).finish(); - return response + return response; } // Create a new polykey agent private async newNode(nodePath: string, request: Uint8Array) { // Throw if path already exists if (this.polykeyMap.has(nodePath) && fs.existsSync(nodePath)) { - throw Error(`node path '${nodePath}' is already loaded`) + throw Error(`node path '${nodePath}' is already loaded`); } else if (fs.existsSync(nodePath)) { - throw Error(`node path already exists: '${nodePath}'`) + throw Error(`node path already exists: '${nodePath}'`); } - const { name, email, passphrase, nbits } = NewNodeRequestMessage.decode(request) + const { name, email, passphrase, nbits } = NewNodeRequestMessage.decode(request); - const km = new KeyManager(nodePath, fs) + const km = new KeyManager(nodePath, fs); - await km.generateKeyPair(name, email, passphrase, (nbits == 0) ? undefined : nbits, true, (info) => { + await km.generateKeyPair(name, email, passphrase, nbits == 0 ? undefined : nbits, true, (info) => { // socket.write(JSON.stringify(info)) - }) + }); // Create and set polykey class - const pk = new Polykey(nodePath, fs, km) - this.addToNodePaths(nodePath, pk) + const pk = new Polykey(nodePath, fs, km); + this.addToNodePaths(nodePath, pk); // Encode and send response - const response = NewNodeResponseMessage.encode({ successful: km.identityLoaded && this.polykeyMap.has(nodePath) }).finish() - return response + const response = NewNodeResponseMessage.encode({ + successful: km.identityLoaded && this.polykeyMap.has(nodePath), + }).finish(); + return response; } // Create a new polykey agent private listNodes(request: Uint8Array) { - const { unlockedOnly } = ListNodesRequestMessage.decode(request) + const { unlockedOnly } = ListNodesRequestMessage.decode(request); if (unlockedOnly) { - return ListNodesResponseMessage.encode({ nodes: this.UnlockedNodePaths }).finish() + return ListNodesResponseMessage.encode({ nodes: this.UnlockedNodePaths }).finish(); } else { - return ListNodesResponseMessage.encode({ nodes: this.AllNodePaths }).finish() + return ListNodesResponseMessage.encode({ nodes: this.AllNodePaths }).finish(); } } private getPolykey(nodePath: string) { if (this.polykeyMap.has(nodePath)) { - return this.polykeyMap.get(nodePath)! + return this.polykeyMap.get(nodePath)!; } else if (fs.existsSync(nodePath)) { - throw Error(`polykey node has not been loaded yet: '${nodePath}'`) + throw Error(`polykey node has not been loaded yet: '${nodePath}'`); } else { - const nodePathList = new Set(this.persistentStore.get('nodePaths') ?? []) - nodePathList.delete(nodePath) - this.persistentStore.set('nodePaths', nodePathList) - throw Error(`node path does not exist: '${nodePath}'`) + const nodePathList = new Set(this.persistentStore.get('nodePaths') ?? []); + nodePathList.delete(nodePath); + this.persistentStore.set('nodePaths', Array.from(nodePathList.values())); + throw Error(`node path does not exist: '${nodePath}'`); } } ///////////////////////// // KeyManager commands // ///////////////////////// private async deriveKey(nodePath: string, request: Uint8Array) { - const { keyName, passphrase } = DeriveKeyRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - await pk.keyManager.generateKey(keyName, passphrase) - return DeriveKeyResponseMessage.encode({ successful: true }).finish() + const { keyName, passphrase } = DeriveKeyRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + await pk.keyManager.generateKey(keyName, passphrase); + return DeriveKeyResponseMessage.encode({ successful: true }).finish(); } ///////////////////// // Crypto commands // ///////////////////// private async signFile(nodePath: string, request: Uint8Array) { - const { filePath, privateKeyPath, passphrase } = SignFileRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - const signaturePath = await pk.keyManager.signFile(filePath, privateKeyPath, passphrase) - return SignFileResponseMessage.encode({ signaturePath }).finish() + const { filePath, privateKeyPath, passphrase } = SignFileRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const signaturePath = await pk.keyManager.signFile(filePath, privateKeyPath, passphrase); + return SignFileResponseMessage.encode({ signaturePath }).finish(); } private async verifyFile(nodePath: string, request: Uint8Array) { - const { filePath, signaturePath } = VerifyFileRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - const verified = await pk.keyManager.verifyFile(filePath, signaturePath) - return VerifyFileResponseMessage.encode({ verified }).finish() + const { filePath, signaturePath } = VerifyFileRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const verified = await pk.keyManager.verifyFile(filePath, signaturePath); + return VerifyFileResponseMessage.encode({ verified }).finish(); } ////////////////////// // Vault Operations // ////////////////////// private async listVaults(nodePath: string) { - const pk = this.getPolykey(nodePath) - const vaultNames = pk.vaultManager.listVaults() - return ListVaultsResponseMessage.encode({ vaultNames }).finish() + const pk = this.getPolykey(nodePath); + const vaultNames = pk.vaultManager.listVaults(); + return ListVaultsResponseMessage.encode({ vaultNames }).finish(); } private async newVault(nodePath: string, request: Uint8Array) { - const { vaultName } = NewVaultRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - await pk.vaultManager.createVault(vaultName) - return NewVaultResponseMessage.encode({ successful: true }).finish() + const { vaultName } = NewVaultRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + await pk.vaultManager.createVault(vaultName); + return NewVaultResponseMessage.encode({ successful: true }).finish(); } private async destroyVault(nodePath: string, request: Uint8Array) { - const { vaultName } = DestroyVaultRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - pk.vaultManager.destroyVault(vaultName) - return DestroyVaultResponseMessage.encode({ successful: true }).finish() + const { vaultName } = DestroyVaultRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + pk.vaultManager.destroyVault(vaultName); + return DestroyVaultResponseMessage.encode({ successful: true }).finish(); } /////////////////////// // Secret Operations // /////////////////////// private async listSecrets(nodePath: string, request: Uint8Array) { - const { vaultName } = ListSecretsRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - const vault = pk.vaultManager.getVault(vaultName) - const secretNames = vault.listSecrets() - return ListSecretsResponseMessage.encode({ secretNames }).finish() + const { vaultName } = ListSecretsRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const vault = pk.vaultManager.getVault(vaultName); + const secretNames = vault.listSecrets(); + return ListSecretsResponseMessage.encode({ secretNames }).finish(); } private async createSecret(nodePath: string, request: Uint8Array) { - const { vaultName, secretName, secretPath } = CreateSecretRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - const vault = pk.vaultManager.getVault(vaultName) - const secret = await fs.promises.readFile(secretPath) - await vault.addSecret(secretName, secret) - return CreateSecretResponseMessage.encode({ successful: true }).finish() + const { vaultName, secretName, secretPath, secretContent } = CreateSecretRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const vault = pk.vaultManager.getVault(vaultName); + let secretBuffer: Buffer + if (secretPath) { + secretBuffer = await fs.promises.readFile(secretPath); + } else { + secretBuffer = Buffer.from(secretContent) + } + await vault.addSecret(secretName, secretBuffer); + return CreateSecretResponseMessage.encode({ successful: true }).finish(); } private async destroySecret(nodePath: string, request: Uint8Array) { - const { vaultName, secretName } = DestroySecretRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - const vault = pk.vaultManager.getVault(vaultName) - await vault.removeSecret(secretName) - return DestroySecretResponseMessage.encode({ successful: true }).finish() + const { vaultName, secretName } = DestroySecretRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const vault = pk.vaultManager.getVault(vaultName); + await vault.removeSecret(secretName); + return DestroySecretResponseMessage.encode({ successful: true }).finish(); } private async getSecret(nodePath: string, request: Uint8Array) { - const { vaultName, secretName } = GetSecretRequestMessage.decode(request) - const pk = this.getPolykey(nodePath) - const vault = pk.vaultManager.getVault(vaultName) - const secret = Buffer.from(vault.getSecret(secretName)) - return GetSecretResponseMessage.encode({ secret: secret }).finish() + const { vaultName, secretName } = GetSecretRequestMessage.decode(request); + const pk = this.getPolykey(nodePath); + const vault = pk.vaultManager.getVault(vaultName); + const secret = Buffer.from(vault.getSecret(secretName)); + return GetSecretResponseMessage.encode({ secret: secret }).finish(); } /////////////////////// // Client Connection // /////////////////////// - static connectToAgent(getStream?: () => PassThrough): PolykeyClient { + static connectToAgent(getStream?: () => Duplex): PolykeyClient { const defaultStream = () => { - const passThrough = new PassThrough() - const socket = net.createConnection(PolykeyAgent.SocketPath) - socket.pipe(passThrough) - passThrough.pipe(socket) - return passThrough - } - - const client = new PolykeyClient(getStream ?? defaultStream) + const socket = (net.createConnection(PolykeyAgent.SocketPath)); + return socket; + }; - // if (checkStatus) { - // const status = await client.getAgentStatus() - // if (status != 'online') { - // throw Error(`agent status is: ${status}, restart with 'pk agent start'`) - // } - // } + const client = new PolykeyClient(getStream ?? defaultStream); - return client + return client; } // ===== Helper methods===== // static get SocketPath(): string { - const platform = os.platform() - const userInfo = os.userInfo() + const platform = os.platform(); + const userInfo = os.userInfo(); if (platform == 'win32') { - return path.join('\\\\?\\pipe', process.cwd(), 'polykey-agent') + return path.join('\\\\?\\pipe', process.cwd(), 'polykey-agent'); } else { - return `/run/user/${userInfo.uid}/polykey/S.polykey-agent` + return `/run/user/${userInfo.uid}/polykey/S.polykey-agent`; } } public static get LogPath(): string { - const platform = os.platform() - const userInfo = os.userInfo() + const platform = os.platform(); + const userInfo = os.userInfo(); if (platform == 'win32') { - return path.join(os.tmpdir(), 'polykey', 'log') + return path.join(os.tmpdir(), 'polykey', 'log'); } else { - return `/run/user/${userInfo.uid}/polykey/log` + return `/run/user/${userInfo.uid}/polykey/log`; } } ////////////////////// // Agent Operations // ////////////////////// - static DAEMON_SCRIPT_PATH = path.join(__dirname, 'internal', 'daemon-script.js') + static DAEMON_SCRIPT_PATH = path.join(__dirname, 'internal', 'daemon-script.js'); public static async startAgent(daemon: boolean = false) { return new Promise((resolve, reject) => { try { let options: ForkOptions = { uid: process.getuid(), - detached: daemon - } + detached: daemon, + }; if (daemon) { - fs.rmdirSync(PolykeyAgent.LogPath, { recursive: true }) - fs.mkdirSync(PolykeyAgent.LogPath, { recursive: true }) + fs.rmdirSync(PolykeyAgent.LogPath, { recursive: true }); + fs.mkdirSync(PolykeyAgent.LogPath, { recursive: true }); options.stdio = [ 'ipc', fs.openSync(path.join(PolykeyAgent.LogPath, 'output.log'), 'a'), - fs.openSync(path.join(PolykeyAgent.LogPath, 'error.log'), 'a'), , - ] + fs.openSync(path.join(PolykeyAgent.LogPath, 'error.log'), 'a'), + ]; } - const agentProcess = fork( - PolykeyAgent.DAEMON_SCRIPT_PATH, - undefined, - options - ) + const agentProcess = fork(PolykeyAgent.DAEMON_SCRIPT_PATH, undefined, options); - const pid = agentProcess.pid - agentProcess.unref() - resolve(pid) + const pid = agentProcess.pid; + agentProcess.unref(); + resolve(pid); } catch (err) { - reject(err) + reject(err); } - }) + }); } } -export default PolykeyAgent +export default PolykeyAgent; diff --git a/src/lib/agent/PolykeyClient.ts b/src/lib/agent/PolykeyClient.ts index 4ae1f79520..4b92d20641 100644 --- a/src/lib/agent/PolykeyClient.ts +++ b/src/lib/agent/PolykeyClient.ts @@ -1,5 +1,5 @@ import { agent } from '../../../proto/js/Agent'; -import { PassThrough } from 'readable-stream' +import { Duplex } from 'readable-stream'; const { AgentMessage, CreateSecretRequestMessage, @@ -29,242 +29,265 @@ const { SignFileResponseMessage, Type, VerifyFileRequestMessage, - VerifyFileResponseMessage -} = agent + VerifyFileResponseMessage, +} = agent; class PolykeyClient { - private getStream: () => PassThrough + private getStream: () => Duplex; - constructor(getStream: () => PassThrough) { - this.getStream = getStream + constructor(getStream: () => Duplex) { + this.getStream = getStream; } async sendRequestToAgent(request: Uint8Array): Promise { - const stream = this.getStream() + const stream = this.getStream(); + const responseList = await new Promise((resolve, reject) => { try { - const responseList: Uint8Array[] = [] - stream.on('data', (data: Uint8Array) => { - responseList.push(data) - }) + const responseList: Uint8Array[] = []; + stream.on('data', (data: Uint8Array | Uint8Array[]) => { + if (data instanceof Uint8Array) { + responseList.push(data); + } else { + responseList.push(...data) + } + }); stream.on('error', (err) => { - reject(err) - }) + reject(err); + }); stream.on('end', () => { - resolve(responseList) - }) + resolve(responseList); + }); - stream.write(request) + if (!stream.writableEnded) { + stream.write(request); + } } catch (err) { - reject(err) + reject(err); } - }) - stream.end() - return responseList + }); + return responseList; } private async handleAgentCommunication( type: agent.Type, nodePath?: string, - request?: Uint8Array + request?: Uint8Array, ): Promise { // Encode message and sent - const agentMessage = AgentMessage.encode({ type: type, isResponse: false, nodePath: nodePath, subMessage: request }).finish() - const responseList = await this.sendRequestToAgent(agentMessage) - const agentMessageList: agent.AgentMessage[] = [] - for (const response of responseList) { - const { subMessage, type } = AgentMessage.decode(response) + const agentMessage = AgentMessage.encode({ + type: type, + isResponse: false, + nodePath: nodePath, + subMessage: request, + }).finish(); + const responseList = await this.sendRequestToAgent(agentMessage); + + const agentMessageList: agent.AgentMessage[] = []; + for (const response of responseList.values()) { + const { subMessage, type } = AgentMessage.decode(response); if (type == Type.ERROR) { - const { error } = ErrorMessage.decode(subMessage) - const reason = new Error(error) - throw reason + const { error } = ErrorMessage.decode(subMessage); + const reason = new Error(`Agent Error: ${error}`); + throw reason; } else { - agentMessageList.push(AgentMessage.decode(response)) + agentMessageList.push(AgentMessage.decode(response)); } } - return agentMessageList + return agentMessageList; } - async registerNode( - path: string, - passphrase: string - ) { - const registerNodeRequest = RegisterNodeRequestMessage.encode({ passphrase }).finish() + async registerNode(path: string, passphrase: string) { + const registerNodeRequest = RegisterNodeRequestMessage.encode({ passphrase }).finish(); + + const encodedResponse = await this.handleAgentCommunication(Type.REGISTER_NODE, path, registerNodeRequest); - const encodedResponse = await this.handleAgentCommunication(Type.REGISTER_NODE, path, registerNodeRequest) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const subMessage = encodedResponse.find((r) => r.type == Type.REGISTER_NODE)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { successful } = RegisterNodeResponseMessage.decode(encodedResponse[0].subMessage) + const { successful } = RegisterNodeResponseMessage.decode(subMessage); - return successful + return successful; } - async newNode( - path: string, - name: string, - email: string, - passphrase: string, - nbits?: number - ) { - const newNodeRequest = NewNodeRequestMessage.encode({ name, email, passphrase, nbits }).finish() - - const encodedResponse = await this.handleAgentCommunication(Type.NEW_NODE, path, newNodeRequest) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + async newNode(path: string, name: string, email: string, passphrase: string, nbits?: number) { + const newNodeRequest = NewNodeRequestMessage.encode({ name, email, passphrase, nbits }).finish(); + + const encodedResponse = await this.handleAgentCommunication(Type.NEW_NODE, path, newNodeRequest); + + const subMessage = encodedResponse.find((r) => r.type == Type.NEW_NODE)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { successful } = NewNodeResponseMessage.decode(encodedResponse[0].subMessage) + const { successful } = NewNodeResponseMessage.decode(subMessage); - return successful + return successful; } - async listNodes( - unlockedOnly: boolean = true - ) { - const newNodeRequest = ListNodesRequestMessage.encode({ unlockedOnly }).finish() + async listNodes(unlockedOnly: boolean = true) { + const newNodeRequest = ListNodesRequestMessage.encode({ unlockedOnly }).finish(); + + const encodedResponse = await this.handleAgentCommunication(Type.LIST_NODES, undefined, newNodeRequest); - const encodedResponse = await this.handleAgentCommunication(Type.LIST_NODES, undefined, newNodeRequest) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const subMessage = encodedResponse.find((r) => r.type == Type.LIST_NODES)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { nodes } = ListNodesResponseMessage.decode(encodedResponse[0].subMessage) - return nodes + const { nodes } = ListNodesResponseMessage.decode(subMessage); + return nodes; } ///////////////////// // Crypto commands // ///////////////////// async deriveKey(nodePath: string, keyName: string, passphrase: string) { - const request = DeriveKeyRequestMessage.encode({ keyName, passphrase }).finish() + const request = DeriveKeyRequestMessage.encode({ keyName, passphrase }).finish(); - const encodedResponse = await this.handleAgentCommunication(Type.DERIVE_KEY, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const encodedResponse = await this.handleAgentCommunication(Type.DERIVE_KEY, nodePath, request); + + const subMessage = encodedResponse.find((r) => r.type == Type.DERIVE_KEY)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { successful } = DeriveKeyResponseMessage.decode(encodedResponse[0].subMessage) - return successful + const { successful } = DeriveKeyResponseMessage.decode(subMessage); + return successful; } ///////////////////// // Crypto commands // ///////////////////// - async signFile( - nodePath: string, - filePath: string, - privateKeyPath?: string, - passphrase?: string - ) { - const request = SignFileRequestMessage.encode({ filePath, privateKeyPath, passphrase }).finish() - - const encodedResponse = await this.handleAgentCommunication(Type.SIGN_FILE, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + async signFile(nodePath: string, filePath: string, privateKeyPath?: string, passphrase?: string) { + const request = SignFileRequestMessage.encode({ filePath, privateKeyPath, passphrase }).finish(); + + const encodedResponse = await this.handleAgentCommunication(Type.SIGN_FILE, nodePath, request); + + const subMessage = encodedResponse.find((r) => r.type == Type.SIGN_FILE)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { signaturePath } = SignFileResponseMessage.decode(encodedResponse[0].subMessage) - return signaturePath + const { signaturePath } = SignFileResponseMessage.decode(subMessage); + return signaturePath; } - async verifyFile( - nodePath: string, - filePath: string, - signaturePath?: string - ) { - const request = VerifyFileRequestMessage.encode({ filePath, signaturePath }).finish() - - const encodedResponse = await this.handleAgentCommunication(Type.VERIFY_FILE, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + async verifyFile(nodePath: string, filePath: string, signaturePath?: string) { + const request = VerifyFileRequestMessage.encode({ filePath, signaturePath }).finish(); + + const encodedResponse = await this.handleAgentCommunication(Type.VERIFY_FILE, nodePath, request); + + const subMessage = encodedResponse.find((r) => r.type == Type.VERIFY_FILE)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { verified } = VerifyFileResponseMessage.decode(encodedResponse[0].subMessage) - return verified + const { verified } = VerifyFileResponseMessage.decode(subMessage); + return verified; } ////////////////////// // Vault Operations // ////////////////////// async listVaults(nodePath: string) { - const encodedResponse = await this.handleAgentCommunication(Type.LIST_VAULTS, nodePath) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const encodedResponse = await this.handleAgentCommunication(Type.LIST_VAULTS, nodePath); + + const subMessage = encodedResponse.find((r) => r.type == Type.LIST_VAULTS)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { vaultNames } = ListVaultsResponseMessage.decode(encodedResponse[0].subMessage) - return vaultNames + const { vaultNames } = ListVaultsResponseMessage.decode(subMessage); + return vaultNames; } async newVault(nodePath: string, vaultName: string) { - const request = NewVaultRequestMessage.encode({ vaultName }).finish() + const request = NewVaultRequestMessage.encode({ vaultName }).finish(); + + const encodedResponse = await this.handleAgentCommunication(Type.NEW_VAULT, nodePath, request); - const encodedResponse = await this.handleAgentCommunication(Type.NEW_VAULT, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const subMessage = encodedResponse.find((r) => r.type == Type.NEW_VAULT)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { successful } = NewVaultResponseMessage.decode(encodedResponse[0].subMessage) - return successful + const { successful } = NewVaultResponseMessage.decode(subMessage); + return successful; } async destroyVault(nodePath: string, vaultName: string) { - const request = DestroyVaultRequestMessage.encode({ vaultName }).finish() + const request = DestroyVaultRequestMessage.encode({ vaultName }).finish(); + + const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_VAULT, nodePath, request); - const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_VAULT, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const subMessage = encodedResponse.find((r) => r.type == Type.DESTROY_VAULT)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { successful } = DestroyVaultResponseMessage.decode(encodedResponse[0].subMessage) - return successful + const { successful } = DestroyVaultResponseMessage.decode(subMessage); + return successful; } /////////////////////// // Secret Operations // /////////////////////// async listSecrets(nodePath: string, vaultName: string) { - const request = ListSecretsRequestMessage.encode({ vaultName }).finish() - const encodedResponse = await this.handleAgentCommunication(Type.LIST_SECRETS, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const request = ListSecretsRequestMessage.encode({ vaultName }).finish(); + const encodedResponse = await this.handleAgentCommunication(Type.LIST_SECRETS, nodePath, request); + + const subMessage = encodedResponse.find((r) => r.type == Type.LIST_SECRETS)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { secretNames } = ListSecretsResponseMessage.decode(encodedResponse[0].subMessage) - return secretNames + const { secretNames } = ListSecretsResponseMessage.decode(subMessage); + return secretNames; } - async createSecret(nodePath: string, vaultName: string, secretName: string, secretPath: string) { - const request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretPath }).finish() + async createSecret(nodePath: string, vaultName: string, secretName: string, secret: string | Buffer) { + let request: Uint8Array + if (typeof secret == 'string') { + request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretPath: secret }).finish(); + } else { + request = CreateSecretRequestMessage.encode({ vaultName, secretName, secretContent: secret }).finish(); + } - const encodedResponse = await this.handleAgentCommunication(Type.CREATE_SECRET, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const encodedResponse = await this.handleAgentCommunication(Type.CREATE_SECRET, nodePath, request); + + const subMessage = encodedResponse.find((r) => r.type == Type.CREATE_SECRET)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { successful } = CreateSecretResponseMessage.decode(encodedResponse[0].subMessage) - return successful + const { successful } = CreateSecretResponseMessage.decode(subMessage); + return successful; } async destroySecret(nodePath: string, vaultName: string, secretName: string) { - const request = DestroySecretRequestMessage.encode({ vaultName, secretName }).finish() + const request = DestroySecretRequestMessage.encode({ vaultName, secretName }).finish(); + + const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_SECRET, nodePath, request); - const encodedResponse = await this.handleAgentCommunication(Type.DESTROY_SECRET, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const subMessage = encodedResponse.find((r) => r.type == Type.DESTROY_SECRET)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { successful } = DestroySecretResponseMessage.decode(encodedResponse[0].subMessage) - return successful + const { successful } = DestroySecretResponseMessage.decode(subMessage); + return successful; } async getSecret(nodePath: string, vaultName: string, secretName: string) { - const request = GetSecretRequestMessage.encode({ vaultName, secretName }).finish() + const request = GetSecretRequestMessage.encode({ vaultName, secretName }).finish(); - const encodedResponse = await this.handleAgentCommunication(Type.GET_SECRET, nodePath, request) - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const encodedResponse = await this.handleAgentCommunication(Type.GET_SECRET, nodePath, request); + + const subMessage = encodedResponse.find((r) => r.type == Type.GET_SECRET)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const { secret } = GetSecretResponseMessage.decode(encodedResponse[0].subMessage) - return Buffer.from(secret) + const { secret } = GetSecretResponseMessage.decode(subMessage); + return Buffer.from(secret); } /////////////////// @@ -272,27 +295,30 @@ class PolykeyClient { /////////////////// async getAgentStatus(): Promise { try { - const encodedResponse = await this.handleAgentCommunication(Type.STATUS) + const encodedResponse = await this.handleAgentCommunication(Type.STATUS); - if (encodedResponse.length == 0) { - throw Error('agent did not respond') + const subMessage = encodedResponse.find((r) => r.type == Type.STATUS)?.subMessage + if (!subMessage) { + throw Error('agent did not respond'); } - const status = encodedResponse[0].subMessage.toString() - return status + const status = Buffer.from(subMessage).toString(); + return status; } catch (err) { - return 'stopped' + console.log(err); + + return 'stopped'; } } async stopAgent(): Promise { try { // Tell it to start shutting and wait for response - await this.handleAgentCommunication(Type.STOP_AGENT) - return true + await this.handleAgentCommunication(Type.STOP_AGENT); + return true; } catch (err) { - return (await this.getAgentStatus() != 'online') + return (await this.getAgentStatus()) != 'online'; } } } -export default PolykeyClient +export default PolykeyClient; diff --git a/src/lib/agent/internal/daemon-script.js b/src/lib/agent/internal/daemon-script.js index 0c503d6bb9..f0ed6d5e5a 100644 --- a/src/lib/agent/internal/daemon-script.js +++ b/src/lib/agent/internal/daemon-script.js @@ -1,5 +1,5 @@ import { PolykeyAgent } from '../../Polykey'; -process.title = 'polykey-agent' +process.title = 'polykey-agent'; -new PolykeyAgent() +new PolykeyAgent(); diff --git a/src/lib/git/GitBackend.ts b/src/lib/git/GitBackend.ts index 12a69f8d9a..f9364e0b7e 100644 --- a/src/lib/git/GitBackend.ts +++ b/src/lib/git/GitBackend.ts @@ -18,12 +18,9 @@ import packObjects from './pack-objects/packObjects'; class GitBackend { private polykeyPath: string; private vaultManager: VaultManager; - constructor( - polykeyPath: string, - vaultManager: VaultManager - ) { - this.polykeyPath = polykeyPath - this.vaultManager = vaultManager + constructor(polykeyPath: string, vaultManager: VaultManager) { + this.polykeyPath = polykeyPath; + this.vaultManager = vaultManager; } /** @@ -33,103 +30,92 @@ class GitBackend { */ private exists(vaultName: string, publicKey: string) { try { - const vault = this.vaultManager.getVault(vaultName) + const vault = this.vaultManager.getVault(vaultName); if (vault) { - return vault.peerCanAccess(publicKey) + return vault.peerCanAccess(publicKey); } - return false + return false; } catch (error) { - return false + return false; } } async handleInfoRequest(vaultName: string): Promise { // Only handle upload-pack for now - const service = 'upload-pack' + const service = 'upload-pack'; - const connectingPublicKey = '' + const connectingPublicKey = ''; - const responseBuffers: Buffer[] = [] + const responseBuffers: Buffer[] = []; if (!this.exists(vaultName, connectingPublicKey)) { - throw new Error('Vault does not exist') + throw Error('Vault does not exist'); } else { - responseBuffers.push(Buffer.from(this.createGitPacketLine('# service=git-' + service + '\n'))) - responseBuffers.push(Buffer.from('0000')) - - const fileSystem = this.vaultManager.getVault(vaultName)?.EncryptedFS - - const buffers = await uploadPack( - fileSystem, - Path.join(this.polykeyPath, vaultName), - undefined, - true - ) - const buffersToWrite = buffers ?? [] - responseBuffers.push(...buffersToWrite) + responseBuffers.push(Buffer.from(this.createGitPacketLine('# service=git-' + service + '\n'))); + responseBuffers.push(Buffer.from('0000')); + + const fileSystem = this.vaultManager.getVault(vaultName)?.EncryptedFS; + + const buffers = await uploadPack(fileSystem, Path.join(this.polykeyPath, vaultName), undefined, true); + const buffersToWrite = buffers ?? []; + responseBuffers.push(...buffersToWrite); } - return Buffer.concat(responseBuffers) + return Buffer.concat(responseBuffers); } async handlePackRequest(vaultName: string, body: Buffer): Promise { + // eslint-disable-next-line return new Promise(async (resolve, reject) => { - const responseBuffers: Buffer[] = [] + const responseBuffers: Buffer[] = []; // Check if vault exists - const connectingPublicKey = '' + const connectingPublicKey = ''; if (!this.exists(vaultName, connectingPublicKey)) { - throw new Error('Vault does not exist') + throw Error('Vault does not exist'); } - const fileSystem = this.vaultManager.getVault(vaultName)?.EncryptedFS + const fileSystem = this.vaultManager.getVault(vaultName)?.EncryptedFS; if (fileSystem) { if (body.toString().slice(4, 8) == 'want') { - const wantedObjectId = body.toString().slice(9, 49) + const wantedObjectId = body.toString().slice(9, 49); const packResult = await packObjects( fileSystem, Path.join(this.polykeyPath, vaultName), [wantedObjectId], - undefined - ) + undefined, + ); // This the 'wait for more data' line as I understand it - responseBuffers.push(Buffer.from('0008NAK\n')) + responseBuffers.push(Buffer.from('0008NAK\n')); // This is to get the side band stuff working - const readable = new PassThrough() - const progressStream = new PassThrough() - const sideBand = GitSideBand.mux( - 'side-band-64', - readable, - packResult.packstream, - progressStream, - [] - ) + const readable = new PassThrough(); + const progressStream = new PassThrough(); + const sideBand = GitSideBand.mux('side-band-64', readable, packResult.packstream, progressStream, []); sideBand.on('data', (data: Buffer) => { - responseBuffers.push(data) - }) + responseBuffers.push(data); + }); sideBand.on('end', () => { - resolve(Buffer.concat(responseBuffers)) - }) + resolve(Buffer.concat(responseBuffers)); + }); sideBand.on('error', (err) => { - reject(err) - }) - + reject(err); + }); // Write progress to the client - progressStream.write(Buffer.from('0014progress is at 50%\n')) - progressStream.end() + progressStream.write(Buffer.from('0014progress is at 50%\n')); + progressStream.end(); } } - }) + }); } // ============ Helper functions ============ // private createGitPacketLine(line: string) { - const hexPrefix = (4 + line.length).toString(16) - return Array(4 - hexPrefix.length + 1).join('0') + hexPrefix + line + const hexPrefix = (4 + line.length).toString(16); + return Array(4 - hexPrefix.length + 1).join('0') + hexPrefix + line; } } -export default GitBackend +export default GitBackend; diff --git a/src/lib/git/GitClient.ts b/src/lib/git/GitClient.ts index d3b0025ce5..26887c0eaf 100644 --- a/src/lib/git/GitClient.ts +++ b/src/lib/git/GitClient.ts @@ -8,50 +8,38 @@ import { InfoRequest, PackRequest } from '../../../proto/compiled/Git_pb'; * Responsible for converting HTTP messages from isomorphic-git into requests and sending them to a specific peer. */ class GitClient { - private client: GitServerClient - private credentials: grpc.ChannelCredentials + private client: GitServerClient; + private credentials: grpc.ChannelCredentials; - constructor( - address: Address, - keyManager: KeyManager - ) { - // const pkiInfo = keyManager.PKIInfo - // if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) { - // this.credentials = grpc.credentials.createSsl( - // pkiInfo.caCert, - // pkiInfo.key, - // pkiInfo.cert, - // ) - // } else { - this.credentials = grpc.credentials.createInsecure() - // } - this.client = new GitServerClient(address.toString(), this.credentials) + constructor(address: Address, keyManager: KeyManager) { + const pkiInfo = keyManager.PKIInfo; + if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) { + this.credentials = grpc.credentials.createSsl(pkiInfo.caCert, pkiInfo.key, pkiInfo.cert); + } else { + this.credentials = grpc.credentials.createInsecure(); + } + this.client = new GitServerClient(address.toString(), this.credentials); } /** * The custom http request method to feed into isomorphic-git's [custom http object](https://isomorphic-git.org/docs/en/http) */ - async request({ - url, - method, - headers, - body, - onProgress - }) { + async request({ url, method, headers, body, onProgress }) { + // eslint-disable-next-line return new Promise(async (resolve, reject) => { - const u = new URL(url) + const u = new URL(url); // Parse request if (method == 'GET') { // Info request - const match = u.pathname.match(/\/(.+)\/info\/refs$/) + const match = u.pathname.match(/\/(.+)\/info\/refs$/); if (!match || /\.\./.test(match[1])) { - reject(new Error('Error')) + reject(new Error('Error')); } - const vaultName = match![1] + const vaultName = match![1]; - const infoResponse = await this.requestInfo(vaultName) + const infoResponse = await this.requestInfo(vaultName); resolve({ url: url, @@ -59,18 +47,18 @@ class GitClient { statusCode: 200, statusMessage: 'OK', body: this.iteratorFromData(infoResponse), - headers: headers - }) + headers: headers, + }); } else if (method == 'POST') { // Info request - const match = u.pathname.match(/\/(.+)\/git-(.+)/) + const match = u.pathname.match(/\/(.+)\/git-(.+)/); if (!match || /\.\./.test(match[1])) { - reject(new Error('Error')) + reject(new Error('Error')); } - const vaultName = match![1] + const vaultName = match![1]; - const packResponse = await this.requestPack(vaultName, body[0]) + const packResponse = await this.requestPack(vaultName, body[0]); resolve({ url: url, @@ -78,12 +66,12 @@ class GitClient { statusCode: 200, statusMessage: 'OK', body: this.iteratorFromData(packResponse), - headers: headers - }) + headers: headers, + }); } else { - reject(new Error('Method not supported')) + reject(new Error('Method not supported')); } - }) + }); } // ==== HELPER METHODS ==== // @@ -93,16 +81,16 @@ class GitClient { */ private async requestInfo(vaultName: string): Promise { return new Promise((resolve, reject) => { - const request = new InfoRequest() - request.setVaultname(vaultName) + const request = new InfoRequest(); + request.setVaultname(vaultName); this.client.requestInfo(request, function (err, response) { if (err) { - reject(err) + reject(err); } else { resolve(Buffer.from(response.getBody_asB64(), 'base64')); } }); - }) + }); } /** @@ -111,17 +99,17 @@ class GitClient { */ private async requestPack(vaultName: string, body: Uint8Array): Promise { return new Promise((resolve, reject) => { - const request = new PackRequest - request.setVaultname(vaultName) - request.setBody(body) + const request = new PackRequest(); + request.setVaultname(vaultName); + request.setBody(body); this.client.requestPack(request, function (err, response) { if (err) { - reject(err) + reject(err); } else { resolve(Buffer.from(response.getBody_asB64(), 'base64')); } }); - }) + }); } /** @@ -129,20 +117,20 @@ class GitClient { * @param data Data to be turned into an iterator */ private iteratorFromData(data: Uint8Array) { - let ended = false + let ended = false; return { next(): Promise { return new Promise((resolve, reject) => { if (ended) { - return resolve({ done: true }) + return resolve({ done: true }); } else { - ended = true - resolve({ value: data, done: false }) + ended = true; + resolve({ value: data, done: false }); } - }) + }); }, - } + }; } } -export default GitClient +export default GitClient; diff --git a/src/lib/git/pack-objects/GitCommit.ts b/src/lib/git/pack-objects/GitCommit.ts index 416653e6ea..5daa57a570 100644 --- a/src/lib/git/pack-objects/GitCommit.ts +++ b/src/lib/git/pack-objects/GitCommit.ts @@ -2,214 +2,208 @@ // -0 (just so we don't lose that information when parsing and reconstructing) // but can also default to +0 was extraordinary. -function simpleSign (n) { - return Math.sign(n) || (Object.is(n, -0) ? -1 : 1) +function simpleSign(n) { + return Math.sign(n) || (Object.is(n, -0) ? -1 : 1); } -function negateExceptForZero (n) { - return n === 0 ? n : -n +function negateExceptForZero(n) { + return n === 0 ? n : -n; } -function formatTimezoneOffset (minutes) { - let sign = simpleSign(negateExceptForZero(minutes)) - minutes = Math.abs(minutes) - let hours = Math.floor(minutes / 60) - minutes -= hours * 60 - let strHours = String(hours) - let strMinutes = String(minutes) - if (strHours.length < 2) strHours = '0' + strHours - if (strMinutes.length < 2) strMinutes = '0' + strMinutes - return (sign === -1 ? '-' : '+') + strHours + strMinutes +function formatTimezoneOffset(minutes) { + let sign = simpleSign(negateExceptForZero(minutes)); + minutes = Math.abs(minutes); + let hours = Math.floor(minutes / 60); + minutes -= hours * 60; + let strHours = String(hours); + let strMinutes = String(minutes); + if (strHours.length < 2) strHours = '0' + strHours; + if (strMinutes.length < 2) strMinutes = '0' + strMinutes; + return (sign === -1 ? '-' : '+') + strHours + strMinutes; } -function parseTimezoneOffset (offset) { - let [, sign, hours, minutes] = offset.match(/(\+|-)(\d\d)(\d\d)/) - minutes = (sign === '+' ? 1 : -1) * (Number(hours) * 60 + Number(minutes)) - return negateExceptForZero(minutes) +function parseTimezoneOffset(offset) { + let [, sign, hours, minutes] = offset.match(/(\+|-)(\d\d)(\d\d)/); + minutes = (sign === '+' ? 1 : -1) * (Number(hours) * 60 + Number(minutes)); + return negateExceptForZero(minutes); } -function parseAuthor (author) { - let [, name, email, timestamp, offset] = author.match( - /^(.*) <(.*)> (.*) (.*)$/ - ) +function parseAuthor(author) { + let [, name, email, timestamp, offset] = author.match(/^(.*) <(.*)> (.*) (.*)$/); return { name: name, email: email, timestamp: Number(timestamp), - timezoneOffset: parseTimezoneOffset(offset) - } + timezoneOffset: parseTimezoneOffset(offset), + }; } -function normalize (str) { +function normalize(str) { // remove all - str = str.replace(/\r/g, '') + str = str.replace(/\r/g, ''); // no extra newlines up front - str = str.replace(/^\n+/, '') + str = str.replace(/^\n+/, ''); // and a single newline at the end - str = str.replace(/\n+$/, '') + '\n' - return str + str = str.replace(/\n+$/, '') + '\n'; + return str; } -function indent (str) { +function indent(str) { return ( str .trim() .split('\n') - .map(x => ' ' + x) + .map((x) => ' ' + x) .join('\n') + '\n' - ) + ); } -function outdent (str) { +function outdent(str) { return str .split('\n') - .map(x => x.replace(/^ /, '')) - .join('\n') + .map((x) => x.replace(/^ /, '')) + .join('\n'); } // TODO: Make all functions have static async signature? class GitCommit { - _commit: string - constructor (commit) { + _commit: string; + constructor(commit) { if (typeof commit === 'string') { - this._commit = commit + this._commit = commit; } else if (Buffer.isBuffer(commit)) { - this._commit = commit.toString('utf8') + this._commit = commit.toString('utf8'); } else if (typeof commit === 'object') { - this._commit = GitCommit.render(commit) + this._commit = GitCommit.render(commit); } else { - throw(new Error('invalid type passed to GitCommit constructor')) + throw new Error('invalid type passed to GitCommit constructor'); } } - static fromPayloadSignature ({ payload, signature }) { - let headers = GitCommit.justHeaders(payload) - let message = GitCommit.justMessage(payload) - let commit = normalize( - headers + '\ngpgsig' + indent(signature) + '\n' + message - ) - return new GitCommit(commit) + static fromPayloadSignature({ payload, signature }) { + let headers = GitCommit.justHeaders(payload); + let message = GitCommit.justMessage(payload); + let commit = normalize(headers + '\ngpgsig' + indent(signature) + '\n' + message); + return new GitCommit(commit); } - static from (commit) { - return new GitCommit(commit) + static from(commit) { + return new GitCommit(commit); } - toObject () { - return Buffer.from(this._commit, 'utf8') + toObject() { + return Buffer.from(this._commit, 'utf8'); } // Todo: allow setting the headers and message - headers () { - return this.parseHeaders() + headers() { + return this.parseHeaders(); } // Todo: allow setting the headers and message - message () { - return GitCommit.justMessage(this._commit) + message() { + return GitCommit.justMessage(this._commit); } - parse () { - return Object.assign({ message: this.message() }, this.headers()) + parse() { + return Object.assign({ message: this.message() }, this.headers()); } - static justMessage (commit) { - return normalize(commit.slice(commit.indexOf('\n\n') + 2)) + static justMessage(commit) { + return normalize(commit.slice(commit.indexOf('\n\n') + 2)); } - static justHeaders (commit) { - return commit.slice(0, commit.indexOf('\n\n')) + static justHeaders(commit) { + return commit.slice(0, commit.indexOf('\n\n')); } - parseHeaders () { - let headers = GitCommit.justHeaders(this._commit).split('\n') - let hs: string[] = [] + parseHeaders() { + let headers = GitCommit.justHeaders(this._commit).split('\n'); + let hs: string[] = []; for (let h of headers) { if (h[0] === ' ') { // combine with previous header (without space indent) - hs[hs.length - 1] += '\n' + h.slice(1) + hs[hs.length - 1] += '\n' + h.slice(1); } else { - hs.push(h) + hs.push(h); } } let obj: any = { - parent: [] - } + parent: [], + }; for (let h of hs) { - let key = h.slice(0, h.indexOf(' ')) - let value = h.slice(h.indexOf(' ') + 1) + let key = h.slice(0, h.indexOf(' ')); + let value = h.slice(h.indexOf(' ') + 1); if (Array.isArray(obj[key])) { - obj[key].push(value) + obj[key].push(value); } else { - obj[key] = value + obj[key] = value; } } if (obj.author) { - obj.author = parseAuthor(obj.author) + obj.author = parseAuthor(obj.author); } if (obj.committer) { - obj.committer = parseAuthor(obj.committer) + obj.committer = parseAuthor(obj.committer); } - return obj + return obj; } - static renderHeaders (obj) { - let headers = '' + static renderHeaders(obj) { + let headers = ''; if (obj.tree) { - headers += `tree ${obj.tree}\n` + headers += `tree ${obj.tree}\n`; } else { - headers += `tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n` // the null tree + headers += `tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n`; // the null tree } if (obj.parent) { if (obj.parent.length === undefined) { - throw(new Error(`commit 'parent' property should be an array`)) + throw new Error(`commit 'parent' property should be an array`); } for (let p of obj.parent) { - headers += `parent ${p}\n` + headers += `parent ${p}\n`; } } - let author = obj.author - headers += `author ${author.name} <${author.email}> ${ - author.timestamp - } ${formatTimezoneOffset(author.timezoneOffset)}\n` - let committer = obj.committer || obj.author - headers += `committer ${committer.name} <${committer.email}> ${ - committer.timestamp - } ${formatTimezoneOffset(committer.timezoneOffset)}\n` + let author = obj.author; + headers += `author ${author.name} <${author.email}> ${author.timestamp} ${formatTimezoneOffset( + author.timezoneOffset, + )}\n`; + let committer = obj.committer || obj.author; + headers += `committer ${committer.name} <${committer.email}> ${committer.timestamp} ${formatTimezoneOffset( + committer.timezoneOffset, + )}\n`; if (obj.gpgsig) { - headers += 'gpgsig' + indent(obj.gpgsig) + headers += 'gpgsig' + indent(obj.gpgsig); } - return headers + return headers; } - static render (obj) { - return GitCommit.renderHeaders(obj) + '\n' + normalize(obj.message) + static render(obj) { + return GitCommit.renderHeaders(obj) + '\n' + normalize(obj.message); } - render () { - return this._commit + render() { + return this._commit; } - withoutSignature () { - let commit = normalize(this._commit) - if (commit.indexOf('\ngpgsig') === -1) return commit - let headers = commit.slice(0, commit.indexOf('\ngpgsig')) + withoutSignature() { + let commit = normalize(this._commit); + if (commit.indexOf('\ngpgsig') === -1) return commit; + let headers = commit.slice(0, commit.indexOf('\ngpgsig')); let message = commit.slice( - commit.indexOf('-----END PGP SIGNATURE-----\n') + - '-----END PGP SIGNATURE-----\n'.length - ) - return normalize(headers + '\n' + message) + commit.indexOf('-----END PGP SIGNATURE-----\n') + '-----END PGP SIGNATURE-----\n'.length, + ); + return normalize(headers + '\n' + message); } - isolateSignature () { + isolateSignature() { let signature = this._commit.slice( this._commit.indexOf('-----BEGIN PGP SIGNATURE-----'), - this._commit.indexOf('-----END PGP SIGNATURE-----') + - '-----END PGP SIGNATURE-----'.length - ) - return outdent(signature) + this._commit.indexOf('-----END PGP SIGNATURE-----') + '-----END PGP SIGNATURE-----'.length, + ); + return outdent(signature); } } -export default GitCommit +export default GitCommit; diff --git a/src/lib/git/pack-objects/GitObject.ts b/src/lib/git/pack-objects/GitObject.ts index 60492e78b2..a9505cb3ec 100644 --- a/src/lib/git/pack-objects/GitObject.ts +++ b/src/lib/git/pack-objects/GitObject.ts @@ -1,46 +1,40 @@ -import shasum from './shasum' +import shasum from './shasum'; class GitObject { - static hash ({ type, object }) { - let buffer = Buffer.concat([ - Buffer.from(`${type} ${object.byteLength.toString()}\0`), - Buffer.from(object) - ]) - let oid = shasum(buffer) - return oid + static hash({ type, object }) { + let buffer = Buffer.concat([Buffer.from(`${type} ${object.byteLength.toString()}\0`), Buffer.from(object)]); + let oid = shasum(buffer); + return oid; } - static wrap ({ type, object }) { - let buffer = Buffer.concat([ - Buffer.from(`${type} ${object.byteLength.toString()}\0`), - object - ]) - let oid = shasum(buffer) + static wrap({ type, object }) { + let buffer = Buffer.concat([Buffer.from(`${type} ${object.byteLength.toString()}\0`), object]); + let oid = shasum(buffer); return { oid, - buffer - } + buffer, + }; } - static unwrap ({ oid, buffer }) { + static unwrap({ oid, buffer }) { if (oid) { - let sha = shasum(buffer) + let sha = shasum(buffer); if (sha !== oid) { - throw(new Error(`SHA check failed! Expected ${oid}, computed ${sha}`)) + throw new Error(`SHA check failed! Expected ${oid}, computed ${sha}`); } } - let s = buffer.indexOf(32) // first space - let i = buffer.indexOf(0) // first null value - let type = buffer.slice(0, s).toString('utf8') // get type of object - let length = buffer.slice(s + 1, i).toString('utf8') // get type of object - let actualLength = buffer.length - (i + 1) + let s = buffer.indexOf(32); // first space + let i = buffer.indexOf(0); // first null value + let type = buffer.slice(0, s).toString('utf8'); // get type of object + let length = buffer.slice(s + 1, i).toString('utf8'); // get type of object + let actualLength = buffer.length - (i + 1); // verify length if (parseInt(length) !== actualLength) { - throw(new Error(`Length mismatch: expected ${length} bytes but got ${actualLength} instead.`)) + throw new Error(`Length mismatch: expected ${length} bytes but got ${actualLength} instead.`); } return { type, - object: Buffer.from(buffer.slice(i + 1)) - } + object: Buffer.from(buffer.slice(i + 1)), + }; } } -export default GitObject +export default GitObject; diff --git a/src/lib/git/pack-objects/GitObjectManager.ts b/src/lib/git/pack-objects/GitObjectManager.ts index fcab1b86dc..c907959900 100644 --- a/src/lib/git/pack-objects/GitObjectManager.ts +++ b/src/lib/git/pack-objects/GitObjectManager.ts @@ -1,63 +1,62 @@ -import fs from 'fs' -import pako from 'pako' -import path from 'path' -import GitObject from './GitObject' -import { EncryptedFS } from 'encryptedfs' +import fs from 'fs'; +import pako from 'pako'; +import path from 'path'; +import GitObject from './GitObject'; +import { EncryptedFS } from 'encryptedfs'; -const PackfileCache = new Map() +const PackfileCache = new Map(); class GitObjectManager { static async read(fileSystem: EncryptedFS, gitdir: string, oid: string, format = 'content') { // Look for it in the loose object directory. - let file = fileSystem.readFileSync(`${gitdir}/objects/${oid.slice(0, 2)}/${oid.slice(2)}`) - let source = `./objects/${oid.slice(0, 2)}/${oid.slice(2)}` + let file = fileSystem.readFileSync(`${gitdir}/objects/${oid.slice(0, 2)}/${oid.slice(2)}`); + let source = `./objects/${oid.slice(0, 2)}/${oid.slice(2)}`; // Check to see if it's in a packfile. if (!file) { // Curry the current read method so that the packfile un-deltification // process can acquire external ref-deltas. - const getExternalRefDelta = oid => - GitObjectManager.read(fileSystem, gitdir, oid) + const getExternalRefDelta = (oid) => GitObjectManager.read(fileSystem, gitdir, oid); // Iterate through all the .pack files - let list = fs.readdirSync(path.join(gitdir, '/objects/pack')) - list = list.filter(x => x.endsWith('.pack')) + let list = fs.readdirSync(path.join(gitdir, '/objects/pack')); + list = list.filter((x) => x.endsWith('.pack')); for (let filename of list) { // Try to get the packfile from the in-memory cache - let p = PackfileCache.get(filename) + let p = PackfileCache.get(filename); // If the packfile DOES have the oid we're looking for... if (p.offsets.has(oid)) { // Make sure the packfile is loaded in memory if (!p.pack) { - const pack = fileSystem.readFileSync(`${gitdir}/objects/pack/${filename}`) - await p.load({ pack }) + const pack = fileSystem.readFileSync(`${gitdir}/objects/pack/${filename}`); + await p.load({ pack }); } // Get the resolved git object from the packfile - let result = await p.read({ oid, getExternalRefDelta }) - result.source = `./objects/pack/${filename}` - return result + let result = await p.read({ oid, getExternalRefDelta }); + result.source = `./objects/pack/${filename}`; + return result; } } } // Check to see if it's in shallow commits. if (!file) { - let text = fileSystem.readFileSync(`${gitdir}/shallow`, { encoding: 'utf8' }) + let text = fileSystem.readFileSync(`${gitdir}/shallow`, { encoding: 'utf8' }); if (text !== null && text.includes(oid)) { - throw(new Error(`ReadShallowObjectFail: ${oid}`)) + throw new Error(`ReadShallowObjectFail: ${oid}`); } } // Finally if (!file) { - throw(new Error(`ReadObjectFail: ${oid}`)) + throw new Error(`ReadObjectFail: ${oid}`); } if (format === 'deflated') { - return { format: 'deflated', object: file, source } + return { format: 'deflated', object: file, source }; } - let buffer = Buffer.from(pako.inflate(file)) + let buffer = Buffer.from(pako.inflate(file)); if (format === 'wrapped') { - return { format: 'wrapped', object: buffer, source } + return { format: 'wrapped', object: buffer, source }; } - let { type, object } = GitObject.unwrap({ oid, buffer }) - if (format === 'content') return { type, format: 'content', object, source } + let { type, object } = GitObject.unwrap({ oid, buffer }); + if (format === 'content') return { type, format: 'content', object, source }; } } -export default GitObjectManager +export default GitObjectManager; diff --git a/src/lib/git/pack-objects/GitTree.ts b/src/lib/git/pack-objects/GitTree.ts index a3c17ca60e..195ea71ffa 100644 --- a/src/lib/git/pack-objects/GitTree.ts +++ b/src/lib/git/pack-objects/GitTree.ts @@ -7,96 +7,98 @@ type TreeEntry = { } */ -function parseBuffer (buffer) { - let _entries: any[] = [] - let cursor = 0 +function parseBuffer(buffer) { + let _entries: any[] = []; + let cursor = 0; while (cursor < buffer.length) { - let space = buffer.indexOf(32, cursor) + let space = buffer.indexOf(32, cursor); if (space === -1) { - throw(new Error(`GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next space character.`)) + throw new Error( + `GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next space character.`, + ); } - let nullchar = buffer.indexOf(0, cursor) + let nullchar = buffer.indexOf(0, cursor); if (nullchar === -1) { - throw(new Error(`GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next null character.`)) + throw new Error( + `GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next null character.`, + ); } - let mode = buffer.slice(cursor, space).toString('utf8') - if (mode === '40000') mode = '040000' // makes it line up neater in printed output - let type = mode === '040000' ? 'tree' : 'blob' - let path = buffer.slice(space + 1, nullchar).toString('utf8') - let oid = buffer.slice(nullchar + 1, nullchar + 21).toString('hex') - cursor = nullchar + 21 - _entries.push({ mode, path, oid, type }) + let mode = buffer.slice(cursor, space).toString('utf8'); + if (mode === '40000') mode = '040000'; // makes it line up neater in printed output + let type = mode === '040000' ? 'tree' : 'blob'; + let path = buffer.slice(space + 1, nullchar).toString('utf8'); + let oid = buffer.slice(nullchar + 1, nullchar + 21).toString('hex'); + cursor = nullchar + 21; + _entries.push({ mode, path, oid, type }); } - return _entries + return _entries; } -function limitModeToAllowed (mode) { +function limitModeToAllowed(mode) { if (typeof mode === 'number') { - mode = mode.toString(8) + mode = mode.toString(8); } // tree - if (mode.match(/^0?4.*/)) return '40000' // Directory - if (mode.match(/^1006.*/)) return '100644' // Regular non-executable file - if (mode.match(/^1007.*/)) return '100755' // Regular executable file - if (mode.match(/^120.*/)) return '120000' // Symbolic link - if (mode.match(/^160.*/)) return '160000' // Commit (git submodule reference) - throw(new Error(`Could not understand file mode: ${mode}`)) + if (mode.match(/^0?4.*/)) return '40000'; // Directory + if (mode.match(/^1006.*/)) return '100644'; // Regular non-executable file + if (mode.match(/^1007.*/)) return '100755'; // Regular executable file + if (mode.match(/^120.*/)) return '120000'; // Symbolic link + if (mode.match(/^160.*/)) return '160000'; // Commit (git submodule reference) + throw new Error(`Could not understand file mode: ${mode}`); } -function nudgeIntoShape (entry) { +function nudgeIntoShape(entry) { if (!entry.oid && entry.sha) { - entry.oid = entry.sha // Github + entry.oid = entry.sha; // Github } - entry.mode = limitModeToAllowed(entry.mode) // index + entry.mode = limitModeToAllowed(entry.mode); // index if (!entry.type) { - entry.type = 'blob' // index + entry.type = 'blob'; // index } - return entry + return entry; } class GitTree { /* :: _entries: Array */ - _entries: any[] - constructor (entries) { + _entries: any[]; + constructor(entries) { if (Buffer.isBuffer(entries)) { - this._entries = parseBuffer(entries) + this._entries = parseBuffer(entries); } else if (Array.isArray(entries)) { - this._entries = entries.map(nudgeIntoShape) + this._entries = entries.map(nudgeIntoShape); } else { - throw(new Error('invalid type passed to GitTree constructor')) + throw new Error('invalid type passed to GitTree constructor'); } } - static from (tree) { - return new GitTree(tree) + static from(tree) { + return new GitTree(tree); } - render () { - return this._entries - .map(entry => `${entry.mode} ${entry.type} ${entry.oid} ${entry.path}`) - .join('\n') + render() { + return this._entries.map((entry) => `${entry.mode} ${entry.type} ${entry.oid} ${entry.path}`).join('\n'); } - toObject () { + toObject() { return Buffer.concat( this._entries.map((entry) => { - let mode = Buffer.from(entry.mode.replace(/^0/, '')) - let space = Buffer.from(' ') - let path = Buffer.from(entry.path) + let mode = Buffer.from(entry.mode.replace(/^0/, '')); + let space = Buffer.from(' '); + let path = Buffer.from(entry.path); // let path = Buffer.from(entry.path, { encoding: 'utf8' }) - let nullchar = Buffer.from([0]) - let oid = Buffer.from(entry.oid.match(/../g).map(n => parseInt(n, 16))) - return Buffer.concat([mode, space, path, nullchar, oid]) - }) - ) + let nullchar = Buffer.from([0]); + let oid = Buffer.from(entry.oid.match(/../g).map((n) => parseInt(n, 16))); + return Buffer.concat([mode, space, path, nullchar, oid]); + }), + ); } - entries () { - return this._entries + entries() { + return this._entries; } - * [Symbol.iterator] () { + *[Symbol.iterator]() { for (let entry of this._entries) { - yield entry + yield entry; } } } -export default GitTree +export default GitTree; diff --git a/src/lib/git/pack-objects/log.ts b/src/lib/git/pack-objects/log.ts index bea0a9b037..536d8ad273 100644 --- a/src/lib/git/pack-objects/log.ts +++ b/src/lib/git/pack-objects/log.ts @@ -1,34 +1,31 @@ -import path = require("path") -import GitCommit from './GitCommit' -import { EncryptedFS } from 'encryptedfs' -import GitObjectManager from './GitObjectManager' -import GitRefManager from '../upload-pack/GitRefManager' +import path = require('path'); +import GitCommit from './GitCommit'; +import { EncryptedFS } from 'encryptedfs'; +import GitObjectManager from './GitObjectManager'; +import GitRefManager from '../upload-pack/GitRefManager'; - - -async function logCommit (fileSystem: EncryptedFS, gitdir: string, oid: string, signing: boolean) { +async function logCommit(fileSystem: EncryptedFS, gitdir: string, oid: string, signing: boolean) { try { - let { type, object } = await GitObjectManager.read(fileSystem, gitdir, oid) + let { type, object } = await GitObjectManager.read(fileSystem, gitdir, oid); if (type !== 'commit') { - throw(new Error('expected type to be commit')) + throw new Error('expected type to be commit'); } - const commit = GitCommit.from(object) - const result = Object.assign({ oid }, commit.parse()) + const commit = GitCommit.from(object); + const result = Object.assign({ oid }, commit.parse()); if (signing) { - result.payload = commit.withoutSignature() + result.payload = commit.withoutSignature(); } - return result + return result; } catch (err) { return { oid, - error: err - } + error: err, + }; } } - -function compareAge (a, b) { - return a.committer.timestamp - b.committer.timestamp +function compareAge(a, b) { + return a.committer.timestamp - b.committer.timestamp; } /** @@ -36,67 +33,64 @@ function compareAge (a, b) { * * @link https://isomorphic-git.github.io/docs/log.html */ -async function log ( +async function log( fileSystem: EncryptedFS, dir, gitdir = path.join(dir, '.git'), ref = 'HEAD', depth, since, // Date - signing = false + signing = false, ) { try { - let sinceTimestamp = - since === undefined ? undefined : Math.floor(since.valueOf() / 1000) + let sinceTimestamp = since === undefined ? undefined : Math.floor(since.valueOf() / 1000); // TODO: In the future, we may want to have an API where we return a // async iterator that emits commits. - let commits: any[] = [] - let oid = await GitRefManager.resolve(fileSystem, gitdir, ref) - let tips /* : Array */ = [await logCommit(fileSystem, gitdir, oid, signing)] + let commits: any[] = []; + let oid = await GitRefManager.resolve(fileSystem, gitdir, ref); + let tips = [await logCommit(fileSystem, gitdir, oid, signing)]; + // eslint-disable-next-line while (true) { - let commit = tips.pop() + let commit = tips.pop(); // Stop the loop if we encounter an error if (commit.error) { - commits.push(commit) - break + commits.push(commit); + break; } // Stop the log if we've hit the age limit - if ( - sinceTimestamp !== undefined && - commit.committer.timestamp <= sinceTimestamp - ) { - break + if (sinceTimestamp !== undefined && commit.committer.timestamp <= sinceTimestamp) { + break; } - commits.push(commit) + commits.push(commit); // Stop the loop if we have enough commits now. - if (depth !== undefined && commits.length === depth) break + if (depth !== undefined && commits.length === depth) break; // Add the parents of this commit to the queue // Note: for the case of a commit with no parents, it will concat an empty array, having no net effect. for (const oid of commit.parent) { - let commit = await logCommit(fileSystem, gitdir, oid, signing) - if (!tips.map(commit => commit.oid).includes(commit.oid)) { - tips.push(commit) + let commit = await logCommit(fileSystem, gitdir, oid, signing); + if (!tips.map((commit) => commit.oid).includes(commit.oid)) { + tips.push(commit); } } // Stop the loop if there are no more commit parents - if (tips.length === 0) break + if (tips.length === 0) break; // Process tips in order by age - tips.sort(compareAge) + tips.sort(compareAge); } - return commits + return commits; } catch (err) { - err.caller = 'git.log' - throw err + err.caller = 'git.log'; + throw err; } } -export default log -export {logCommit} +export default log; +export { logCommit }; diff --git a/src/lib/git/pack-objects/packObjects.ts b/src/lib/git/pack-objects/packObjects.ts index ce710de3a7..7e02d1097f 100644 --- a/src/lib/git/pack-objects/packObjects.ts +++ b/src/lib/git/pack-objects/packObjects.ts @@ -1,12 +1,12 @@ -import pako from 'pako' -import path from 'path' -import log from './log' -import GitTree from './GitTree' -import createHash from 'sha.js' -import GitCommit from './GitCommit' -import { EncryptedFS } from 'encryptedfs' -import { PassThrough } from 'readable-stream' -import GitObjectManager from './GitObjectManager' +import pako from 'pako'; +import path from 'path'; +import log from './log'; +import GitTree from './GitTree'; +import createHash from 'sha.js'; +import GitCommit from './GitCommit'; +import { EncryptedFS } from 'encryptedfs'; +import { PassThrough } from 'readable-stream'; +import GitObjectManager from './GitObjectManager'; const types = { commit: 0b0010000, @@ -14,68 +14,51 @@ const types = { blob: 0b0110000, tag: 0b1000000, ofs_delta: 0b1100000, - ref_delta: 0b1110000 -} + ref_delta: 0b1110000, +}; type Ack = { - oid: string -} + oid: string; +}; /** * Create a packfile stream * * @link https://isomorphic-git.github.io/docs/packObjects.html */ -async function packObjects ( - fileSystem: EncryptedFS, - dir: string, - refs: string[], - depth?: number, - haves?: string[], -) { - const gitdir = path.join(dir, '.git') - let oids = new Set() - let shallows = new Set() - let unshallows = new Set() - let acks: Ack[] = [] +async function packObjects(fileSystem: EncryptedFS, dir: string, refs: string[], depth?: number, haves?: string[]) { + const gitdir = path.join(dir, '.git'); + let oids = new Set(); + let shallows = new Set(); + let unshallows = new Set(); + let acks: Ack[] = []; - haves = (haves) ? haves : [] + haves = haves ? haves : []; - const emitter = undefined - const since = undefined + const emitter = undefined; + const since = undefined; for (const ref of refs) { try { - let commits = await log( - fileSystem, - dir, - gitdir, - emitter, - ref, - depth, - since - ) + let commits = await log(fileSystem, dir, gitdir, emitter, ref, depth, since); - let oldshallows: string[] = [] + let oldshallows: string[] = []; for (let i = 0; i < commits.length; i++) { - let commit = commits[i] + let commit = commits[i]; if (haves.includes(commit.oid)) { acks.push({ - oid: ref - }) - break + oid: ref, + }); + break; } - oids.add(commit.oid) + oids.add(commit.oid); if (i === commits.length - 1) { - if ( - !oldshallows.includes(commit.oid) && - (depth !== undefined || since !== undefined) - ) { - console.log('make it shallow', commit.oid) - shallows.add(commit.oid) + if (!oldshallows.includes(commit.oid) && (depth !== undefined || since !== undefined)) { + console.log('make it shallow', commit.oid); + shallows.add(commit.oid); } } else if (oldshallows.includes(commit.oid)) { - console.log('make it unshallow', commit.oid) - unshallows.add(commit.oid) + console.log('make it unshallow', commit.oid); + unshallows.add(commit.oid); } } } catch (err) { @@ -83,50 +66,44 @@ async function packObjects ( // oh well. } } - let objects = await listObjects(fileSystem, dir, gitdir, Array.from(oids)) + let objects = await listObjects(fileSystem, dir, gitdir, Array.from(oids)); - let packstream = new PassThrough() - pack( - fileSystem, - dir, - undefined, - [...objects], - packstream - ) - return { packstream, shallows, unshallows, acks } + let packstream = new PassThrough(); + pack(fileSystem, dir, undefined, [...objects], packstream); + return { packstream, shallows, unshallows, acks }; } -async function listObjects ( +async function listObjects( fileSystem: EncryptedFS, dir: string, gitdir: string = path.join(dir, '.git'), - oids: string[] + oids: string[], ) { - let commits = new Set() - let trees = new Set() - let blobs = new Set() + let commits = new Set(); + let trees = new Set(); + let blobs = new Set(); // We don't do the purest simplest recursion, because we can // avoid reading Blob objects entirely since the Tree objects // tell us which oids are Blobs and which are Trees. And we // do not need to recurse through commit parents. - async function walk (oid) { - let { type, object } = await GitObjectManager.read(fileSystem, gitdir, oid) + async function walk(oid) { + let { type, object } = await GitObjectManager.read(fileSystem, gitdir, oid); if (type === 'commit') { - commits.add(oid) - let commit = GitCommit.from(object) - let tree = commit.headers().tree - await walk(tree) + commits.add(oid); + let commit = GitCommit.from(object); + let tree = commit.headers().tree; + await walk(tree); } else if (type === 'tree') { - trees.add(oid) - let tree = GitTree.from(object) + trees.add(oid); + let tree = GitTree.from(object); for (let entry of tree) { if (entry.type === 'blob') { - blobs.add(entry.oid) + blobs.add(entry.oid); } // only recurse for trees if (entry.type === 'tree') { - await walk(entry.oid) + await walk(entry.oid); } } } @@ -134,75 +111,75 @@ async function listObjects ( // Let's go walking! for (let oid of oids) { - await walk(oid) + await walk(oid); } - return [...commits, ...trees, ...blobs] + return [...commits, ...trees, ...blobs]; } -async function pack ( +async function pack( fileSystem: EncryptedFS, dir: string, gitdir: string = path.join(dir, '.git'), oids: string[], - outputStream: PassThrough + outputStream: PassThrough, ) { - let hash = createHash('sha1') + let hash = createHash('sha1'); function write(chunk: any, enc: string | undefined = undefined) { - if(enc) { - outputStream.write(chunk, enc) + if (enc) { + outputStream.write(chunk, enc); } else { - outputStream.write(chunk) + outputStream.write(chunk); } - hash.update(chunk, enc) + hash.update(chunk, enc); } - function writeObject (object, stype) { - let lastFour - let multibyte - let length + function writeObject(object, stype) { + let lastFour; + let multibyte; + let length; // Object type is encoded in bits 654 - let type = types[stype] - if (type === undefined) throw new Error('Unrecognized type: ' + stype) + let type = types[stype]; + if (type === undefined) throw Error('Unrecognized type: ' + stype); // The length encoding get complicated. - length = object.length + length = object.length; // Whether the next byte is part of the variable-length encoded number // is encoded in bit 7 - multibyte = length > 0b1111 ? 0b10000000 : 0b0 + multibyte = length > 0b1111 ? 0b10000000 : 0b0; // Last four bits of length is encoded in bits 3210 - lastFour = length & 0b1111 + lastFour = length & 0b1111; // Discard those bits - length = length >>> 4 + length = length >>> 4; // The first byte is then (1-bit multibyte?), (3-bit type), (4-bit least sig 4-bits of length) - let byte: any = (multibyte | type | lastFour).toString(16) - write(byte, 'hex') + let byte: any = (multibyte | type | lastFour).toString(16); + write(byte, 'hex'); // Now we keep chopping away at length 7-bits at a time until its zero, // writing out the bytes in what amounts to little-endian order. while (multibyte) { - multibyte = length > 0b01111111 ? 0b10000000 : 0b0 - byte = multibyte | (length & 0b01111111) - const unpaddedChunk = byte.toString(16) - const paddedChunk = '0'.repeat(2-unpaddedChunk.length) + unpaddedChunk - write(paddedChunk, 'hex') - length = length >>> 7 + multibyte = length > 0b01111111 ? 0b10000000 : 0b0; + byte = multibyte | (length & 0b01111111); + const unpaddedChunk = byte.toString(16); + const paddedChunk = '0'.repeat(2 - unpaddedChunk.length) + unpaddedChunk; + write(paddedChunk, 'hex'); + length = length >>> 7; } // Lastly, we can compress and write the object. - write(Buffer.from(pako.deflate(object))) + write(Buffer.from(pako.deflate(object))); } - write('PACK') - write('00000002', 'hex') + write('PACK'); + write('00000002', 'hex'); // Write a 4 byte (32-bit) int - const unpaddedChunk = oids.length.toString(16) - const paddedChunk = '0'.repeat(8-unpaddedChunk.length) + unpaddedChunk - write(paddedChunk, 'hex') + const unpaddedChunk = oids.length.toString(16); + const paddedChunk = '0'.repeat(8 - unpaddedChunk.length) + unpaddedChunk; + write(paddedChunk, 'hex'); for (let oid of oids) { - let { type, object } = await GitObjectManager.read(fileSystem, gitdir, oid) - writeObject(object, type) + let { type, object } = await GitObjectManager.read(fileSystem, gitdir, oid); + writeObject(object, type); } // Write SHA1 checksum - let digest = hash.digest() - outputStream.end(digest) - return outputStream + let digest = hash.digest(); + outputStream.end(digest); + return outputStream; } -export default packObjects -export {listObjects, pack} +export default packObjects; +export { listObjects, pack }; diff --git a/src/lib/git/pack-objects/shasum.ts b/src/lib/git/pack-objects/shasum.ts index 848fe2004c..204de90220 100644 --- a/src/lib/git/pack-objects/shasum.ts +++ b/src/lib/git/pack-objects/shasum.ts @@ -1,10 +1,10 @@ -import Hash from 'sha.js/sha1' +import Hash from 'sha.js/sha1'; // This is modeled after @dominictarr's "shasum" module, // but without the 'json-stable-stringify' dependency and // extra type-casting features. -function shasum (buffer: Buffer) { - return new Hash().update(buffer).digest('hex') +function shasum(buffer: Buffer) { + return new Hash().update(buffer).digest('hex'); } -export default shasum +export default shasum; diff --git a/src/lib/git/side-band/GitSideBand.ts b/src/lib/git/side-band/GitSideBand.ts index 767ff500cc..d18acd6632 100644 --- a/src/lib/git/side-band/GitSideBand.ts +++ b/src/lib/git/side-band/GitSideBand.ts @@ -19,122 +19,116 @@ information. If no 'side-band' capability was specified, the server will stream the entire packfile without multiplexing. */ -import { Buffer } from 'buffer' -import { PassThrough } from 'readable-stream' +import { Buffer } from 'buffer'; +import { PassThrough } from 'readable-stream'; -import GitPktLine from '../upload-pack/GitPktLine' +import GitPktLine from '../upload-pack/GitPktLine'; function splitBuffer(buffer: Buffer, maxBytes: number) { const result: Buffer[] = []; - let index = 0 + let index = 0; while (index < buffer.length) { - const buf = buffer.slice(index, index+maxBytes) - result.push(buf) - index += buf.length + const buf = buffer.slice(index, index + maxBytes); + result.push(buf); + index += buf.length; } - result.push(buffer.slice(index)) + result.push(buffer.slice(index)); return result; } class GitSideBand { - static demux (input) { - let read = GitPktLine.streamReader(input) + static demux(input) { + let read = GitPktLine.streamReader(input); // And now for the ridiculous side-band or side-band-64k protocol - let packetlines = new PassThrough() - let packfile = new PassThrough() - let progress = new PassThrough() + let packetlines = new PassThrough(); + let packfile = new PassThrough(); + let progress = new PassThrough(); // TODO: Use a proper through stream? const nextBit = async function () { - let line = await read() + let line = await read(); // Skip over flush packets - if (line === null) return nextBit() + if (line === null) return nextBit(); // A made up convention to signal there's no more to read. if (line === true) { - packetlines.end() - progress.end() - packfile.end() - return + packetlines.end(); + progress.end(); + packfile.end(); + return; } // Examine first byte to determine which output "stream" to use switch (line[0]) { case 1: // pack data - packfile.write(line.slice(1)) - break + packfile.write(line.slice(1)); + break; case 2: // progress message - progress.write(line.slice(1)) - break + progress.write(line.slice(1)); + break; case 3: // fatal error message just before stream aborts - let error = line.slice(1) - progress.write(error) - packfile.destroy(new Error(error.toString('utf8'))) - return + // eslint-disable-next-line + const error = line.slice(1); + progress.write(error); + packfile.destroy(new Error(error.toString('utf8'))); + return; default: // Not part of the side-band-64k protocol - packetlines.write(line.slice(0)) + packetlines.write(line.slice(0)); } // Careful not to blow up the stack. // I think Promises in a tail-call position should be OK. - nextBit() - } - nextBit() + nextBit(); + }; + nextBit(); return { packetlines, packfile, - progress - } + progress, + }; } - static mux ( + static mux( protocol, // 'side-band' or 'side-band-64k' packetlines, packfile, progress, - error + error, ) { - const MAX_PACKET_LENGTH = protocol === 'side-band-64k' ? 999 : 65519 - let output = new PassThrough() - packetlines.on('data', data => { + const MAX_PACKET_LENGTH = protocol === 'side-band-64k' ? 999 : 65519; + let output = new PassThrough(); + packetlines.on('data', (data) => { if (data === null) { - output.write(GitPktLine.flush()) + output.write(GitPktLine.flush()); } else { - output.write(GitPktLine.encode(data)) + output.write(GitPktLine.encode(data)); } - }) - let packfileWasEmpty = true - let packfileEnded = false - let progressEnded = false - let errorEnded = true - let goodbye = Buffer.concat([ - GitPktLine.encode(Buffer.from('010A', 'hex')), - GitPktLine.flush() - ]) + }); + let packfileWasEmpty = true; + let packfileEnded = false; + let progressEnded = false; + let errorEnded = true; + let goodbye = Buffer.concat([GitPktLine.encode(Buffer.from('010A', 'hex')), GitPktLine.flush()]); packfile - .on('data', data => { - packfileWasEmpty = false - const buffers = splitBuffer(data, MAX_PACKET_LENGTH) + .on('data', (data) => { + packfileWasEmpty = false; + const buffers = splitBuffer(data, MAX_PACKET_LENGTH); for (const buffer of buffers) { - output.write( - GitPktLine.encode(Buffer.concat([Buffer.from('01', 'hex'), buffer])) - ) + output.write(GitPktLine.encode(Buffer.concat([Buffer.from('01', 'hex'), buffer]))); } }) .on('end', () => { - packfileEnded = true - if (!packfileWasEmpty) output.write(goodbye) - if (progressEnded && errorEnded) output.end() - }) + packfileEnded = true; + if (!packfileWasEmpty) output.write(goodbye); + if (progressEnded && errorEnded) output.end(); + }); progress - .on('data', data => { - const buffers = splitBuffer(data, MAX_PACKET_LENGTH) + .on('data', (data) => { + const buffers = splitBuffer(data, MAX_PACKET_LENGTH); for (const buffer of buffers) { - output.write( - GitPktLine.encode(Buffer.concat([Buffer.from('02', 'hex'), buffer])) - ) + output.write(GitPktLine.encode(Buffer.concat([Buffer.from('02', 'hex'), buffer]))); } }) .on('end', () => { - progressEnded = true - if (packfileEnded && errorEnded) output.end() - }) + progressEnded = true; + if (packfileEnded && errorEnded) output.end(); + }); // error // .on('data', data => { // const buffers = splitBuffer(data, MAX_PACKET_LENGTH) @@ -148,8 +142,8 @@ class GitSideBand { // errorEnded = true // if (progressEnded && packfileEnded) output.end() // }) - return output + return output; } } -export default GitSideBand +export default GitSideBand; diff --git a/src/lib/git/upload-pack/GitPackedRefs.ts b/src/lib/git/upload-pack/GitPackedRefs.ts index ef2ab90d2e..af08624ee6 100644 --- a/src/lib/git/upload-pack/GitPackedRefs.ts +++ b/src/lib/git/upload-pack/GitPackedRefs.ts @@ -1,49 +1,49 @@ type Config = { - line: string - ref?: string - peeled?: string - oid?: string - comment?: boolean -} + line: string; + ref?: string; + peeled?: string; + oid?: string; + comment?: boolean; +}; class GitPackedRefs { - refs: Map - parsedConfig: Config[] + refs: Map; + parsedConfig: Config[]; constructor(text: string) { - this.refs = new Map() - this.parsedConfig = [] + this.refs = new Map(); + this.parsedConfig = []; if (text) { - let key: string + let key: string; this.parsedConfig = text .trim() .split('\n') - .map(line => { + .map((line) => { if (/^\s*#/.test(line)) { - return { line: line, comment: true } + return { line: line, comment: true }; } - const i = line.indexOf(' ') + const i = line.indexOf(' '); if (line.startsWith('^')) { // This is a oid for the commit associated with the annotated tag immediately preceding this line. // Trim off the '^' - const value = line.slice(1) + const value = line.slice(1); // The tagname^{} syntax is based on the output of `git show-ref --tags -d` - this.refs.set(key + '^{}', value) - return { line: line, ref: key, peeled: value } + this.refs.set(key + '^{}', value); + return { line: line, ref: key, peeled: value }; } else { // This is an oid followed by the ref name - const value = line.slice(0, i) - key = line.slice(i + 1) - this.refs.set(key, value) - return { line: line, ref: key, oid: value } + const value = line.slice(0, i); + key = line.slice(i + 1); + this.refs.set(key, value); + return { line: line, ref: key, oid: value }; } - }) + }); } - return this + return this; } static from(text) { - return new GitPackedRefs(text) + return new GitPackedRefs(text); } } -export default GitPackedRefs +export default GitPackedRefs; diff --git a/src/lib/git/upload-pack/GitPktLine.ts b/src/lib/git/upload-pack/GitPktLine.ts index a27feb041e..c2fa8ebdd3 100644 --- a/src/lib/git/upload-pack/GitPktLine.ts +++ b/src/lib/git/upload-pack/GitPktLine.ts @@ -50,10 +50,9 @@ Examples (as C-style strings): ---- */ - function padHex(b, n) { - const s = n.toString(16) - return '0'.repeat(b - s.length) + s + const s = n.toString(16); + return '0'.repeat(b - s.length) + s; } // I'm really using this more as a namespace. @@ -61,34 +60,34 @@ function padHex(b, n) { class GitPktLine { static flush() { - return Buffer.from('0000', 'utf8') + return Buffer.from('0000', 'utf8'); } static encode(line) { if (typeof line === 'string') { - line = Buffer.from(line) + line = Buffer.from(line); } - const length = line.length + 4 - const hexlength = padHex(4, length) - return Buffer.concat([Buffer.from(hexlength, 'utf8'), line]) + const length = line.length + 4; + const hexlength = padHex(4, length); + return Buffer.concat([Buffer.from(hexlength, 'utf8'), line]); } - static streamReader (stream) { - return async function read () { + static streamReader(stream) { + return async function read() { try { - let length = await stream.slice(4) - if (length === null) return true - length = parseInt(length.toString('utf8'), 16) - if (length === 0) return null - let buffer = await stream.slice(length - 4) - if (buffer === null) return true - return buffer + let length = await stream.slice(4); + if (length === null) return true; + length = parseInt(length.toString('utf8'), 16); + if (length === 0) return null; + let buffer = await stream.slice(length - 4); + if (buffer === null) return true; + return buffer; } catch (err) { - console.log('error', err) - return true + console.log('error', err); + return true; } - } + }; } } -export default GitPktLine +export default GitPktLine; diff --git a/src/lib/git/upload-pack/GitRefManager.ts b/src/lib/git/upload-pack/GitRefManager.ts index 44ab9d83b9..27dd7e8f5d 100644 --- a/src/lib/git/upload-pack/GitRefManager.ts +++ b/src/lib/git/upload-pack/GitRefManager.ts @@ -1,126 +1,126 @@ // This is a convenience wrapper for reading and writing files in the 'refs' directory. -import path from 'path' -import { EncryptedFS } from 'encryptedfs' -import GitPackedRefs from './GitPackedRefs' +import path from 'path'; +import { EncryptedFS } from 'encryptedfs'; +import GitPackedRefs from './GitPackedRefs'; // @see https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions -const refpaths = ref => [ +const refpaths = (ref) => [ `${ref}`, `refs/${ref}`, `refs/tags/${ref}`, `refs/heads/${ref}`, `refs/remotes/${ref}`, `refs/remotes/${ref}/HEAD`, -] +]; function compareRefNames(a, b) { // https://stackoverflow.com/a/40355107/2168416 - const _a = a.replace(/\^\{\}$/, '') - const _b = b.replace(/\^\{\}$/, '') - const tmp = -(_a < _b) || +(_a > _b) + const _a = a.replace(/\^\{\}$/, ''); + const _b = b.replace(/\^\{\}$/, ''); + const tmp = -(_a < _b) || +(_a > _b); if (tmp === 0) { - return a.endsWith('^{}') ? 1 : -1 + return a.endsWith('^{}') ? 1 : -1; } - return tmp + return tmp; } - // @see https://git-scm.com/docs/gitrepository-layout -const GIT_FILES = ['config', 'description', 'index', 'shallow', 'commondir'] - +const GIT_FILES = ['config', 'description', 'index', 'shallow', 'commondir']; // This function is used to get all the files in the refs folder for listRefs function async function recursiveDirectoryWalk(dir: string, fileSystem: EncryptedFS): Promise { return new Promise((resolve, reject) => { let results: string[] = []; - fileSystem.promises.readdir(dir).then(async (list) => { - var pending = list.length; - if (!pending) return resolve(results); - list.forEach(async function(file) { - file = path.resolve(dir, file); - fileSystem.promises.stat(file).then(async (stat) => { - if (stat && stat.isDirectory()) { - const res = await recursiveDirectoryWalk(file, fileSystem) - results = results.concat(res); - if (!--pending) resolve(results); - } else { - results.push(file); - if (!--pending) resolve(results); - } + fileSystem.promises + .readdir(dir) + .then(async (list) => { + var pending = list.length; + if (!pending) return resolve(results); + list.forEach(async function (file) { + file = path.resolve(dir, file); + fileSystem.promises.stat(file).then(async (stat) => { + if (stat && stat.isDirectory()) { + const res = await recursiveDirectoryWalk(file, fileSystem); + results = results.concat(res); + if (!--pending) resolve(results); + } else { + results.push(file); + if (!--pending) resolve(results); + } + }); }); + }) + .catch((err) => { + if (err) return reject(err); }); - }).catch((err) => { - if (err) return reject(err); - }) - }) -}; + }); +} class GitRefManager { static async packedRefs(fileSystem: EncryptedFS, gitdir: string) { - const text = fileSystem.readFileSync(`${gitdir}/packed-refs`, { encoding: 'utf8' }) - const packed = GitPackedRefs.from(text) - return packed.refs + const text = fileSystem.readFileSync(`${gitdir}/packed-refs`, { encoding: 'utf8' }); + const packed = GitPackedRefs.from(text); + return packed.refs; } // List all the refs that match the `filepath` prefix static async listRefs(fileSystem: EncryptedFS, gitdir: string, filepath: string): Promise { - const packedMap = GitRefManager.packedRefs(fileSystem, gitdir) - let files: string[] = [] + const packedMap = GitRefManager.packedRefs(fileSystem, gitdir); + let files: string[] = []; try { - files = await recursiveDirectoryWalk(`${gitdir}/${filepath}`, fileSystem) + files = await recursiveDirectoryWalk(`${gitdir}/${filepath}`, fileSystem); - files = files.map(x => x.replace(`${gitdir}/${filepath}/`, '')) + files = files.map((x) => x.replace(`${gitdir}/${filepath}/`, '')); } catch (err) { - files = [] + files = []; } for (let key of (await packedMap).keys()) { // filter by prefix if (key.startsWith(filepath)) { // remove prefix - key = key.replace(filepath + '/', '') + key = key.replace(filepath + '/', ''); // Don't include duplicates; the loose files have precedence anyway if (!files.includes(key)) { - files.push(key) + files.push(key); } } } // since we just appended things onto an array, we need to sort them now - files.sort(compareRefNames) + files.sort(compareRefNames); - return files + return files; } static async resolve(fileSystem: EncryptedFS, gitdir: string, ref: string, depth?: number) { if (depth !== undefined) { - depth-- + depth--; if (depth === -1) { - return ref + return ref; } } // Is it a ref pointer? if (ref.startsWith('ref: ')) { - ref = ref.slice('ref: '.length) - return GitRefManager.resolve(fileSystem, gitdir, ref, depth) + ref = ref.slice('ref: '.length); + return GitRefManager.resolve(fileSystem, gitdir, ref, depth); } // Is it a complete and valid SHA? if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) { - return ref + return ref; } // We need to alternate between the file system and the packed-refs - const packedMap = await GitRefManager.packedRefs(fileSystem, gitdir) + const packedMap = await GitRefManager.packedRefs(fileSystem, gitdir); // Look in all the proper paths, in this order - const allpaths = refpaths(ref).filter(p => !GIT_FILES.includes(p)) // exclude git system files (#709) + const allpaths = refpaths(ref).filter((p) => !GIT_FILES.includes(p)); // exclude git system files (#709) for (const ref of allpaths) { - const sha = (fileSystem.readFileSync(`${gitdir}/${ref}`, { encoding: 'utf8' }).toString()) || packedMap.get(ref) + const sha = fileSystem.readFileSync(`${gitdir}/${ref}`, { encoding: 'utf8' }).toString() || packedMap.get(ref); if (sha) { - return GitRefManager.resolve(fileSystem, gitdir, sha.trim(), depth) + return GitRefManager.resolve(fileSystem, gitdir, sha.trim(), depth); } } // Do we give up? - throw(Error('RefNotFound')) + throw Error('RefNotFound'); } - } -export default GitRefManager +export default GitRefManager; diff --git a/src/lib/git/upload-pack/uploadPack.ts b/src/lib/git/upload-pack/uploadPack.ts index ea9f8a1e19..1056287f9a 100644 --- a/src/lib/git/upload-pack/uploadPack.ts +++ b/src/lib/git/upload-pack/uploadPack.ts @@ -1,26 +1,26 @@ -import path from 'path' -import GitPktLine from './GitPktLine' -import { EncryptedFS } from 'encryptedfs' -import GitRefManager from './GitRefManager' +import path from 'path'; +import GitPktLine from './GitPktLine'; +import { EncryptedFS } from 'encryptedfs'; +import GitRefManager from './GitRefManager'; async function writeRefsAdResponse({ capabilities, refs, symrefs }) { - const stream: Buffer[] = [] + const stream: Buffer[] = []; // Compose capabilities string - let syms = '' + let syms = ''; for (const [key, value] of Object.entries(symrefs)) { - syms += `symref=${key}:${value} ` + syms += `symref=${key}:${value} `; } - let caps = `\x00${[...capabilities].join(' ')} ${syms}agent=git/isomorphic-git@1.4.0` + let caps = `\x00${[...capabilities].join(' ')} ${syms}agent=git/isomorphic-git@1.4.0`; // stream.write(GitPktLine.encode(`# service=${service}\n`)) // stream.write(GitPktLine.flush()) // Note: In the edge case of a brand new repo, zero refs (and zero capabilities) // are returned. for (const [key, value] of Object.entries(refs)) { - stream.push(GitPktLine.encode(`${value} ${key}${caps}\n`)) - caps = '' + stream.push(GitPktLine.encode(`${value} ${key}${caps}\n`)); + caps = ''; } - stream.push(GitPktLine.flush()) - return stream + stream.push(GitPktLine.flush()); + return stream; } async function uploadPack( @@ -32,40 +32,29 @@ async function uploadPack( try { if (advertiseRefs) { // Send a refs advertisement - const capabilities = [ - 'side-band-64k', - ] - let keys = await GitRefManager.listRefs( - fileSystem, - gitdir, - 'refs' - ) - keys = keys.map(ref => `refs/${ref}`) - const refs = {} - keys.unshift('HEAD') // HEAD must be the first in the list + const capabilities = ['side-band-64k']; + let keys = await GitRefManager.listRefs(fileSystem, gitdir, 'refs'); + keys = keys.map((ref) => `refs/${ref}`); + const refs = {}; + keys.unshift('HEAD'); // HEAD must be the first in the list for (const key of keys) { - refs[key] = await GitRefManager.resolve(fileSystem, gitdir, key) + refs[key] = await GitRefManager.resolve(fileSystem, gitdir, key); } - const symrefs = {} + const symrefs = {}; - symrefs['HEAD'] = await GitRefManager.resolve( - fileSystem, - gitdir, - 'HEAD', - 2, - ) + symrefs['HEAD'] = await GitRefManager.resolve(fileSystem, gitdir, 'HEAD', 2); return writeRefsAdResponse({ capabilities, refs, symrefs, - }) + }); } } catch (err) { - err.caller = 'git.uploadPack' - throw err + err.caller = 'git.uploadPack'; + throw err; } } -export default uploadPack +export default uploadPack; diff --git a/src/lib/keys/KeyManager.ts b/src/lib/keys/KeyManager.ts index 5ead0ef364..639a5e6f95 100644 --- a/src/lib/keys/KeyManager.ts +++ b/src/lib/keys/KeyManager.ts @@ -8,72 +8,69 @@ import { Pool, ModuleThread } from 'threads'; import { KeyManagerWorker } from '../keys/KeyManagerWorker'; type KeyManagerMetadata = { - privateKeyPath: string | null, - publicKeyPath: string | null, - pkiKeyPath: string | null, - pkiCertPath: string | null, - caCertPath: string | null, -} + privateKeyPath: string | null; + publicKeyPath: string | null; + pkiKeyPath: string | null; + pkiCertPath: string | null; + caCertPath: string | null; +}; type KeyPair = { - private: string | null, - public: string | null -} + private: string | null; + public: string | null; +}; -type PKInfo = { key: Buffer | null, cert: Buffer | null, caCert: Buffer | null } +type PKInfo = { key: Buffer | null; cert: Buffer | null; caCert: Buffer | null }; class KeyManager { - private primaryKeyPair: KeyPair = { private: null, public: null } - private primaryIdentity?: Object - private derivedKeys: Map - private useWebWorkers: boolean - private workerPool?: Pool> + private primaryKeyPair: KeyPair = { private: null, public: null }; + private primaryIdentity?: Object; + private derivedKeys: Map; + private useWebWorkers: boolean; + private workerPool?: Pool>; - polykeyPath: string - private fileSystem: typeof fs + polykeyPath: string; + private fileSystem: typeof fs; - private keypairPath: string - private metadataPath: string + private keypairPath: string; + private metadataPath: string; private metadata: KeyManagerMetadata = { privateKeyPath: null, publicKeyPath: null, pkiKeyPath: null, pkiCertPath: null, caCertPath: null, - } + }; ///////// // PKI // ///////// - pkiInfo: PKInfo = { key: null, cert: null, caCert: null } + pkiInfo: PKInfo = { key: null, cert: null, caCert: null }; constructor( polyKeyPath: string = `${os.homedir()}/.polykey`, fileSystem: typeof fs, useWebWorkers: boolean = false, - workerPool?: Pool> + workerPool?: Pool>, ) { - this.useWebWorkers = useWebWorkers - this.workerPool = workerPool - this.derivedKeys = new Map() - this.fileSystem = fileSystem + this.useWebWorkers = useWebWorkers; + this.workerPool = workerPool; + this.derivedKeys = new Map(); + this.fileSystem = fileSystem; // Load key manager metadata - this.polykeyPath = polyKeyPath - this.keypairPath = path.join(polyKeyPath, '.keypair') + this.polykeyPath = polyKeyPath; + this.keypairPath = path.join(polyKeyPath, '.keypair'); if (!this.fileSystem.existsSync(this.keypairPath)) { - this.fileSystem.mkdirSync(this.keypairPath, { recursive: true }) + this.fileSystem.mkdirSync(this.keypairPath, { recursive: true }); } - this.metadataPath = path.join(this.keypairPath, 'metadata') - this.loadMetadata() + this.metadataPath = path.join(this.keypairPath, 'metadata'); + this.loadMetadata(); // Load keys if they were provided if (this.metadata.privateKeyPath && this.metadata.publicKeyPath) { // Load files into memory - this.loadKeyPair( - this.metadata.publicKeyPath, - this.metadata.privateKeyPath - ) + this.loadKeyPair(this.metadata.publicKeyPath, this.metadata.privateKeyPath); } ///////// @@ -81,19 +78,19 @@ class KeyManager { ///////// // Load pki keys and certs if (this.metadata.pkiKeyPath) { - this.pkiInfo.key = fs.readFileSync(this.metadata.pkiKeyPath) + this.pkiInfo.key = fs.readFileSync(this.metadata.pkiKeyPath); } if (this.metadata.pkiCertPath) { - this.pkiInfo.cert = fs.readFileSync(this.metadata.pkiCertPath) + this.pkiInfo.cert = fs.readFileSync(this.metadata.pkiCertPath); } if (this.metadata.caCertPath) { - this.pkiInfo.caCert = fs.readFileSync(this.metadata.caCertPath) + this.pkiInfo.caCert = fs.readFileSync(this.metadata.caCertPath); } - this.loadPKIInfo(this.pkiInfo.key, this.pkiInfo.cert, this.pkiInfo.caCert, true) + this.loadPKIInfo(this.pkiInfo.key, this.pkiInfo.cert, this.pkiInfo.caCert, true); } public get identityLoaded(): boolean { - return (this.primaryIdentity) ? true : false + return this.primaryIdentity ? true : false; } /** @@ -111,68 +108,68 @@ class KeyManager { passphrase: string, nbits: number = 4096, replacePrimary: boolean = false, - progressCallback?: (info) => void + progressCallback?: (info) => void, ): Promise { // kbpgp doesn't seem to work for small nbits so set a minimum of 1024 if (nbits < 1024) { - throw new Error('nbits must be greater than 1024 for keypair generation') + throw Error('nbits must be greater than 1024 for keypair generation'); } // Define options - const flags = kbpgp["const"].openpgp + const flags = kbpgp['const'].openpgp; const params = { - asp: (progressCallback) ? new kbpgp.ASP({ progress_hook: progressCallback }) : undefined, + asp: progressCallback ? new kbpgp.ASP({ progress_hook: progressCallback }) : undefined, userid: `${name} <${email}>`, primary: { nbits: nbits, flags: flags.certify_keys | flags.sign_data | flags.auth | flags.encrypt_comm | flags.encrypt_storage, - expire_in: 0 // never expire + expire_in: 0, // never expire }, - subkeys: [] - } + subkeys: [], + }; - const identity = await promisify(kbpgp.KeyManager.generate)(params) + const identity = await promisify(kbpgp.KeyManager.generate)(params); - await promisify(identity.sign.bind(identity))({}) + await promisify(identity.sign.bind(identity))({}); // Export pub key first - const publicKey = await promisify(identity.export_pgp_public.bind(identity))({}) + const publicKey = await promisify(identity.export_pgp_public.bind(identity))({}); // Finally export priv key - const privateKey = await promisify(identity.export_pgp_private.bind(identity))({ passphrase: passphrase }) + const privateKey = await promisify(identity.export_pgp_private.bind(identity))({ passphrase: passphrase }); // Resolve to parent promise - const keypair = { private: privateKey, public: publicKey } + const keypair = { private: privateKey, public: publicKey }; if (replacePrimary) { // Set the new keypair - this.primaryKeyPair = keypair + this.primaryKeyPair = keypair; // Set the new identity - this.primaryIdentity = identity + this.primaryIdentity = identity; // Overwrite in memory - const privateKeyPath = path.join(this.keypairPath, 'private_key') - const publicKeyPath = path.join(this.keypairPath, 'public_key') - await this.fileSystem.promises.writeFile(privateKeyPath, keypair.private) - await this.fileSystem.promises.writeFile(publicKeyPath, keypair.public) + const privateKeyPath = path.join(this.keypairPath, 'private_key'); + const publicKeyPath = path.join(this.keypairPath, 'public_key'); + await this.fileSystem.promises.writeFile(privateKeyPath, keypair.private); + await this.fileSystem.promises.writeFile(publicKeyPath, keypair.public); // Set metadata - this.metadata.privateKeyPath = privateKeyPath - this.metadata.publicKeyPath = publicKeyPath - this.writeMetadata() + this.metadata.privateKeyPath = privateKeyPath; + this.metadata.publicKeyPath = publicKeyPath; + this.writeMetadata(); } - return keypair + return keypair; } /** * Get the primary keypair */ getKeyPair(): KeyPair { - return this.primaryKeyPair + return this.primaryKeyPair; } /** * Determines whether public key is loaded or not */ hasPublicKey(): boolean { - return (this.primaryKeyPair.public) ? true : false + return this.primaryKeyPair.public ? true : false; } /** @@ -180,9 +177,9 @@ class KeyManager { */ getPublicKey(): string { if (!this.primaryKeyPair.public) { - throw new Error('Public key does not exist in memory') + throw Error('Public key does not exist in memory'); } - return this.primaryKeyPair.public + return this.primaryKeyPair.public; } /** @@ -190,9 +187,9 @@ class KeyManager { */ getPrivateKey(): string { if (!this.primaryKeyPair.private) { - throw new Error('Private key does not exist in memory') + throw Error('Private key does not exist in memory'); } - return this.primaryKeyPair.private + return this.primaryKeyPair.private; } /** @@ -201,8 +198,8 @@ class KeyManager { * @param privateKey Private Key */ loadKeyPair(publicKey: string | Buffer, privateKey: string | Buffer): void { - this.loadPrivateKey(privateKey) - this.loadPublicKey(publicKey) + this.loadPrivateKey(privateKey); + this.loadPublicKey(publicKey); } /** @@ -210,15 +207,15 @@ class KeyManager { * @param privateKey Private Key */ loadPrivateKey(privateKey: string | Buffer): void { - let keyBuffer: Buffer + let keyBuffer: Buffer; if (typeof privateKey === 'string') { - keyBuffer = this.fileSystem.readFileSync(privateKey) - this.metadata.privateKeyPath = privateKey - this.writeMetadata() + keyBuffer = this.fileSystem.readFileSync(privateKey); + this.metadata.privateKeyPath = privateKey; + this.writeMetadata(); } else { - keyBuffer = privateKey + keyBuffer = privateKey; } - this.primaryKeyPair.private = keyBuffer.toString() + this.primaryKeyPair.private = keyBuffer.toString(); } /** @@ -226,15 +223,15 @@ class KeyManager { * @param publicKey Public Key */ loadPublicKey(publicKey: string | Buffer): void { - let keyBuffer: Buffer + let keyBuffer: Buffer; if (typeof publicKey === 'string') { - keyBuffer = this.fileSystem.readFileSync(publicKey) - this.metadata.publicKeyPath = publicKey - this.writeMetadata() + keyBuffer = this.fileSystem.readFileSync(publicKey); + this.metadata.publicKeyPath = publicKey; + this.writeMetadata(); } else { - keyBuffer = publicKey + keyBuffer = publicKey; } - this.primaryKeyPair.public = keyBuffer.toString() + this.primaryKeyPair.public = keyBuffer.toString(); } /** @@ -242,18 +239,18 @@ class KeyManager { * @param passphrase Passphrase to unlock the private key */ async unlockIdentity(passphrase: string): Promise { - const publicKey: string = this.getPublicKey() - const privateKey: string = this.getPrivateKey() + const publicKey: string = this.getPublicKey(); + const privateKey: string = this.getPrivateKey(); - const identity = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({ armored: publicKey }) + const identity = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({ armored: publicKey }); - await promisify(identity.merge_pgp_private.bind(identity))({ armored: privateKey }) + await promisify(identity.merge_pgp_private.bind(identity))({ armored: privateKey }); if (identity.is_pgp_locked.bind(identity)()) { - await promisify(identity.unlock_pgp.bind(identity))({ passphrase: passphrase }) + await promisify(identity.unlock_pgp.bind(identity))({ passphrase: passphrase }); } - this.primaryIdentity = identity + this.primaryIdentity = identity; } /** @@ -261,9 +258,9 @@ class KeyManager { * @param path Destination path */ exportPrivateKey(path: string): void { - this.fileSystem.writeFileSync(path, this.primaryKeyPair.private) - this.metadata.privateKeyPath = path - this.writeMetadata() + this.fileSystem.writeFileSync(path, this.primaryKeyPair.private); + this.metadata.privateKeyPath = path; + this.writeMetadata(); } /** @@ -271,9 +268,9 @@ class KeyManager { * @param path Destination path */ exportPublicKey(path: string): void { - this.fileSystem.writeFileSync(path, this.primaryKeyPair.public) - this.metadata.publicKeyPath = path - this.writeMetadata() + this.fileSystem.writeFileSync(path, this.primaryKeyPair.public); + this.metadata.publicKeyPath = path; + this.writeMetadata(); } /** @@ -282,10 +279,10 @@ class KeyManager { * @param passphrase Passphrase to derive the key from */ generateKeySync(name: string, passphrase: string): Buffer { - const salt = crypto.randomBytes(32) - this.derivedKeys[name] = crypto.pbkdf2Sync(passphrase, salt, 10000, 256 / 8, 'sha256') + const salt = crypto.randomBytes(32); + this.derivedKeys[name] = crypto.pbkdf2Sync(passphrase, salt, 10000, 256 / 8, 'sha256'); - return this.derivedKeys[name] + return this.derivedKeys[name]; } /** @@ -294,10 +291,10 @@ class KeyManager { * @param passphrase Passphrase to derive the key from */ async generateKey(name: string, passphrase: string): Promise { - const salt = crypto.randomBytes(32) - this.derivedKeys[name] = await promisify(crypto.pbkdf2)(passphrase, salt, 10000, 256 / 8, 'sha256') + const salt = crypto.randomBytes(32); + this.derivedKeys[name] = await promisify(crypto.pbkdf2)(passphrase, salt, 10000, 256 / 8, 'sha256'); - return this.derivedKeys[name] + return this.derivedKeys[name]; } /** @@ -307,9 +304,9 @@ class KeyManager { */ importKeySync(name: string, key: string | Buffer): void { if (typeof key === 'string') { - this.derivedKeys[name] = this.fileSystem.readFileSync(key) + this.derivedKeys[name] = this.fileSystem.readFileSync(key); } else { - this.derivedKeys[name] = key + this.derivedKeys[name] = key; } } @@ -320,9 +317,9 @@ class KeyManager { */ async importKey(name: string, key: string | Buffer): Promise { if (typeof key === 'string') { - this.derivedKeys[name] = await this.fileSystem.promises.readFile(key) + this.derivedKeys[name] = await this.fileSystem.promises.readFile(key); } else { - this.derivedKeys[name] = key + this.derivedKeys[name] = key; } } @@ -334,12 +331,12 @@ class KeyManager { */ exportKeySync(name: string, dest: string, createPath?: boolean): void { if (!this.derivedKeys.has(name)) { - throw Error(`There is no key loaded for name: ${name}`) + throw Error(`There is no key loaded for name: ${name}`); } if (createPath) { - this.fileSystem.mkdirSync(path.dirname(dest), { recursive: true }) + this.fileSystem.mkdirSync(path.dirname(dest), { recursive: true }); } - this.fileSystem.writeFileSync(dest, this.derivedKeys[name]) + this.fileSystem.writeFileSync(dest, this.derivedKeys[name]); } /** @@ -350,12 +347,12 @@ class KeyManager { */ async exportKey(name: string, dest: string, createPath?: boolean): Promise { if (!this.derivedKeys.has(name)) { - throw Error(`There is no key loaded for name: ${name}`) + throw Error(`There is no key loaded for name: ${name}`); } if (createPath) { - await this.fileSystem.promises.mkdir(path.dirname(dest), { recursive: true }) + await this.fileSystem.promises.mkdir(path.dirname(dest), { recursive: true }); } - await this.fileSystem.promises.writeFile(dest, this.derivedKeys[name]) + await this.fileSystem.promises.writeFile(dest, this.derivedKeys[name]); } /** @@ -363,8 +360,8 @@ class KeyManager { * @param publicKey Buffer containing the public key */ async getIdentityFromPublicKey(publicKey: Buffer): Promise { - const identity = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({ armored: publicKey }) - return identity + const identity = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({ armored: publicKey }); + return identity; } /** @@ -372,11 +369,11 @@ class KeyManager { * @param publicKey Buffer containing the public key */ async getIdentityFromPrivateKey(privateKey: Buffer, passphrase: string): Promise { - const identity = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({ armored: privateKey }) + const identity = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({ armored: privateKey }); if (identity.is_pgp_locked()) { - await promisify(identity.unlock_pgp)({ passphrase: passphrase }) + await promisify(identity.unlock_pgp)({ passphrase: passphrase }); } - return identity + return identity; } /** @@ -386,31 +383,31 @@ class KeyManager { * @param keyPassphrase Required if privateKey is provided. */ async signData(data: Buffer | string, privateKey?: Buffer, keyPassphrase?: string): Promise { - let resolvedIdentity: Object + let resolvedIdentity: Object; if (privateKey) { if (!keyPassphrase) { - throw new Error('passphrase for private key was not provided') + throw Error('passphrase for private key was not provided'); } - resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase!) + resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase!); } else if (this.primaryIdentity) { - resolvedIdentity = this.primaryIdentity + resolvedIdentity = this.primaryIdentity; } else { - throw new Error('key pair is not loaded') + throw Error('key pair is not loaded'); } if (this.useWebWorkers && this.workerPool) { const workerResponse = await this.workerPool.queue(async (workerCrypto) => { return await workerCrypto.signData(data, resolvedIdentity); }); - return workerResponse + return workerResponse; } else { const params = { msg: data.toString(), - sign_with: resolvedIdentity - } - const result_string = await promisify(kbpgp.box)(params) + sign_with: resolvedIdentity, + }; + const result_string = await promisify(kbpgp.box)(params); - return Buffer.from(result_string) + return Buffer.from(result_string); } } @@ -422,23 +419,25 @@ class KeyManager { */ async signFile(filePath: string, privateKey?: string | Buffer, keyPassphrase?: string): Promise { // Get key if provided - let keyBuffer: Buffer + let keyBuffer: Buffer; if (privateKey) { - if (typeof privateKey === 'string') { // Path + if (typeof privateKey === 'string') { + // Path // Read in from fs - keyBuffer = this.fileSystem.readFileSync(privateKey) - } else { // Buffer - keyBuffer = privateKey + keyBuffer = this.fileSystem.readFileSync(privateKey); + } else { + // Buffer + keyBuffer = privateKey; } } // Read file into buffer - const buffer = this.fileSystem.readFileSync(filePath) + const buffer = this.fileSystem.readFileSync(filePath); // Sign the buffer - const signedBuffer = await this.signData(buffer, keyBuffer!, keyPassphrase) + const signedBuffer = await this.signData(buffer, keyBuffer!, keyPassphrase); // Write buffer to signed file - const signedPath = `${filePath}.sig` - this.fileSystem.writeFileSync(signedPath, signedBuffer) - return signedPath + const signedPath = `${filePath}.sig`; + this.fileSystem.writeFileSync(signedPath, signedBuffer); + return signedPath; } /** @@ -448,46 +447,46 @@ class KeyManager { * @param publicKey Buffer containing the key to verify with. Defaults to primary public key if no key is given. */ async verifyData(data: Buffer | string, signature: Buffer, publicKey?: Buffer): Promise { - const ring = new kbpgp.keyring.KeyRing; - let resolvedIdentity: Object + const ring = new kbpgp.keyring.KeyRing(); + let resolvedIdentity: Object; if (publicKey) { - resolvedIdentity = await this.getIdentityFromPublicKey(publicKey) + resolvedIdentity = await this.getIdentityFromPublicKey(publicKey); } else if (this.primaryIdentity) { - resolvedIdentity = this.primaryIdentity + resolvedIdentity = this.primaryIdentity; } else { - throw new Error('key pair is not loaded') + throw Error('key pair is not loaded'); } - ring.add_key_manager(resolvedIdentity) + ring.add_key_manager(resolvedIdentity); if (this.useWebWorkers && this.workerPool) { const workerResponse = await this.workerPool.queue(async (workerCrypto) => { return await workerCrypto.verifyData(data, signature, resolvedIdentity); }); - return workerResponse + return workerResponse; } else { const params = { armored: signature, data: data, - keyfetch: ring - } - const literals = await promisify(kbpgp.unbox)(params) + keyfetch: ring, + }; + const literals = await promisify(kbpgp.unbox)(params); // Get the identity that signed the data if any - let dataSigner = literals[0].get_data_signer() + let dataSigner = literals[0].get_data_signer(); // Retrieve the key manager associated with that data signer - let keyManager: any + let keyManager: any; if (dataSigner) { - keyManager = dataSigner.get_key_manager() + keyManager = dataSigner.get_key_manager(); } // If we know the pgp finger print then we say the data is verified. // Otherwise it is unverified. if (keyManager) { if (keyManager.get_pgp_fingerprint()) { - return true + return true; } else { - return false + return false; } } else { - return false + return false; } } } @@ -500,20 +499,22 @@ class KeyManager { */ async verifyFile(filePath: string, signaturePath: string, publicKey?: string | Buffer): Promise { // Get key if provided - let keyBuffer: Buffer + let keyBuffer: Buffer; if (publicKey) { - if (typeof publicKey === 'string') { // Path + if (typeof publicKey === 'string') { + // Path // Read in from fs - keyBuffer = this.fileSystem.readFileSync(publicKey) - } else { // Buffer - keyBuffer = publicKey + keyBuffer = this.fileSystem.readFileSync(publicKey); + } else { + // Buffer + keyBuffer = publicKey; } } // Read in file buffer and signature - const fileBuffer = this.fileSystem.readFileSync(filePath) - const signatureBuffer = this.fileSystem.readFileSync(signaturePath) - const isVerified = await this.verifyData(fileBuffer, signatureBuffer, keyBuffer!) - return isVerified + const fileBuffer = this.fileSystem.readFileSync(filePath); + const signatureBuffer = this.fileSystem.readFileSync(signaturePath); + const isVerified = await this.verifyData(fileBuffer, signatureBuffer, keyBuffer!); + return isVerified; } /** @@ -522,27 +523,27 @@ class KeyManager { * @param publicKey The key to encrypt for */ async encryptData(data: Buffer, publicKey?: Buffer): Promise { - let resolvedIdentity: Object + let resolvedIdentity: Object; if (publicKey) { - resolvedIdentity = await this.getIdentityFromPublicKey(publicKey) + resolvedIdentity = await this.getIdentityFromPublicKey(publicKey); } else if (this.primaryIdentity) { - resolvedIdentity = this.primaryIdentity + resolvedIdentity = this.primaryIdentity; } else { - throw new Error(`Identity could not be resolved for encrypting`) + throw Error(`Identity could not be resolved for encrypting`); } if (this.useWebWorkers && this.workerPool) { const workerResponse = await this.workerPool.queue(async (workerCrypto) => { return await workerCrypto.encryptData(data, resolvedIdentity); }); - return workerResponse + return workerResponse; } else { const params = { msg: data, - encrypt_for: resolvedIdentity - } - const result_string = await promisify(kbpgp.box)(params) - return result_string + encrypt_for: resolvedIdentity, + }; + const result_string = await promisify(kbpgp.box)(params); + return result_string; } } @@ -553,34 +554,34 @@ class KeyManager { * @param keyPassphrase Required if privateKey is provided. */ async decryptData(data: Buffer, privateKey?: Buffer, keyPassphrase?: string): Promise { - var ring = new kbpgp.keyring.KeyRing; - let resolvedIdentity: Object + var ring = new kbpgp.keyring.KeyRing(); + let resolvedIdentity: Object; if (privateKey) { if (keyPassphrase) { - resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase) + resolvedIdentity = await this.getIdentityFromPrivateKey(privateKey, keyPassphrase); } else { - throw new Error('A key passphrase must be supplied if a privateKey is specified') + throw Error('A key passphrase must be supplied if a privateKey is specified'); } } else if (this.primaryIdentity) { - resolvedIdentity = this.primaryIdentity + resolvedIdentity = this.primaryIdentity; } else { - throw Error('no identity available for decrypting') + throw Error('no identity available for decrypting'); } if (this.useWebWorkers && this.workerPool) { const workerResponse = await this.workerPool.queue(async (workerCrypto) => { return await workerCrypto.decryptData(data, resolvedIdentity); }); - return workerResponse + return workerResponse; } else { - ring.add_key_manager(resolvedIdentity) + ring.add_key_manager(resolvedIdentity); const params = { armored: data.toString(), - keyfetch: ring - } - const literals = await promisify(kbpgp.unbox)(params) - const decryptedData = Buffer.from(literals[0].toString()) - return decryptedData + keyfetch: ring, + }; + const literals = await promisify(kbpgp.unbox)(params); + const decryptedData = Buffer.from(literals[0].toString()); + return decryptedData; } } @@ -588,39 +589,39 @@ class KeyManager { // PKI // ///////// public get PKIInfo(): PKInfo { - return this.pkiInfo + return this.pkiInfo; } loadPKIInfo(key?: Buffer | null, cert?: Buffer | null, caCert?: Buffer | null, writeToFile: boolean = false) { if (key) { - this.pkiInfo.key = key + this.pkiInfo.key = key; } if (cert) { - this.pkiInfo.cert = cert + this.pkiInfo.cert = cert; } if (caCert) { - this.pkiInfo.caCert = caCert + this.pkiInfo.caCert = caCert; } if (writeToFile) { // Store in the metadata path folder - const storagePath = path.dirname(this.metadataPath) + const storagePath = path.dirname(this.metadataPath); if (key) { - this.metadata.pkiKeyPath = path.join(storagePath, 'pki_private_key') - fs.writeFileSync(this.metadata.pkiKeyPath, key) + this.metadata.pkiKeyPath = path.join(storagePath, 'pki_private_key'); + fs.writeFileSync(this.metadata.pkiKeyPath, key); } if (cert) { - this.metadata.pkiCertPath = path.join(storagePath, 'pki_cert') - fs.writeFileSync(this.metadata.pkiCertPath, cert) + this.metadata.pkiCertPath = path.join(storagePath, 'pki_cert'); + fs.writeFileSync(this.metadata.pkiCertPath, cert); } if (caCert) { - this.metadata.caCertPath = path.join(storagePath, 'ca_cert') - fs.writeFileSync(this.metadata.caCertPath, caCert) + this.metadata.caCertPath = path.join(storagePath, 'ca_cert'); + fs.writeFileSync(this.metadata.caCertPath, caCert); } } } @@ -631,7 +632,7 @@ class KeyManager { * @param name The unique name of the desired key */ getKey(name: string): Buffer { - return this.derivedKeys[name] + return this.derivedKeys[name]; } /** @@ -640,23 +641,23 @@ class KeyManager { */ hasKey(name: string): boolean { if (this.derivedKeys[name]) { - return true + return true; } - return false + return false; } private writeMetadata(): void { - const metadata = JSON.stringify(this.metadata) - this.fileSystem.writeFileSync(this.metadataPath, metadata) + const metadata = JSON.stringify(this.metadata); + this.fileSystem.writeFileSync(this.metadataPath, metadata); } private loadMetadata(): void { // Check if file exists if (this.fileSystem.existsSync(this.metadataPath)) { - const metadata = this.fileSystem.readFileSync(this.metadataPath).toString() - this.metadata = JSON.parse(metadata) + const metadata = this.fileSystem.readFileSync(this.metadataPath).toString(); + this.metadata = JSON.parse(metadata); } } } -export default KeyManager -export { KeyPair } +export default KeyManager; +export { KeyPair }; diff --git a/src/lib/keys/KeyManagerWorker.ts b/src/lib/keys/KeyManagerWorker.ts index 9a661e9ba6..7998bdbeb5 100644 --- a/src/lib/keys/KeyManagerWorker.ts +++ b/src/lib/keys/KeyManagerWorker.ts @@ -1,4 +1,4 @@ -import kbpgp from 'kbpgp' +import kbpgp from 'kbpgp'; import { promisify } from 'util'; import { expose } from 'threads/worker'; @@ -11,10 +11,10 @@ const keyManagerWorker = { async signData(data: Buffer | string, identity: any): Promise { const params = { msg: data, - sign_with: identity - } - const result_string = await promisify(kbpgp)(params) - return Buffer.from(result_string) + sign_with: identity, + }; + const result_string = await promisify(kbpgp)(params); + return Buffer.from(result_string); }, /** * Verifies the given data with the provided identity @@ -23,32 +23,32 @@ const keyManagerWorker = { * @param identity Identity with which to verify with. */ async verifyData(data: Buffer | string, signature: Buffer, identity: any): Promise { - const ring = new kbpgp.keyring.KeyRing; + const ring = new kbpgp.keyring.KeyRing(); - ring.add_key_manager(identity) + ring.add_key_manager(identity); const params = { armored: signature, data: data, - keyfetch: ring - } - const literals = await promisify(kbpgp.unbox)(params) + keyfetch: ring, + }; + const literals = await promisify(kbpgp.unbox)(params); // Get the identity that signed the data if any - const dataSigner = literals[0].get_data_signer() + const dataSigner = literals[0].get_data_signer(); // Retrieve the key manager associated with that data signer - let keyManager: any + let keyManager: any; if (dataSigner) { - keyManager = dataSigner.get_key_manager() + keyManager = dataSigner.get_key_manager(); } // If we know the pgp finger print then we say the data is verified. // Otherwise it is unverified. if (keyManager) { if (keyManager.get_pgp_fingerprint()) { - return true + return true; } else { - return false + return false; } } else { - return false + return false; } }, /** @@ -59,10 +59,10 @@ const keyManagerWorker = { async encryptData(data: Buffer, identity: any): Promise { const params = { msg: data, - encrypt_for: identity - } - const result_string: string = await promisify(kbpgp.box)(params) - return result_string + encrypt_for: identity, + }; + const result_string: string = await promisify(kbpgp.box)(params); + return result_string; }, /** * Decrypts the given data with the provided identity @@ -70,17 +70,17 @@ const keyManagerWorker = { * @param identity Identity to decrypt with */ async decryptData(data: Buffer, identity: any): Promise { - var ring = new kbpgp.keyring.KeyRing; + var ring = new kbpgp.keyring.KeyRing(); - ring.add_key_manager(identity) + ring.add_key_manager(identity); const params = { armored: data.toString(), - keyfetch: ring - } - const literals = await promisify(kbpgp.unbox)(params) - const decryptedData = Buffer.from(literals[0].toString()) - return decryptedData - } + keyfetch: ring, + }; + const literals = await promisify(kbpgp.unbox)(params); + const decryptedData = Buffer.from(literals[0].toString()); + return decryptedData; + }, }; export type KeyManagerWorker = typeof keyManagerWorker; diff --git a/src/lib/keys/pki/PublicKeyInfrastructure.ts b/src/lib/keys/pki/PublicKeyInfrastructure.ts index c7731423a0..eccd093fd1 100644 --- a/src/lib/keys/pki/PublicKeyInfrastructure.ts +++ b/src/lib/keys/pki/PublicKeyInfrastructure.ts @@ -1,13 +1,13 @@ -import forge, { pki } from 'node-forge' +import forge, { pki } from 'node-forge'; /** * This class manages X.509 certificates for secure and authenticated communication between peers. */ class PublicKeyInfrastructure { // Cert defaults - static N_BITS: number = 2048 - static COMMON_NAME: string = 'localhost' - static ORGANIZATION_NAME: string = 'MatrixAI' + static N_BITS: number = 2048; + static COMMON_NAME: string = 'localhost'; + static ORGANIZATION_NAME: string = 'MatrixAI'; /** * Creates an X.509 certificate for transport layer security @@ -18,7 +18,7 @@ class PublicKeyInfrastructure { nbits: number = PublicKeyInfrastructure.N_BITS, commonName: string = PublicKeyInfrastructure.COMMON_NAME, organizationName: string = PublicKeyInfrastructure.ORGANIZATION_NAME, - sign?: (cert: pki.Certificate) => pki.Certificate + sign?: (cert: pki.Certificate) => pki.Certificate, ) { const pki = forge.pki; @@ -36,68 +36,75 @@ class PublicKeyInfrastructure { const attrs = [ { name: 'commonName', - value: commonName + value: commonName, }, { name: 'organizationName', - value: organizationName - } + value: organizationName, + }, ]; cert.setSubject(attrs); // alternatively set subject from a csr //cert.setSubject(csr.subject.attributes); cert.setIssuer(attrs); - cert.setExtensions([{ - name: 'basicConstraints', - cA: true - }, { - name: 'keyUsage', - keyCertSign: true, - digitalSignature: true, - nonRepudiation: true, - keyEncipherment: true, - dataEncipherment: true - }, { - name: 'extKeyUsage', - serverAuth: true, - clientAuth: true, - codeSigning: true, - emailProtection: true, - timeStamping: true - }, { - name: 'nsCertType', - client: true, - server: true, - email: true, - objsign: true, - sslCA: true, - emailCA: true, - objCA: true - }, { - name: 'subjectAltName', - altNames: { - type: 7, // IP - ip: '127.0.0.1' - } - }, { - name: 'subjectKeyIdentifier' - }]); + cert.setExtensions([ + { + name: 'basicConstraints', + cA: true, + }, + { + name: 'keyUsage', + keyCertSign: true, + digitalSignature: true, + nonRepudiation: true, + keyEncipherment: true, + dataEncipherment: true, + }, + { + name: 'extKeyUsage', + serverAuth: true, + clientAuth: true, + codeSigning: true, + emailProtection: true, + timeStamping: true, + }, + { + name: 'nsCertType', + client: true, + server: true, + email: true, + objsign: true, + sslCA: true, + emailCA: true, + objCA: true, + }, + { + name: 'subjectAltName', + altNames: { + type: 7, // IP + ip: '127.0.0.1', + }, + }, + { + name: 'subjectKeyIdentifier', + }, + ]); // Self-sign or sign with provided key if (sign) { - cert = sign(cert) + cert = sign(cert); } else { cert.sign(keys.privateKey); } // convert a Forge certificate to PEM - const keyPem = Buffer.from(pki.privateKeyToPem(keys.privateKey)) - const certPem = Buffer.from(pki.certificateToPem(cert)) + const keyPem = Buffer.from(pki.privateKeyToPem(keys.privateKey)); + const certPem = Buffer.from(pki.certificateToPem(cert)); return { keyPem, - certPem - } + certPem, + }; } } -export default PublicKeyInfrastructure +export default PublicKeyInfrastructure; diff --git a/src/lib/peers/MulticastBroadcaster.ts b/src/lib/peers/MulticastBroadcaster.ts index a6e74a4eb4..c1fd12a732 100644 --- a/src/lib/peers/MulticastBroadcaster.ts +++ b/src/lib/peers/MulticastBroadcaster.ts @@ -1,10 +1,10 @@ -import dgram from 'dgram' -import crypto from 'crypto' -import PeerInfo from './PeerInfo' -import { EventEmitter } from 'events' -import KeyManager from '../keys/KeyManager' +import dgram from 'dgram'; +import crypto from 'crypto'; +import PeerInfo from './PeerInfo'; +import { EventEmitter } from 'events'; +import KeyManager from '../keys/KeyManager'; import { peer } from '../../../proto/js/Peer.js'; -const { HandshakeMessage, PeerInfoMessage } = peer +const { HandshakeMessage, PeerInfoMessage } = peer; // This module is based heavily on libp2p's mDNS module: // https://github.com/libp2p/js-libp2p-mdns @@ -19,54 +19,53 @@ const { HandshakeMessage, PeerInfoMessage } = peer // """ const UDP_MULTICAST_PORT = parseInt(process.env.UDP_MULTICAST_PORT ?? '5353'); -const UDP_MULTICAST_ADDR = process.env.UDP_MULTICAST_ADDR ?? "224.0.0.251"; +const UDP_MULTICAST_ADDR = process.env.UDP_MULTICAST_ADDR ?? '224.0.0.251'; type PeerMessage = { - encryptedLocalPubKey: Buffer - encryptedPeerPubKey: Buffer - rawRandomMessage: Buffer - encryptedRandomMessage: Buffer -} + encryptedLocalPubKey: Buffer; + encryptedPeerPubKey: Buffer; + rawRandomMessage: Buffer; + encryptedRandomMessage: Buffer; +}; class MulticastBroadcaster extends EventEmitter { - addPeer: (peerInfo: PeerInfo) => void - localPeerInfo: PeerInfo - keyManager: KeyManager + addPeer: (peerInfo: PeerInfo) => void; + localPeerInfo: PeerInfo; + keyManager: KeyManager; - socket: dgram.Socket + socket: dgram.Socket; - interval: number - queryInterval: NodeJS.Timeout | null - peerPubKeyMessages: Map = new Map() - constructor( - addPeer: (peerInfo: PeerInfo) => void, - localPeerInfo: PeerInfo, - keyManager: KeyManager - ) { - super() + interval: number; + queryInterval: NodeJS.Timeout | null; + peerPubKeyMessages: Map = new Map(); + constructor(addPeer: (peerInfo: PeerInfo) => void, localPeerInfo: PeerInfo, keyManager: KeyManager) { + super(); - this.addPeer = addPeer - this.localPeerInfo = localPeerInfo - this.keyManager = keyManager + this.addPeer = addPeer; + this.localPeerInfo = localPeerInfo; + this.keyManager = keyManager; - this.interval = (1e3) - this.queryInterval = null + this.interval = 1e3; + this.queryInterval = null; // Create socket - this.socket = dgram.createSocket({ type: "udp4", reuseAddr: true }) - this.socket.bind(UDP_MULTICAST_PORT) + this.socket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); + this.socket.bind(UDP_MULTICAST_PORT); // Set up listener - this.socket.on("listening", (() => { - this.socket.addMembership(UDP_MULTICAST_ADDR); - const address = this.socket.address(); - }).bind(this)); + this.socket.on( + 'listening', + (() => { + this.socket.addMembership(UDP_MULTICAST_ADDR); + const address = this.socket.address(); + }).bind(this), + ); // Handle messages - this.socket.on("message", this.handleHandshakeMessages.bind(this)); + this.socket.on('message', this.handleHandshakeMessages.bind(this)); // Start the query process - this.queryInterval = this.queryLAN() + this.queryInterval = this.queryLAN(); } /** @@ -74,99 +73,108 @@ class MulticastBroadcaster extends EventEmitter { * @param publicKey Public key of the desired peer */ async requestPeerContact(publicKey: string) { - const pubKeyBuf = Buffer.from(publicKey) - const randomMessage = crypto.randomBytes(16) + const pubKeyBuf = Buffer.from(publicKey); + const randomMessage = crypto.randomBytes(16); // Encrypt message - const encryptedPeerPubKey = await this.keyManager.encryptData(pubKeyBuf, pubKeyBuf) - const encryptedRandomMessage = await this.keyManager.encryptData(randomMessage, pubKeyBuf) - const encryptedLocalPubKey = await this.keyManager.encryptData(Buffer.from(this.keyManager.getPublicKey()), pubKeyBuf) + const encryptedPeerPubKey = await this.keyManager.encryptData(pubKeyBuf, pubKeyBuf); + const encryptedRandomMessage = await this.keyManager.encryptData(randomMessage, pubKeyBuf); + const encryptedLocalPubKey = await this.keyManager.encryptData( + Buffer.from(this.keyManager.getPublicKey()), + pubKeyBuf, + ); // Add to peer messages to be sent over multicast this.peerPubKeyMessages.set(publicKey, { encryptedLocalPubKey: Buffer.from(encryptedLocalPubKey), encryptedPeerPubKey: Buffer.from(encryptedPeerPubKey), rawRandomMessage: randomMessage, - encryptedRandomMessage: Buffer.from(encryptedRandomMessage) - }) + encryptedRandomMessage: Buffer.from(encryptedRandomMessage), + }); } // ==== Helper methods ==== // private queryLAN() { const query = () => { for (const pubKey of this.peerPubKeyMessages.keys()) { - const peerMessage = this.peerPubKeyMessages.get(pubKey) + const peerMessage = this.peerPubKeyMessages.get(pubKey); if (peerMessage) { const handshakeMessage = HandshakeMessage.encode({ targetPubKey: peerMessage.encryptedPeerPubKey, requestingPubKey: peerMessage.encryptedLocalPubKey, - message: peerMessage.encryptedRandomMessage - }).finish() + message: peerMessage.encryptedRandomMessage, + }).finish(); this.socket.send(handshakeMessage, 0, handshakeMessage.length, UDP_MULTICAST_PORT, UDP_MULTICAST_ADDR); } - } - } + }; // Immediately start a query, then do it every interval. - query() - return setInterval(query, this.interval) + query(); + return setInterval(query, this.interval); } private async handleHandshakeMessages(request: any, rinfo: any) { try { - const { message, requestingPubKey, responsePeerInfo, targetPubKey } = HandshakeMessage.decode(request) + const { message, requestingPubKey, responsePeerInfo, targetPubKey } = HandshakeMessage.decode(request); // Try to decrypt message and pubKey - const decryptedMessage = await this.keyManager.decryptData(Buffer.from(message)) - const decryptedTargetPubKey = await this.keyManager.decryptData(Buffer.from(targetPubKey)) - const decryptedRequestingPubKey = await this.keyManager.decryptData(Buffer.from(requestingPubKey)) + const decryptedMessage = await this.keyManager.decryptData(Buffer.from(message)); + const decryptedTargetPubKey = await this.keyManager.decryptData(Buffer.from(targetPubKey)); + const decryptedRequestingPubKey = await this.keyManager.decryptData(Buffer.from(requestingPubKey)); - const myPubKey = this.keyManager.getPublicKey() + const myPubKey = this.keyManager.getPublicKey(); - if (decryptedRequestingPubKey.toString() == myPubKey) { // Response + if (decryptedRequestingPubKey.toString() == myPubKey) { + // Response // Make sure decrypted bytes equal raw bytes in memory - const originalMessage = this.peerPubKeyMessages.get(decryptedTargetPubKey.toString())?.rawRandomMessage + const originalMessage = this.peerPubKeyMessages.get(decryptedTargetPubKey.toString())?.rawRandomMessage; - if (decryptedMessage.toString() == originalMessage?.toString()) { // Validated! + if (decryptedMessage.toString() == originalMessage?.toString()) { + // Validated! // Add peer info to peerStore - const { addresses, connectedAddr, pubKey } = PeerInfoMessage.decode(responsePeerInfo) - const newPeerInfo = new PeerInfo(pubKey, addresses, connectedAddr) + const { addresses, connectedAddr, pubKey } = PeerInfoMessage.decode(responsePeerInfo); + const newPeerInfo = new PeerInfo(pubKey, addresses, connectedAddr); if (newPeerInfo) { - this.addPeer(newPeerInfo) + this.addPeer(newPeerInfo); // Remove peerId from requested messages - const pubKey = newPeerInfo.publicKey - this.peerPubKeyMessages.delete(pubKey) + const pubKey = newPeerInfo.publicKey; + this.peerPubKeyMessages.delete(pubKey); console.log(`New peer added to the store`); - this.emit('found', newPeerInfo) + this.emit('found', newPeerInfo); } else { - this.emit('error', "I got a validated response. But no peerInfo"); + this.emit('error', 'I got a validated response. But no peerInfo'); } } - } else { // Requests on target node + } else { + // Requests on target node // Try decrypting message // Re-encrypt the data and send it on its way - const encryptedTargetPubKey = await this.keyManager.encryptData(Buffer.from(myPubKey), decryptedRequestingPubKey) - const encryptedMessage = await this.keyManager.encryptData(decryptedMessage, decryptedRequestingPubKey) - const encryptedPubKey = await this.keyManager.encryptData(decryptedRequestingPubKey, decryptedRequestingPubKey) + const encryptedTargetPubKey = await this.keyManager.encryptData( + Buffer.from(myPubKey), + decryptedRequestingPubKey, + ); + const encryptedMessage = await this.keyManager.encryptData(decryptedMessage, decryptedRequestingPubKey); + const encryptedPubKey = await this.keyManager.encryptData(decryptedRequestingPubKey, decryptedRequestingPubKey); const encodedLocalPeerInfo = PeerInfoMessage.encode({ - addresses:this.localPeerInfo.AdressStringList, + addresses: this.localPeerInfo.AdressStringList, connectedAddr: this.localPeerInfo.connectedAddr?.toString(), - pubKey: this.localPeerInfo.publicKey - }).finish() + pubKey: this.localPeerInfo.publicKey, + }).finish(); const handshakeMessage = HandshakeMessage.encode({ targetPubKey: Buffer.from(encryptedTargetPubKey), requestingPubKey: Buffer.from(encryptedPubKey), message: Buffer.from(encryptedMessage), - responsePeerInfo: encodedLocalPeerInfo - }).finish() + responsePeerInfo: encodedLocalPeerInfo, + }).finish(); this.socket.send(handshakeMessage, 0, handshakeMessage.length, UDP_MULTICAST_PORT, UDP_MULTICAST_ADDR); } - } catch (err) { // Couldn't decode message + } catch (err) { + // Couldn't decode message // We don't want the multicast discovery to error on every message it coudln't decode! } } } -export default MulticastBroadcaster +export default MulticastBroadcaster; diff --git a/src/lib/peers/PeerInfo.ts b/src/lib/peers/PeerInfo.ts index 5cc1f6a7ba..0033d2e69a 100644 --- a/src/lib/peers/PeerInfo.ts +++ b/src/lib/peers/PeerInfo.ts @@ -1,14 +1,11 @@ import { AddressInfo } from 'net'; class Address { - ip: string - port: string - constructor( - ip: string, - port: string - ) { - this.ip = ip - this.port = port + ip: string; + port: string; + constructor(ip: string, port: string) { + this.ip = ip; + this.port = port; } /** @@ -16,11 +13,11 @@ class Address { * @param addressString Address string in the format of `${this.ip}:${this.port}` */ static parse(addressString: string): Address { - const components = addressString.split(':') - const ip = components[0] - const port = components[1] + const components = addressString.split(':'); + const ip = components[0]; + const port = components[1]; - return new Address(ip, port) + return new Address(ip, port); } /** @@ -28,36 +25,34 @@ class Address { * @param addressInfo AddressInfo of desired address */ static fromAddressInfo(addressInfo: AddressInfo) { - const ip = (addressInfo.address == '::') ? 'localhost' : addressInfo.address - return new Address(ip, addressInfo.port.toString()) + const ip = addressInfo.address == '::' ? 'localhost' : addressInfo.address; + return new Address(ip, addressInfo.port.toString()); } /** * Convert address into string of format `${this.ip}:${this.port}` */ toString() { - return `${this.ip}:${this.port}` + return `${this.ip}:${this.port}`; } } -Address.prototype.toString = function() { - return `${this.ip}:${this.port}` -} +Address.prototype.toString = function () { + return `${this.ip}:${this.port}`; +}; class PeerInfo { - publicKey: string - addresses: Set
              - connectedAddr?: Address - constructor( - pubKey: string, - addresses: string[] = [], - connectedAddr?: string - ) { - this.publicKey = pubKey - this.addresses = new Set(addresses.map((addr) => { - return Address.parse(addr) - })) - this.connectedAddr = (connectedAddr) ? Address.parse(connectedAddr) : undefined + publicKey: string; + addresses: Set
              ; + connectedAddr?: Address; + constructor(pubKey: string, addresses: string[] = [], connectedAddr?: string) { + this.publicKey = pubKey; + this.addresses = new Set( + addresses.map((addr) => { + return Address.parse(addr); + }), + ); + this.connectedAddr = connectedAddr ? Address.parse(connectedAddr) : undefined; } /** @@ -66,27 +61,25 @@ class PeerInfo { */ connect(address: Address) { if (!this.addresses.has(address)) { - this.addresses.add(address) + this.addresses.add(address); } - this.connectedAddr = address + this.connectedAddr = address; } /** * Clears the main server address for the peer */ disconnect() { - this.connectedAddr = undefined + this.connectedAddr = undefined; } - - public get AdressStringList() : string[] { + public get AdressStringList(): string[] { return Array.from(this.addresses.values()).map((addr) => { - return addr.toString() - }) + return addr.toString(); + }); } - } -export default PeerInfo -export { Address } +export default PeerInfo; +export { Address }; diff --git a/src/lib/peers/PeerManager.ts b/src/lib/peers/PeerManager.ts index d35ffa7a3c..c2a62b3b7d 100644 --- a/src/lib/peers/PeerManager.ts +++ b/src/lib/peers/PeerManager.ts @@ -1,7 +1,7 @@ import os from 'os'; import fs from 'fs'; import path from 'path'; -import * as grpc from '@grpc/grpc-js' +import * as grpc from '@grpc/grpc-js'; import GitClient from '../git/GitClient'; import GitBackend from '../git/GitBackend'; import KeyManager from '../keys/KeyManager'; @@ -15,49 +15,49 @@ import { InfoRequest, PackRequest, PackReply, InfoReply } from '../../../proto/c interface SocialDiscovery { // Must return a public pgp key - name: string - findUser(handle: string, service: string): Promise + name: string; + findUser(handle: string, service: string): Promise; } const keybaseDiscovery: SocialDiscovery = { name: 'Keybase', findUser: async (handle: string, service: string): Promise => { - const url = `https://keybase.io/_/api/1.0/user/lookup.json?${service}=${handle}` + const url = `https://keybase.io/_/api/1.0/user/lookup.json?${service}=${handle}`; try { - const response = await fetch(url) - const data = await response.json() + const response = await fetch(url); + const data = await response.json(); - const pubKey = data.them[0].public_keys.primary.bundle - return pubKey + const pubKey = data.them[0].public_keys.primary.bundle; + return pubKey; } catch (err) { - throw new Error(`User was not found: ${err.message}`) + throw Error(`User was not found: ${err.message}`); } - } -} + }, +}; type PeerManagerMetadata = { - localPeerInfo: PeerInfo | null -} + localPeerInfo: PeerInfo | null; +}; class PeerManager { - private fileSystem: typeof fs + private fileSystem: typeof fs; - private metadataPath: string - private metadata: PeerManagerMetadata = { localPeerInfo: null } + private metadataPath: string; + private metadata: PeerManagerMetadata = { localPeerInfo: null }; - private localPeerInfo: PeerInfo - private peerStore: Map - private keyManager: KeyManager - multicastBroadcaster: MulticastBroadcaster - private socialDiscoveryServices: SocialDiscovery[] + private localPeerInfo: PeerInfo; + private peerStore: Map; + private keyManager: KeyManager; + multicastBroadcaster: MulticastBroadcaster; + private socialDiscoveryServices: SocialDiscovery[]; // Peer connections - server: grpc.Server - serverStarted: boolean = false - private gitBackend: GitBackend - private credentials: grpc.ServerCredentials - private peerConnections: Map + server: grpc.Server; + serverStarted: boolean = false; + private gitBackend: GitBackend; + private credentials: grpc.ServerCredentials; + private peerConnections: Map; constructor( polykeyPath: string = `${os.homedir()}/.polykey`, @@ -65,99 +65,101 @@ class PeerManager { keyManager: KeyManager, vaultManager: VaultManager, peerInfo?: PeerInfo, - socialDiscoveryServices: SocialDiscovery[] = [] + socialDiscoveryServices: SocialDiscovery[] = [], ) { - this.fileSystem = fileSystem + this.fileSystem = fileSystem; - this.fileSystem.mkdirSync(polykeyPath, { recursive: true }) - this.metadataPath = path.join(polykeyPath, '.peerMetadata') + this.fileSystem.mkdirSync(polykeyPath, { recursive: true }); + this.metadataPath = path.join(polykeyPath, '.peerMetadata'); // Set given variables - this.keyManager = keyManager - this.socialDiscoveryServices = socialDiscoveryServices + this.keyManager = keyManager; + this.socialDiscoveryServices = socialDiscoveryServices; // Load metadata with peer info - this.loadMetadata() + this.loadMetadata(); // Load peer store and local peer info if (peerInfo) { - this.localPeerInfo = peerInfo - this.writeMetadata() + this.localPeerInfo = peerInfo; + this.writeMetadata(); } else if (this.metadata.localPeerInfo) { - this.localPeerInfo = this.metadata.localPeerInfo + this.localPeerInfo = this.metadata.localPeerInfo; } else if (this.keyManager.hasPublicKey()) { - this.localPeerInfo = new PeerInfo(this.keyManager.getPublicKey()) + this.localPeerInfo = new PeerInfo(this.keyManager.getPublicKey()); } - this.peerStore = new Map() + this.peerStore = new Map(); - this.socialDiscoveryServices = [] - this.socialDiscoveryServices.push(keybaseDiscovery) + this.socialDiscoveryServices = []; + this.socialDiscoveryServices.push(keybaseDiscovery); for (const service of socialDiscoveryServices) { - this.socialDiscoveryServices.push(service) + this.socialDiscoveryServices.push(service); } - this.multicastBroadcaster = new MulticastBroadcaster(this.addPeer, this.localPeerInfo, this.keyManager) + this.multicastBroadcaster = new MulticastBroadcaster(this.addPeer, this.localPeerInfo, this.keyManager); - this.peerConnections = new Map() + this.peerConnections = new Map(); ///////////////// // GRPC Server // ///////////////// - this.gitBackend = new GitBackend(polykeyPath, vaultManager) + this.gitBackend = new GitBackend(polykeyPath, vaultManager); this.server = new grpc.Server(); // Add service this.server.addService(GitServerService, { requestInfo: this.requestInfo.bind(this), - requestPack: this.requestPack.bind(this) + requestPack: this.requestPack.bind(this), }); // Create the server credentials. SSL only if ca cert exists - const pkiInfo = this.keyManager.PKIInfo - - // if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) { - // this.credentials = grpc.ServerCredentials.createSsl( - // pkiInfo.caCert, - // [{ - // private_key: pkiInfo.key, - // cert_chain: pkiInfo.cert, - // }], - // true - // ) - // } else { - this.credentials = grpc.ServerCredentials.createInsecure() - // } + const pkiInfo = this.keyManager.PKIInfo; + + if (pkiInfo.caCert && pkiInfo.cert && pkiInfo.key) { + this.credentials = grpc.ServerCredentials.createSsl( + pkiInfo.caCert, + [ + { + private_key: pkiInfo.key, + cert_chain: pkiInfo.cert, + }, + ], + true, + ); + } else { + this.credentials = grpc.ServerCredentials.createInsecure(); + } this.server.bindAsync(`0.0.0.0:${process.env.PK_PORT ?? 0}`, this.credentials, (err, boundPort) => { if (err) { - throw err + throw err; } else { - const address = new Address('localhost', boundPort.toString()) + const address = new Address('localhost', boundPort.toString()); this.server.start(); - this.localPeerInfo.connect(address) - this.serverStarted = true + this.localPeerInfo.connect(address); + this.serverStarted = true; } }); } private async requestInfo(call, callback) { - const infoRequest: InfoRequest = call.request + const infoRequest: InfoRequest = call.request; - const vaultName = infoRequest.getVaultname() + const vaultName = infoRequest.getVaultname(); - const infoReply = new InfoReply() - infoReply.setVaultname(vaultName) - infoReply.setBody(await this.gitBackend.handleInfoRequest(vaultName)) + const infoReply = new InfoReply(); + infoReply.setVaultname(vaultName); + infoReply.setBody(await this.gitBackend.handleInfoRequest(vaultName)); callback(null, infoReply); } - private async requestPack(call, callback) { - const packRequest: PackRequest = call.request - const vaultName = packRequest.getVaultname() - const body = Buffer.from(packRequest.getBody_asB64(), 'base64') + private async requestPack(call, callback) { + const packRequest: PackRequest = call.request; + const vaultName = packRequest.getVaultname(); + const body = Buffer.from(packRequest.getBody_asB64(), 'base64'); - const reply = new PackReply() - reply.setVaultname(vaultName) - reply.setBody(await this.gitBackend.handlePackRequest(vaultName, body)) + const reply = new PackReply(); + reply.setVaultname(vaultName); + reply.setBody(await this.gitBackend.handlePackRequest(vaultName, body)); callback(null, reply); } @@ -168,7 +170,7 @@ class PeerManager { * Get the peer info of the current keynode */ getLocalPeerInfo(): PeerInfo { - return this.localPeerInfo + return this.localPeerInfo; } /** @@ -176,7 +178,7 @@ class PeerManager { * @param adress Address of active server */ connectLocalPeerInfo(address: Address) { - this.localPeerInfo.connect(address) + this.localPeerInfo.connect(address); } /** @@ -184,8 +186,7 @@ class PeerManager { * @param peerInfo Info of the peer to be added */ addPeer(peerInfo: PeerInfo): void { - this.peerStore.set(peerInfo.publicKey, peerInfo) - + this.peerStore.set(peerInfo.publicKey, peerInfo); } /** @@ -193,7 +194,7 @@ class PeerManager { * @param publicKey Public key of the desired peer */ getPeer(publicKey: string): PeerInfo | null { - return this.peerStore.get(publicKey) ?? null + return this.peerStore.get(publicKey) ?? null; } /** @@ -201,7 +202,7 @@ class PeerManager { * @param publicKey Public key of the desired peer */ hasPeer(pubKey: string): boolean { - return this.peerStore.has(pubKey) + return this.peerStore.has(pubKey); } ////////////////////// @@ -213,19 +214,19 @@ class PeerManager { */ async findPubKey(publicKey: string): Promise { return new Promise((resolve, reject) => { - this.multicastBroadcaster.requestPeerContact(publicKey) + this.multicastBroadcaster.requestPeerContact(publicKey); this.multicastBroadcaster.on('found', (peerInfo: PeerInfo) => { if (peerInfo.publicKey == publicKey) { - resolve(peerInfo) + resolve(peerInfo); } - }) + }); this.multicastBroadcaster.on('timeout', (timedOutPubKey: string) => { if (timedOutPubKey == publicKey) { - reject('The broadcaster stopped looking') + reject('The broadcaster stopped looking'); } - }) - }) + }); + }); } /** @@ -234,24 +235,23 @@ class PeerManager { * @param service Service on which to search for the user (e.g. github) */ async findSocialUser(handle: string, service: string): Promise { - const tasks: Promise[] = [] + const tasks: Promise[] = []; for (const socialDiscovery of this.socialDiscoveryServices) { - try { - tasks.push(socialDiscovery.findUser(handle, service)) + tasks.push(socialDiscovery.findUser(handle, service)); } catch (error) { console.log(`Could not find user on this discovery service: ${socialDiscovery.name}`); } } - const pubKeyOrFail = await firstPromiseFulfilled(tasks) + const pubKeyOrFail = await firstPromiseFulfilled(tasks); if (pubKeyOrFail.length > 1) { - throw new Error('Could not find public key from services') + throw Error('Could not find public key from services'); } - const pubKeyFound = pubKeyOrFail[0] - const peerInfo = await this.findPubKey(pubKeyFound) - return peerInfo + const pubKeyFound = pubKeyOrFail[0]; + const peerInfo = await this.findPubKey(pubKeyFound); + return peerInfo; } /////////////////////// @@ -264,53 +264,53 @@ class PeerManager { connectToPeer(peer: string | Address): GitClient { // Throw error if trying to connect to self if (peer == this.localPeerInfo.connectedAddr || peer == this.localPeerInfo.publicKey) { - throw new Error('Cannot connect to self') + throw Error('Cannot connect to self'); } - let address: Address + let address: Address; if (typeof peer == 'string') { - const existingSocket = this.peerConnections.get(peer) + const existingSocket = this.peerConnections.get(peer); if (existingSocket) { - return existingSocket + return existingSocket; } - const peerAddress = this.getPeer(peer)?.connectedAddr + const peerAddress = this.getPeer(peer)?.connectedAddr; if (peerAddress) { - address = peerAddress + address = peerAddress; } else { - throw new Error('Peer does not exist in peer store') + throw Error('Peer does not exist in peer store'); } } else { - address = peer + address = peer; } - const conn = new GitClient(address, this.keyManager) + const conn = new GitClient(address, this.keyManager); if (typeof peer == 'string') { - this.peerConnections.set(peer, conn) + this.peerConnections.set(peer, conn); } - return conn + return conn; } /* ============ HELPERS =============== */ private writeMetadata(): void { - const peerInfo = this.localPeerInfo + const peerInfo = this.localPeerInfo; const metadata = peer.PeerInfoMessage.encode({ addresses: peerInfo.AdressStringList, connectedAddr: peerInfo.connectedAddr?.toString(), - pubKey: peerInfo.publicKey - }).finish() - this.fileSystem.writeFileSync(this.metadataPath, metadata) + pubKey: peerInfo.publicKey, + }).finish(); + this.fileSystem.writeFileSync(this.metadataPath, metadata); } private loadMetadata(): void { // Check if file exists if (this.fileSystem.existsSync(this.metadataPath)) { - const metadata = this.fileSystem.readFileSync(this.metadataPath) - const { addresses, connectedAddr, pubKey } = peer.PeerInfoMessage.decode(metadata) - this.localPeerInfo = new PeerInfo(pubKey, addresses, connectedAddr) + const metadata = this.fileSystem.readFileSync(this.metadataPath); + const { addresses, connectedAddr, pubKey } = peer.PeerInfoMessage.decode(metadata); + this.localPeerInfo = new PeerInfo(pubKey, addresses, connectedAddr); } } } -export default PeerManager -export { SocialDiscovery } +export default PeerManager; +export { SocialDiscovery }; diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 3ce9cc999e..16cc50f57a 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -2,7 +2,10 @@ * Returns a 5 character long random string of lower case letters */ function randomString(): string { - return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5) + return Math.random() + .toString(36) + .replace(/[^a-z]+/g, '') + .substr(0, 5); } /** @@ -18,7 +21,7 @@ function invertPromise(p: Promise): Promise { * @param ps List of promises */ function firstPromiseFulfilled(ps: Promise[]) { - return invertPromise(Promise.all(ps.map(invertPromise))) + return invertPromise(Promise.all(ps.map(invertPromise))); } -export { randomString, firstPromiseFulfilled } +export { randomString, firstPromiseFulfilled }; diff --git a/src/lib/vaults/Vault.ts b/src/lib/vaults/Vault.ts index c00c39e73d..7fa9d38793 100644 --- a/src/lib/vaults/Vault.ts +++ b/src/lib/vaults/Vault.ts @@ -3,60 +3,50 @@ import Path from 'path'; import git from 'isomorphic-git'; import GitClient from '../git/GitClient'; import { EncryptedFS } from 'encryptedfs'; - +import { Mutex } from 'async-mutex'; type VaultMetadata = { - sharedPubKeys: string[] -} + sharedPubKeys: string[]; +}; class Vault { - - private key: Buffer - private keyLen: number - name: string - private efs: EncryptedFS - vaultPath: string - private secrets: Map - private sharedPubKeys: Set - private metadataPath: string - constructor( - name: string, - symKey: Buffer, - baseDir: string - ) { + private key: Buffer; + name: string; + private efs: EncryptedFS; + vaultPath: string; + private secrets: Map; + private sharedPubKeys: Set; + private metadataPath: string; + + // Concurrency + private mutex: Mutex = new Mutex(); + constructor(name: string, symKey: Buffer, baseDir: string) { // how do we create pub/priv key pair? // do we use the same gpg pub/priv keypair - this.key = symKey - this.keyLen = symKey.length + this.key = symKey; // Set filesystem - const vfsInstance = new (require('virtualfs')).VirtualFS - - this.efs = new EncryptedFS( - this.key, - vfsInstance, - vfsInstance, - fs, - process - ) - - this.name = name - this.vaultPath = Path.join(baseDir, name) + const vfsInstance = new (require('virtualfs').VirtualFS)(); + + this.efs = new EncryptedFS(this.key, vfsInstance, vfsInstance, fs, process); + + this.name = name; + this.vaultPath = Path.join(baseDir, name); // make the vault directory - this.efs.mkdirSync(this.vaultPath, { recursive: true }) - this.secrets = new Map() + this.efs.mkdirSync(this.vaultPath, { recursive: true }); + this.secrets = new Map(); - this.loadSecrets() + this.loadSecrets(); // Load metadata - this.metadataPath = Path.join(this.vaultPath, '.vault', 'metadata') - this.loadMetadata() + this.metadataPath = Path.join(this.vaultPath, '.vault', 'metadata'); + this.loadMetadata(); } /** * Returns the Encrypted File System used for vault operations */ public get EncryptedFS(): EncryptedFS { - return this.efs + return this.efs; } /** @@ -64,8 +54,8 @@ class Vault { * @param secretName Name of desired secret */ secretExists(secretName: string): boolean { - const secretPath = Path.join(this.vaultPath, secretName) - return this.secrets.has(secretName) && this.efs.existsSync(secretPath) + const secretPath = Path.join(this.vaultPath, secretName); + return this.secrets.has(secretName) && this.efs.existsSync(secretPath); } /** @@ -74,17 +64,25 @@ class Vault { * @param secret Content of new secret */ async addSecret(secretName: string, secret: Buffer): Promise { - // Check if secret already exists - if (this.secrets.has(secretName)) { - throw new Error('Secret already exists, try updating it instead.') + const release = await this.mutex.acquire(); + try { + // Check if secret already exists + if (this.secrets.has(secretName)) { + throw Error('Secret already exists, try updating it instead.'); + } + const writePath = Path.join(this.vaultPath, secretName); + // Write secret + await this.efs.promises.writeFile(writePath, secret, {}); + // Update secrets map + this.secrets.set(secretName, secret); + // Auto commit message + await this.commitChanges(`Add secret: ${secretName}`, secretName, 'added'); + } catch (error) { + release(); + throw error; + } finally { + release(); } - const writePath = Path.join(this.vaultPath, secretName) - // Write secret - await this.efs.promises.writeFile(writePath, secret, {}) - // Update secrets map - this.secrets.set(secretName, secret) - // Auto commit message - await this.commitChanges(`Add secret: ${secretName}`, secretName, 'added') } /** @@ -93,17 +91,25 @@ class Vault { * @param secret Content of updated secret */ async updateSecret(secretName: string, secret: Buffer): Promise { - // Check if secret already exists - if (!this.secrets.has(secretName)) { - throw new Error('Secret does not exist, try adding it instead.') + const release = await this.mutex.acquire(); + try { + // Check if secret already exists + if (!this.secrets.has(secretName)) { + throw Error('Secret does not exist, try adding it instead.'); + } + const writePath = Path.join(this.vaultPath, secretName); + // Write secret + await this.efs.promises.writeFile(writePath, secret, {}); + // Update secrets map + this.secrets.set(secretName, secret); + // Auto commit message + await this.commitChanges(`Update secret: ${secretName}`, secretName, 'modified'); + } catch (error) { + release(); + throw error; + } finally { + release(); } - const writePath = Path.join(this.vaultPath, secretName) - // Write secret - await this.efs.promises.writeFile(writePath, secret, {}) - // Update secrets map - this.secrets.set(secretName, secret) - // Auto commit message - await this.commitChanges(`Update secret: ${secretName}`, secretName, 'modified') } /** @@ -112,18 +118,18 @@ class Vault { */ getSecret(secretName: string): Buffer | string { if (this.secrets.has(secretName)) { - const secret = this.secrets.get(secretName) + const secret = this.secrets.get(secretName); if (secret) { - return secret + return secret; } else { - const secretPath = Path.join(this.vaultPath, secretName) + const secretPath = Path.join(this.vaultPath, secretName); // TODO: this should be async - const secretBuf = this.efs.readFileSync(secretPath, {}) - this.secrets.set(secretName, secretBuf) - return secretBuf + const secretBuf = this.efs.readFileSync(secretPath, {}); + this.secrets.set(secretName, secretBuf); + return secretBuf; } } - throw Error('Secret: ' + secretName + ' does not exist') + throw Error('Secret: ' + secretName + ' does not exist'); } /** @@ -131,36 +137,40 @@ class Vault { * @param secretName Name of secret to be removed */ async removeSecret(secretName: string): Promise { - if (this.secrets.has(secretName)) { - const successful = this.secrets.delete(secretName) - // Remove from fs - await this.efs.promises.unlink(Path.join(this.vaultPath, secretName)) - // Auto commit message - await this.commitChanges(`Remove secret: ${secretName}`, secretName, 'removed') - - if (successful) { - return + const release = await this.mutex.acquire(); + try { + if (this.secrets.has(secretName)) { + const successful = this.secrets.delete(secretName); + // Remove from fs + await this.efs.promises.unlink(Path.join(this.vaultPath, secretName)); + // Auto commit message + await this.commitChanges(`Remove secret: ${secretName}`, secretName, 'removed'); + + if (successful) { + return; + } + throw Error('Secret: ' + secretName + ' was not removed'); } - throw Error('Secret: ' + secretName + ' was not removed') + throw Error('Secret: ' + secretName + ' does not exist'); + } catch (error) { + release(); + throw error; + } finally { + release(); } - throw Error('Secret: ' + secretName + ' does not exist') } /** * Lists all the secrets currently in the vault */ listSecrets(): string[] { - let secrets: string[] = Array.from(this.secrets.keys()) - return secrets + let secrets: string[] = Array.from(this.secrets.keys()); + return secrets; } - tagVault() { + tagVault() {} - } - - untagVault() { - - } + untagVault() {} ///////////// // Sharing // @@ -171,13 +181,13 @@ class Vault { */ shareVault(publicKey: string) { if (this.sharedPubKeys.has(name)) { - throw new Error('Vault is already shared with given public key') + throw Error('Vault is already shared with given public key'); } - this.sharedPubKeys.add(publicKey) + this.sharedPubKeys.add(publicKey); // Write metadata - this.writeMetadata() + this.writeMetadata(); } /** @@ -186,13 +196,13 @@ class Vault { */ unshareVault(publicKey: string) { if (!this.sharedPubKeys.has(publicKey)) { - throw new Error('Vault is not shared with given public key') + throw Error('Vault is not shared with given public key'); } - this.sharedPubKeys.delete(publicKey) + this.sharedPubKeys.delete(publicKey); // Write metadata - this.writeMetadata() + this.writeMetadata(); } /** @@ -201,7 +211,7 @@ class Vault { */ peerCanAccess(publicKey: string): boolean { // return this.sharedPubKeys.has(publicKey) - return true + return true; } /** @@ -210,113 +220,113 @@ class Vault { * @param getSocket Function to get an active connection to provided address */ async pullVault(gitClient: GitClient) { - // Strangely enough this is needed for pulls along with ref set to 'HEAD' - // In isogit's documentation, this is just to get the currentBranch name - // But it solves a bug whereby if not used, git.pull complains that it can't - // find the master branch or HEAD - await git.currentBranch({ - fs: { promises: this.efs.promises }, - dir: this.vaultPath, - fullname: true - }) - // First pull - await git.pull({ - fs: { promises: this.efs.promises }, - http: gitClient, - dir: this.vaultPath, - url: "http://" + '0.0.0.0:0' + '/' + this.name, - ref: 'HEAD', - singleBranch: true, - author: { - name: this.name - } - }) - - // Load any new secrets - this.loadSecrets() + const release = await this.mutex.acquire(); + try { + // Strangely enough this is needed for pulls along with ref set to 'HEAD' + // In isogit's documentation, this is just to get the currentBranch name + // But it solves a bug whereby if not used, git.pull complains that it can't + // find the master branch or HEAD + await git.currentBranch({ + fs: { promises: this.efs.promises }, + dir: this.vaultPath, + fullname: true, + }); + // First pull + await git.pull({ + fs: { promises: this.efs.promises }, + http: gitClient, + dir: this.vaultPath, + url: 'http://' + '0.0.0.0:0' + '/' + this.name, + ref: 'HEAD', + singleBranch: true, + author: { + name: this.name, + }, + }); + + // Load any new secrets + this.loadSecrets(); + } catch (error) { + release(); + throw error; + } finally { + release(); + } } - /** - * Initializes the git repository for new vaults - */ - async initRepository() { - const fileSystem = this.efs - await git.init({ - fs: fileSystem, - dir: this.vaultPath - }) - - // Initial commit - await git.commit({ - fs: fileSystem, + async getVaultHistory(depth?: number) { + const logs = await git.log({ + fs: { promises: this.efs.promises }, dir: this.vaultPath, - author: { - name: this.name - }, - message: "init commit" - }) - - // Write packed-refs file because isomorphic git goes searching for it - // and apparently its not autogenerated - this.efs.writeFileSync(Path.join(this.vaultPath, '.git', 'packed-refs'), '# pack-refs with: peeled fully-peeled sorted') + depth, + }); + return logs.map((commit) => { + return commit.commit.message; + }); } // ============== Helper methods ============== // private writeMetadata(): void { // mkdir first - this.efs.mkdirSync(Path.dirname(this.metadataPath), { recursive: true }) + this.efs.mkdirSync(Path.dirname(this.metadataPath), { recursive: true }); // Create and write metadata const metadata: VaultMetadata = { - sharedPubKeys: Array.from(this.sharedPubKeys.keys()) - } - this.efs.writeFileSync(this.metadataPath, JSON.stringify(metadata)) + sharedPubKeys: Array.from(this.sharedPubKeys.keys()), + }; + this.efs.writeFileSync(this.metadataPath, JSON.stringify(metadata)); } private loadMetadata(): void { if (this.efs.existsSync(this.metadataPath)) { - const fileContents = this.efs.readFileSync(this.metadataPath).toString() - const metadata: VaultMetadata = JSON.parse(fileContents) - this.sharedPubKeys = new Set(metadata.sharedPubKeys) + const fileContents = this.efs.readFileSync(this.metadataPath).toString(); + const metadata: VaultMetadata = JSON.parse(fileContents); + this.sharedPubKeys = new Set(metadata.sharedPubKeys); } else { // Need to create it - this.sharedPubKeys = new Set() - this.writeMetadata() + this.sharedPubKeys = new Set(); + this.writeMetadata(); } } - private async commitChanges(message: string, secretName: string, action: 'added' | 'modified' | 'removed'): Promise { + private async commitChanges( + message: string, + secretName: string, + action: 'added' | 'modified' | 'removed', + ): Promise { if (action == 'removed') { await git.remove({ - fs: this.efs, + fs: { promises: this.efs.promises }, dir: this.vaultPath, - filepath: secretName - }) + filepath: secretName, + }); } else { await git.add({ - fs: this.efs, + fs: { promises: this.efs.promises }, dir: this.vaultPath, - filepath: secretName - }) + filepath: secretName, + }); } return await git.commit({ - fs: this.efs, + fs: { promises: this.efs.promises }, dir: this.vaultPath, author: { - name: this.name + name: this.name, }, - message: message - }) + message: message, + }); } private loadSecrets(): void { - const secrets = fs.readdirSync(this.vaultPath, undefined) - + const secrets = fs.readdirSync(this.vaultPath, undefined); + // Remove all secrets first + this.secrets.clear(); + // Load secrets for (const secret of secrets.filter((s) => s[0] != '.')) { - this.secrets.set(secret, null) + this.secrets.set(secret, null); } } } -export default Vault +export default Vault; diff --git a/src/lib/vaults/VaultManager.ts b/src/lib/vaults/VaultManager.ts index c13d80953f..3018424db8 100644 --- a/src/lib/vaults/VaultManager.ts +++ b/src/lib/vaults/VaultManager.ts @@ -1,4 +1,3 @@ - import fs from 'fs'; import os from 'os'; import Path from 'path'; @@ -9,39 +8,35 @@ import { EncryptedFS } from 'encryptedfs'; import KeyManager from '../keys/KeyManager'; class VaultManager { - polykeyPath: string - fileSystem: typeof fs - keyManager: KeyManager - - metadataPath: string - vaults: Map - vaultKeys: Map - constructor( - polykeyPath: string = `${os.homedir()}/.polykey`, - fileSystem: typeof fs, - keyManager: KeyManager - ) { - this.polykeyPath = polykeyPath - this.fileSystem = fileSystem - this.keyManager = keyManager - this.metadataPath = Path.join(polykeyPath, '.vaultKeys') + polykeyPath: string; + fileSystem: typeof fs; + keyManager: KeyManager; + + metadataPath: string; + vaults: Map; + vaultKeys: Map; + constructor(polykeyPath: string = `${os.homedir()}/.polykey`, fileSystem: typeof fs, keyManager: KeyManager) { + this.polykeyPath = polykeyPath; + this.fileSystem = fileSystem; + this.keyManager = keyManager; + this.metadataPath = Path.join(polykeyPath, '.vaultKeys'); // Make polykeyPath if it doesn't exist - this.fileSystem.mkdirSync(this.polykeyPath, { recursive: true }) + this.fileSystem.mkdirSync(this.polykeyPath, { recursive: true }); // Initialize stateful variables - this.vaults = new Map() - this.vaultKeys = new Map() + this.vaults = new Map(); + this.vaultKeys = new Map(); // Read in vault keys - this.loadMetadata() + this.loadMetadata(); // Initialize vaults in memory for (const [vaultName, vaultKey] of this.vaultKeys.entries()) { - const path = Path.join(this.polykeyPath, vaultName) + const path = Path.join(this.polykeyPath, vaultName); if (this.fileSystem.existsSync(path)) { - const vault = new Vault(vaultName, vaultKey, this.polykeyPath) - this.vaults.set(vaultName, vault) + const vault = new Vault(vaultName, vaultKey, this.polykeyPath); + this.vaults.set(vaultName, vault); } } } @@ -52,19 +47,19 @@ class VaultManager { */ getVault(vaultName: string): Vault { if (this.vaults.has(vaultName)) { - const vault = this.vaults.get(vaultName) - return vault! + const vault = this.vaults.get(vaultName); + return vault!; } else if (this.vaultKeys.has(vaultName)) { // vault not in map, create new instance - this.validateVault(vaultName) + this.validateVault(vaultName); - const vaultKey = this.vaultKeys.get(vaultName) + const vaultKey = this.vaultKeys.get(vaultName); - const vault = new Vault(vaultName, vaultKey!, this.polykeyPath) - this.vaults.set(vaultName, vault) - return vault + const vault = new Vault(vaultName, vaultKey!, this.polykeyPath); + this.vaults.set(vaultName, vault); + return vault; } else { - throw new Error('Vault does not exist in memory') + throw Error('Vault does not exist in memory'); } } @@ -74,34 +69,58 @@ class VaultManager { * @param key Optional key to use for the vault encryption, otherwise it is generated */ async createVault(vaultName: string, key?: Buffer): Promise { - if (this.vaultExists(vaultName)) { - throw Error('Vault already exists!') + throw Error('Vault already exists!'); } try { - const path = Path.join(this.polykeyPath, vaultName) + const path = Path.join(this.polykeyPath, vaultName); // Directory not present, create one - this.fileSystem.mkdirSync(path, { recursive: true }) + this.fileSystem.mkdirSync(path, { recursive: true }); // Create key if not provided - let vaultKey: Buffer + let vaultKey: Buffer; if (!key) { // Generate new key - vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey()) + vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey()); } else { // Assign key if it is provided - vaultKey = key + vaultKey = key; } - this.vaultKeys.set(vaultName, vaultKey) - this.writeMetadata() - const vault = new Vault(vaultName, vaultKey, this.polykeyPath) - await vault.initRepository() - this.vaults.set(vaultName, vault) - return this.getVault(vaultName) + this.vaultKeys.set(vaultName, vaultKey); + this.writeMetadata(); + + // Create vault + const vault = new Vault(vaultName, vaultKey, this.polykeyPath); + + // Init repository for vault + const vaultPath = Path.join(this.polykeyPath, vaultName); + const efs = vault.EncryptedFS; + const fileSystem = { promises: efs.promises }; + await git.init({ + fs: fileSystem, + dir: vaultPath, + }); + + // Initial commit + await git.commit({ + fs: fileSystem, + dir: vaultPath, + author: { + name: vaultName, + }, + message: 'init commit', + }); + // Write packed-refs file because isomorphic git goes searching for it + // and apparently its not autogenerated + efs.writeFileSync(Path.join(vaultPath, '.git', 'packed-refs'), '# pack-refs with: peeled fully-peeled sorted'); + + // Set vault + this.vaults.set(vaultName, vault); + return this.getVault(vaultName); } catch (err) { // Delete vault dir and garbage collect - this.destroyVault(vaultName) - throw err + this.destroyVault(vaultName); + throw err; } } @@ -114,35 +133,29 @@ class VaultManager { async cloneVault(vaultName: string, gitClient: GitClient): Promise { // Confirm it doesn't exist locally already if (this.vaultExists(vaultName)) { - throw new Error('Vault name already exists locally, try pulling instead') + throw Error('Vault name already exists locally, try pulling instead'); } - const vaultUrl = `http://0.0.0.0/${vaultName}` + const vaultUrl = `http://0.0.0.0/${vaultName}`; // First check if it exists on remote const info = await git.getRemoteInfo({ http: gitClient, - url: vaultUrl - }) + url: vaultUrl, + }); if (!info.refs) { - throw new Error(`Peer does not have vault: '${vaultName}'`) + throw Error(`Peer does not have vault: '${vaultName}'`); } // Create new efs first // Generate new key - const vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey()) + const vaultKey = await this.keyManager.generateKey(`${vaultName}-Key`, this.keyManager.getPrivateKey()); // Set filesystem - const vfsInstance = new (require('virtualfs')).VirtualFS + const vfsInstance = new (require('virtualfs').VirtualFS)(); - const newEfs = new EncryptedFS( - vaultKey, - vfsInstance, - vfsInstance, - this.fileSystem, - process - ) + const newEfs = new EncryptedFS(vaultKey, vfsInstance, vfsInstance, this.fileSystem, process); // Clone vault from address await git.clone({ @@ -151,13 +164,13 @@ class VaultManager { dir: Path.join(this.polykeyPath, vaultName), url: vaultUrl, ref: 'master', - singleBranch: true - }) + singleBranch: true, + }); // Finally return the vault - const vault = new Vault(vaultName, vaultKey, this.polykeyPath) - this.vaults.set(vaultName, vault) - return vault + const vault = new Vault(vaultName, vaultKey, this.polykeyPath); + this.vaults.set(vaultName, vault); + return vault; } /** @@ -165,10 +178,10 @@ class VaultManager { * @param vaultName Name of desired vault */ vaultExists(vaultName: string): boolean { - const path = Path.join(this.polykeyPath, vaultName) - const vaultExists = this.fileSystem.existsSync(path) + const path = Path.join(this.polykeyPath, vaultName); + const vaultExists = this.fileSystem.existsSync(path); - return vaultExists + return vaultExists; } /** @@ -176,27 +189,26 @@ class VaultManager { * @param vaultName Name of vault to be destroyed */ destroyVault(vaultName: string) { - // this is convenience function for removing all tags // and triggering garbage collection // destruction is a better word as we should ensure all traces is removed - const path = Path.join(this.polykeyPath, vaultName) + const path = Path.join(this.polykeyPath, vaultName); // Remove directory on file system if (this.fileSystem.existsSync(path)) { - this.fileSystem.rmdirSync(path, { recursive: true }) + this.fileSystem.rmdirSync(path, { recursive: true }); } // Remove from maps - this.vaults.delete(vaultName) - this.vaultKeys.delete(vaultName) + this.vaults.delete(vaultName); + this.vaultKeys.delete(vaultName); // Write to metadata file - this.writeMetadata() + this.writeMetadata(); - const vaultPathExists = this.fileSystem.existsSync(path) + const vaultPathExists = this.fileSystem.existsSync(path); if (vaultPathExists) { - throw new Error('Vault folder could not be destroyed!') + throw Error('Vault folder could not be destroyed!'); } } @@ -204,38 +216,38 @@ class VaultManager { * List the names of all vaults in memory */ listVaults(): string[] { - return Array.from(this.vaults.keys()) + return Array.from(this.vaults.keys()); } /* ============ HELPERS =============== */ private validateVault(vaultName: string): void { if (!this.vaults.has(vaultName)) { - throw Error('Vault does not exist in memory') + throw Error('Vault does not exist in memory'); } if (!this.vaultKeys.has(vaultName)) { - throw Error('Vault key does not exist in memory') + throw Error('Vault key does not exist in memory'); } - const vaultPath = Path.join(this.polykeyPath, vaultName) + const vaultPath = Path.join(this.polykeyPath, vaultName); if (!this.fileSystem.existsSync(vaultPath)) { - throw Error('Vault directory does not exist') + throw Error('Vault directory does not exist'); } } private async writeMetadata(): Promise { - const metadata = JSON.stringify([...this.vaultKeys]) - const encryptedMetadata = await this.keyManager.encryptData(Buffer.from(metadata)) - await this.fileSystem.promises.writeFile(this.metadataPath, encryptedMetadata) + const metadata = JSON.stringify([...this.vaultKeys]); + const encryptedMetadata = await this.keyManager.encryptData(Buffer.from(metadata)); + await this.fileSystem.promises.writeFile(this.metadataPath, encryptedMetadata); } private async loadMetadata(): Promise { // Check if file exists if (this.fileSystem.existsSync(this.metadataPath) && this.keyManager.identityLoaded) { - const encryptedMetadata = this.fileSystem.readFileSync(this.metadataPath) - const metadata = (await this.keyManager.decryptData(encryptedMetadata)).toString() + const encryptedMetadata = this.fileSystem.readFileSync(this.metadataPath); + const metadata = (await this.keyManager.decryptData(encryptedMetadata)).toString(); for (const [key, value] of new Map(JSON.parse(metadata))) { - this.vaultKeys[key] = Buffer.from(value) + this.vaultKeys[key] = Buffer.from(value); } } } } -export default VaultManager +export default VaultManager; diff --git a/tests/lib/git/GitBackend.test.ts b/tests/lib/git/GitBackend.test.ts new file mode 100644 index 0000000000..46d6ac1a9f --- /dev/null +++ b/tests/lib/git/GitBackend.test.ts @@ -0,0 +1,18 @@ +import os from 'os'; +import fs from 'fs'; +import { randomString } from '../../../src/lib/utils'; + +describe('GitBackend class', () => { + let tempDir: string + + beforeEach(async () => { + tempDir = fs.mkdtempSync(`${os.tmpdir}/pktest${randomString()}`) + }) + + afterEach(() => { + fs.rmdirSync(tempDir, { recursive: true }) + }) + + test('git works properly', async () => { + }) +}) diff --git a/tests/lib/vaults/Vaults.test.ts b/tests/lib/vaults/Vaults.test.ts index ba86dc9d61..c6b9e50e91 100644 --- a/tests/lib/vaults/Vaults.test.ts +++ b/tests/lib/vaults/Vaults.test.ts @@ -1,10 +1,11 @@ -import fs from 'fs'; +import fs, { write } from 'fs'; import os from 'os'; import path from 'path'; import Polykey from "../../../src/lib/Polykey"; import { randomString } from '../../../src/lib/utils'; import KeyManager from '../../../src/lib/keys/KeyManager'; import VaultManager from '../../../src/lib/vaults/VaultManager'; +import crypto from 'crypto'; describe('VaultManager class', () => { let randomVaultName: string @@ -192,7 +193,7 @@ describe('VaultManager class', () => { done() }) - test('removing secrets from shared vaults is reflected in peer vault', async done => { + test('removing secret is reflected in peer vault', async done => { // Create vault const vault = await vm.createVault(randomVaultName) // Add secret @@ -225,4 +226,35 @@ describe('VaultManager class', () => { done() }) }) + + ///////////////// + // Concurrency // + ///////////////// + describe('concurrency', () => { + test('parallel write operations are sequentially executed', async done => { + const vault = await pk.vaultManager.createVault(randomVaultName) + const writeOps: Promise[] = [] + const expectedHistory: number[] = [] + for (const n of Array(50).keys()) { + // Get a random number of bytes so each operation might finish earlier than the others + const randomNumber = 1 + Math.round(Math.random() * 5000) + const secretBuffer = crypto.randomBytes(randomNumber) + const writeOp = vault.addSecret(`${n + 1}`, secretBuffer) + writeOps.push(writeOp) + expectedHistory.push(n + 1) + } + await Promise.all(writeOps) + + const history = (await vault.getVaultHistory()).reverse() + .map((commit) => { + const match = commit.match(/([0-9]+)/) + return (match) ? parseInt(match[0]) : undefined + }) + .filter((n) => n != undefined) + + expect(history).toEqual(expectedHistory) + + done() + }, 20000) + }) }) diff --git a/webpack-plugins/DeclarationBundlePlugin.ts b/webpack-plugins/DeclarationBundlePlugin.ts index d67e22be1d..871a3a407e 100644 --- a/webpack-plugins/DeclarationBundlePlugin.ts +++ b/webpack-plugins/DeclarationBundlePlugin.ts @@ -25,7 +25,6 @@ class DeclarationBundlePlugin { log(message: string) { console.log(`[DeclarationBundlePlugin] ${message}`); - } apply(compiler: webpack.Compiler) { @@ -80,15 +79,10 @@ class DeclarationBundlePlugin { fs.writeFileSync(this.outputFilePath, newContents) } } else if (this.singleFile) { - const split = this.entryFilePath.split('/') - const filename = split[split.length-1].split('.')[0] - console.log(filename); - - const entryFile = path.join(tempDir, `${path.join('agent', filename)}.d.ts`) - console.log('=========='); - console.log(entryFile); - console.log('=========='); + const split = this.entryFilePath.split('.') + const filename = split[split.length-2] + const entryFile = path.join(tempDir, `${filename}.d.ts`) fs.copyFileSync(entryFile, this.outputFilePath) } diff --git a/webpack.config.ts b/webpack.config.ts index 9e97ceba37..3c678492ba 100644 --- a/webpack.config.ts +++ b/webpack.config.ts @@ -70,6 +70,9 @@ const libraryConfig = { ], watchOptions: { ignored: /node_modules/ + }, + optimization: { + minimize: false } } @@ -116,6 +119,9 @@ const polykeyClientConfig = { ], watchOptions: { ignored: /node_modules/ + }, + optimization: { + minimize: false } } @@ -157,6 +163,9 @@ const cliConfig = { ], watchOptions: { ignored: /node_modules/ + }, + optimization: { + minimize: false } } @@ -193,6 +202,9 @@ const agentDaemonScriptConfig = { { "../../Polykey": "commonjs ../polykey.js" }, nodeExternals() ], + optimization: { + minimize: false + } }