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QAAQ,IAEjB,IAAX,IAA4B,IAAT,EACrB,KAAK,SAAS,KAAK,IACD,IAAX,IAA4B,IAAT,GAC1B,KAAK,SAAS,OAAO,EAAG,EAP1B,MAHiB,IAAX,IACF,KAAK,SAAW,CAAC,GAUvB,EAyCA,MAAM,UAAU,QAAU,SAAiB,EAAI,GAC7C,GAAkB,mBAAP,EACT,MAAM,IAAI,UAAU,+BAEtB,GAAK,KAAK,SAAV,CAMA,IAAI,EAAM,KAAK,SAAS,QAAQ,IAEjB,IAAX,IAA4B,IAAT,EACrB,KAAK,SAAS,KAAK,IACD,IAAX,IAA4B,IAAT,GAC1B,KAAK,SAAS,OAAO,EAAG,EAP1B,MAHiB,IAAX,IACF,KAAK,SAAW,CAAC,GAUvB","file":"/npm/psycho-proxy@0.1.2/main.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/psycho-proxy@0.1.2/main.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","var Pipe = process.binding('pipe_wrap').Pipe;\nvar TCP = process.binding('tcp_wrap').TCP;\nvar dns = require('dns');\nvar path = require('path');\nvar util = require('util');\n\n// Extending Pipe and TCP a little to keep then monomorphic constructors.\n\n// Attach the server of the incoming connection for future reference.\nTCP.prototype._server = undefined;\nPipe.prototype._server = undefined;\n\n// Attach the Proxy instance to the server created on instantiation.\nTCP.prototype._proxy = undefined;\nPipe.prototype._proxy = undefined;\n\n// The total number of bytes read from a connection. Used to track if too\n// many bytes have been received without finding the Host header.\nPipe.prototype._nread_total = 0;\nTCP.prototype._nread_total = 0;\n\n// Stored Buffers of incoming requests so we can concat() the data once\n// enough has been collected to read the Host header field.\nPipe.prototype._buffers = undefined;\nTCP.prototype._buffers = undefined;\n\n// The return path of a connection when piping data.\nPipe.prototype._return_route = undefined;\nTCP.prototype._return_route = undefined;\n\n\n// Default maximum incoming header size before closing connection is 64KB.\nvar max_header_length = 64 * 1024;\n\n// TODO(trevnorris): Add check for total number of incoming packet requests\n// before closing the connection. Someone could jack the server by sending\n// many tiny requests very slowly.\n\n// TODO(trevnorris): Add timeout check for incoming requests. So a single\n// connection can't hold open resources without actually using them.\n\n// Export the thing.\nmodule.exports = Proxy;\n\n\n// A Proxy holds a list of headers and their destinations. When a router\n// is instantiated a path or port (pOp) is passed which is where the\n// instance will listen for connections.\nfunction Proxy(pOp) {\n  if (!(this instanceof Proxy))\n    return new Proxy(pOp);\n\n  // Routes that incoming connections must take when they contain a specific\n  // Host HTTP header field.\n  this._host_routes = {};\n\n  // Both setupTCPServer and setupPipeServer will set the ._handle property.\n  if (!isNaN(pOp)) {\n    this._pOp = pOp >>> 0;\n    setupTCPServer(this, this._pOp);\n  } else if (typeof pOp === 'string') {\n    this._pOp = path.normalize(pOp);\n    setupPipeServer(this, this._pOp);\n  } else {\n    throw new TypeError('argument must be port or path');\n  }\n\n  this._handle.onconnection = onConnection;\n  this._handle._proxy = this;\n}\n\nProxy.prototype._handle = undefined;\nProxy.prototype._host_routes = undefined;\nProxy.prototype._onalert = undefined;\nProxy.prototype._onerror = undefined;\nProxy.prototype._pOp = undefined;\n\n\n// Maximum size in bytes to accept in header before Host: field is found.\n// When the maximum length is reached, the connection is immediately\n// closed and an alert is issued. Default is 64KB.\nProxy.setMaxHeaderLength = function setMaxHeaderLength(n) {\n  max_header_length = n >>> 0;\n}\n\n\n// First argument is the Host HTTP header to be looking for.\n// Second argument is the port or path where the data should be piped.\n// TODO(trevnorris): Allow adding routes to other host names.\nProxy.prototype.add = function addRoute(host, pOp) {\n  pOp = isNaN(pOp) ? path.normalize(pOp) : pOp >>> 0;\n\n  if (!this._host_routes[host])\n    this._host_routes[host] = [pOp];\n  else if (this._host_routes[host].indexOf(pOp) < 0)\n    this._host_routes[host].push(pOp);\n};\n\n\n// Pass a Host header that should no longer be checked, but allows existing\n// connections to finish.\nProxy.prototype.close = function closeRoute(host) {\n  throw new Error('Closing a route has not been implemented');\n};\n\n\n// Forcefully terminate all connections for a specific Host header.\nProxy.prototype.remove = function removeRoute(host) {\n  throw new Error('Removing routes has not been implemented');\n};\n\n\n// setupPipeServer and setupTCPServer are the servers to receive the\n// incoming data.\n\nfunction setupPipeServer(self, path) {\n  var socket = new Pipe();\n  var err;\n\n  self._handle = socket;\n\n  err = socket.bind(path);\n  if (err)\n    fail(self, err, 'bind');\n\n  err = socket.listen(511);\n  if (err)\n    fail(self, err, 'listen');\n\n  return socket;\n}\n\n\n// TODO(trevnorris): Properly support IPv6.\nfunction setupTCPServer(self, port) {\n  var server = new TCP();\n  var err;\n\n  self._handle = server;\n\n  err = server.bind('127.0.0.1', port);\n  if (err)\n    fail(self, err, 'bind');\n\n  err = server.listen(511);\n  if (err)\n    fail(self, err, 'listen');\n\n  return server;\n}\n\n\n// This handles when a connection is received by the listening Proxy.\nfunction onConnection(err, client) {\n  if (err)\n    fail(this, err, 'connect');\n\n  client._server = this;\n\n  if (client.setKeepAlive) {\n    err = client.setKeepAlive(true, 10000);\n    if (err)\n      fail(this, err, 'keepAlive');\n  }\n\n  // First thing we do when a connection is made to the Proxy is verify\n  // it is a proper GET or POST. The .onread callback will be reassigned\n  // once this is verified.\n  client.onread = verifyRequest;\n\n  err = client.readStart();\n  if (err)\n    fail(this, err, 'read');\n}\n\n\n// Verify early the request is good by checking GET/POST.\nfunction verifyRequest(nread, buffer) {\n  if (nread < 0)\n    return this.close(onClose);\n  if (nread === 0)\n    return;\n\n  this._nread_total += nread;\n\n  // First make sure we have at least enough to read the request type.\n  if (this._nread_total < 5) {\n    if (!this._buffers)\n      this._buffers = [buffer];\n    else\n      this._buffers.push(buffer);\n    return;\n  }\n\n  // LAZY(trevnorris): The Buffer.concat() thing is me being lazy. Optimize\n  // once I have it working properly.\n  if (this._buffers) {\n    this._buffers.push(buffer);\n    buffer = Buffer.concat(this._buffers);\n    this._buffers = undefined;\n  }\n\n  // LAZY(trevnorris)\n  var str = buffer.toString('binary');\n\n  // Initially only supporting GET/POST, if the header does not start\n  // with one of these then the client connection will be dropped and\n  // and alert() will be broadcast.\n\n  if (str.substr(0, 4) !== 'GET ' && str.substr(0, 5) !== 'POST ') {\n    // Bad request, so alert and cleanup connection.\n    var err = new Error('Bad HTTP Request');\n    // Totally making this up.\n    err.code = 'EBADHTTPREQ'\n    // Attach the headers we have received so the user can do some logging.\n    err.headers = str;\n    err.data = buffer;\n    alert(this, err);\n    this.close(onClose);\n    return;\n  }\n\n  this.onread = searchHostHeader;\n  // Reset to 0 since we're passing the entire concat'd buffer to next\n  // callback, which will then properly set it again if the data can't be\n  // passed on to the route destination.\n  this._nread_total = 0;\n\n  // LAZY(trevnorris): Don't really like that I'm using a .call() here, but\n  // was the easiest way to manage this problem.\n  searchHostHeader.call(this, buffer.length, buffer);\n}\n\n\n// Check for the Host header.\nfunction searchHostHeader(nread, buffer) {\n  if (nread < 0)\n    return this.close(onClose);\n  if (nread === 0)\n    return;\n\n  this._nread_total += nread;\n\n  // LAZY(trevnorris)\n  if (this._buffers) {\n    this._buffers.push(buffer);\n    buffer = Buffer.concat(this._buffers);\n    this._buffers = undefined;\n  }\n\n  var end_cap = -1;\n\n  // Search for termination.\n  // TODO(trevnorris): This only searches for \\r\\n\\r\\n, but it's possible\n  // to receive malformed data that might look like \\n\\n. This should\n  // probably be supported.\n  for (var i = 0; i < buffer.length - 3; i++) {\n    if (buffer[i] === 13 && buffer[i + 1] === 10 &&\n        buffer[i + 2] === 13 && buffer[i + 3] === 10) {\n      end_cap = i;\n      break;\n    }\n  }\n\n  // Didn't find the end of the request, so wait for more data.\n  if (end_cap < 0) {\n    // Check if we've read in too much already.\n    if (this._nread_total > max_header_length) {\n      var err = this.readStop();\n      if (err)\n        fail(this, err, 'read');\n      this.close(onClose);\n    }\n    this._buffers = [buffer];\n    return;\n  }\n\n  var host_string;\n\n  // Found the end of the request, so find the host.\n  // LAZY(trevnorris)\n  var str = buffer.toString();\n  var arr = str.split('\\r\\n');\n  // First line should be the request type.\n  for (var i = 1; i < arr.length; i++) {\n    var idx = arr[i].indexOf(':');\n    // This is freakishly lazy of me.\n    var field = arr[i].slice(0, idx).trim().toLowerCase();\n    if (field === 'host') {\n      host_string = arr[i].slice(idx + 1).trim();\n      break;\n    }\n  }\n\n  var routes = this._server._proxy._host_routes[host_string];\n\n  // Check if a route even exists for this host_string.\n  if (routes == null) {\n    var err = new Error('No known destination for Host: ' + host_string);\n    // Making this up.\n    err.code = 'ENOROUTE';\n    err.host = host_string;\n    err.data = buffer;\n    alert(this, err);\n    this.close(onClose);\n    return;\n  }\n\n  // We've now verified the request is OK. So make the connection(s) and\n  // being piping the data.\n  var connection;\n  for (var i = 0; i < routes.length; i++) {\n    var pOp = routes[i];\n    if (isNaN(pOp))\n      connection = PipeConnect(this, buffer, pOp);\n    else\n      connection = TCPConnect(this, buffer, '127.0.0.1', pOp);\n  }\n\n  // Attach each connection to each other for quick data piping.\n  connection._return_route = this;\n  this._return_route = connection;\n\n  // TODO(trevnorris): Store these connections in the Proxy instance so\n  // they can be cleaned up when close() and remove() are implemented.\n\n  // Overwrite the .onread method to proxy data directly.\n  this.onread = proxyDataToClient;\n}\n\n\nfunction PipeConnect(self, data, path) {\n  var client = new Pipe();\n  var req = { oncomplete: afterConnect, _data: data };\n  var err = client.connect(req, path);\n  if (err)\n    fail(self, err, 'connect');\n  return client;\n}\n\n\nfunction TCPConnect(self, data, host, port) {\n  var client = new TCP();\n  var req = { oncomplete: afterConnect, _data: data };\n  var err = client.connect(req, host, port);\n  if (err)\n    fail(self, err, 'connect');\n  return client;\n}\n\n\nfunction afterConnect(err, client, req, readable, writable) {\n  if (err)\n    fail(client, err, 'connect');\n  client.onread = proxyDataToClient;\n  err = client.readStart();\n  if (err)\n    fail(client, err, 'read');\n  if (client.fd <= 0) {\n    err = new Error('Attempt to write to bad file descriptor');\n    err.code = 'EBADF';\n    alert(client, err);\n    return;\n  }\n  err = client.writeBuffer({ oncomplete: dataWritten }, req._data);\n  if (err)\n    fail(client, err, 'write');\n}\n\n\nfunction proxyDataToClient(nread, data) {\n  if (nread <= 0) {\n    if (nread < 0)\n      this.close(onClose);\n    return;\n  }\n  if (this._return_route.fd <= 0) {\n    err = new Error('Attempt to write to bad file descriptor');\n    err.code = 'EBADF';\n    alert(this, err);\n    return;\n  }\n  var req = { oncomplete: dataWritten };\n  var err = this._return_route.writeBuffer(req, data);\n  if (err)\n    fail(this, err, 'write');\n}\n\n\nfunction dataWritten(err, handle, req) {\n  if (err)\n    fail(handle, err, 'write');\n  // TODO(trevnorris): Took this straight from core, but do some research\n  // why this is necessary.\n  if (req && req.cb)\n    req.cb.call(handle);\n}\n\n\nfunction onClose() {\n  // TODO(trevnorris): Clean up resources.\n}\n\n\n// Alerts are issues encountered that will not prevent the app\n// from functioning, but are still useful for the user to know.\n//\n// The same callback can only be called once.\n//\n// fn: Function to be called when an alert is emitted.\n// remove: Boolean if the callback should be removed.\nProxy.prototype.onalert = function onAlert(fn, remove) {\n  if (typeof fn !== 'function')\n    throw new TypeError('argument must be a function');\n\n  if (!this._onalert) {\n    if (remove !== true)\n      this._onalert = [fn];\n    return;\n  }\n\n  var idx = this._onalert.indexOf(fn);\n\n  if (remove !== true && idx === -1)\n    this._onalert.push(fn);\n  else if (remove === true && idx !== -1)\n    this._onalert.splice(1, idx);\n};\n\n\n// Alert the user that something has occurred. An Error object is still\n// used, but will never be thrown.\nfunction alert(self, err) {\n  var callbacks, i;\n\n  err.handle = self;\n\n  // These are all the paths where onalert() callback handlers may be found.\n  if (self._onalert)\n    callbacks = self._onalert;\n  else if (self._proxy && self._proxy._onalert)\n    callbacks = self._proxy._onalert;\n  else if (self._server &&\n           self._server._proxy &&\n           self._server._proxy._onalert)\n    callbacks = self._server._proxy._onalert;\n  else if (self._return_route &&\n           self._return_route._server &&\n           self._return_route._server._proxy &&\n           self._return_route._server._proxy._onalert)\n    callbacks = self._return_route._server._proxy._onalert;\n  else\n    return;\n\n  if (callbacks.length === 0)\n    return;\n\n  for (i = 0; i < callbacks.length; i++)\n    callbacks[i].call(self, err);\n}\n\n\n// Error handler used when system calls fail. For example, if an attmpt to\n// open a remote connection fails.\n//\n// fn: Function, to be called when an alert is emitted. The same function can\n//     only be added once.\n// remove: Boolean if the callback should be removed.\nProxy.prototype.onerror = function onError(fn, remove) {\n  if (typeof fn !== 'function')\n    throw new TypeError('argument must be a function');\n\n  if (!this._onerror) {\n    if (remove !== true)\n      this._onerror = [fn];\n    return;\n  }\n\n  var idx = this._onerror.indexOf(fn);\n\n  if (remove !== true && idx === -1)\n    this._onerror.push(fn);\n  else if (remove === true && idx !== -1)\n    this._onerror.splice(1, idx);\n};\n\n\n// Users are allowed to handle their errors by returning \"true\". If the\n// error is handled then it will not be thrown.\n//\n// Passed Error object has the following properties attached:\n//    code: Code of the error\n//    errno: Error name\n//    handle: Handle of Pipe/TCP connection.\n//    syscall: Name of the syscall that failed\n//\n// All error callbacks will be called, regardless of whether the error has\n// already been handled or not. The third argument is whether the error\n// was already handled.\nfunction fail(self, err, syscall) {\n  var handled = false;\n  var callbacks, i;\n\n  err = util._errnoException(err, syscall);\n  err.handle = self;\n\n  // Here are several errors that should only alert, and not need to be thrown.\n  if (err.code === 'ECONNRESET' ||\n      err.code === 'ECANCELED' ||\n      err.code === 'EPIPE') {\n    alert(self, err);\n    return;\n  }\n\n  // These are all the paths where onerror() callback handlers may be found.\n  if (self._onerror)\n    callbacks = self._onerror;\n  else if (self._proxy && self._proxy._onerror)\n    callbacks = self._proxy._onerror;\n  else if (self._server &&\n           self._server._proxy &&\n           self._server._proxy._onerror)\n    callbacks = self._server._proxy._onerror;\n  else if (self._return_route &&\n           self._return_route._server &&\n           self._return_route._server._proxy &&\n           self._return_route._server._proxy._onerror)\n    callbacks = self._return_route._server._proxy._onerror;\n  else\n    throw new Error('No error handlers defined');\n\n  for (i = 0; i < callbacks.length; i++)\n    handled = callbacks[i].call(self, err, handled) || handled;\n\n  if (!handled)\n    throw err;\n}\n"]}