Programming/node.js2019. 4. 10. 17:01

node.js 10.x 부터 지원하는 녀석으로(native support)

recursive 옵션을 주고 mkdir 하는게 가장 깔끔할 듯

fs.mkdirSync(targetDir, { recursive: true });

 

[링크 : https://nodejs.org/api/fs.html#fs_fs_mkdirsync_path_options]

[링크 : https://www.npmjs.com/package/mkdirp]

[링크 : https://github.com/shelljs/shelljs]

    [링크 : https://stackoverflow.com/questions/31645738/how-to-create-full-path-with-nodes-fs-mkdirsync]

Posted by 구차니
Programming/node.js2019. 4. 8. 14:28

프록시 설정에서 3128로 모두 처리하도록 하고(http, https 모두 3128 포트)

자동 생성된 인증서를 x509 타입으로 바꾸어서 윈도우에 믿을수 있는 root CA로 등록하면 해결 (HSTS 문제 우회)

$ cd ./.http-mitm-proxy/certs/ca.pem
$ openssl x509 -outform der -in ca.pem -out der.pem

 

아무튼 아래와 같이 하면.. 데이터는 어쩔수 없지만 HTML 등은 볼 수 있을 듯

var Proxy = require('http-mitm-proxy');
var proxy = Proxy();
var path = require('path');

proxy.use(Proxy.wildcard);

proxy.onError(function(ctx, err) {
  console.error('proxy error:', err);
});

proxy.onRequest(function(ctx, callback) {
 {
    ctx.use(Proxy.gunzip);
console.log('');
console.log(ctx.clientToProxyRequest.headers.host);
console.log(ctx.clientToProxyRequest.url);

    ctx.onResponseData(function(ctx, chunk, callback) {
//     chunk = new Buffer(chunk.toString().replace(/<span.*?<\/span>/g, '<span>Pwned!</span>'));

      return callback(null, chunk);
    });
  }
  return callback();
});


proxy.onResponse(function(ctx, callback) {
 return callback();
 });

proxy.onResponseData(function(ctx, chunk, callback) {
console.log(chunk.length);
console.log(chunk.toString());
 return callback(null, chunk);
 });

proxy.onCertificateRequired = function(hostname, callback) {
  return callback(null, {
    keyFile: path.resolve('/ca/certs/', hostname + '.key'),
    certFile: path.resolve('/ca/certs/', hostname + '.crt')
  });
};
proxy.listen({port: 3128});

[링크 : https://www.npmjs.com/package/http-mitm-proxy]

 

+

var Proxy = require('http-mitm-proxy');
var proxy = Proxy();
var path = require('path');
var url = require('url');
var { URLSearchParams } = require('url');
var decode = require('urldecode')

proxy.use(Proxy.wildcard);

proxy.onError(function(ctx, err) {
  console.error('proxy error:', err);
});

proxy.onRequest(function(ctx, callback) {
 {
    ctx.use(Proxy.gunzip);
    console.log(ctx.clientToProxyRequest.headers.host);

    var pback = ctx.clientToProxyRequest.url;
    console.log(ctx.clientToProxyRequest.url);

    var params = new URLSearchParams(url.parse(pback).query);
    params.sort();
    console.log(url.parse(pback).pathname + '?' + decode(params.toString()));

    ctx.onResponseData(function(ctx, chunk, callback) {
//     chunk = new Buffer(chunk.toString().replace(/<span.*?<\/span>/g, '<span>Pwned!</span>'));

      return callback(null, chunk);
    });
  }
  return callback();
});


proxy.onResponse(function(ctx, callback) {
 return callback();
 });

proxy.onResponseData(function(ctx, chunk, callback) {
 return callback(null, chunk);
 });

proxy.onCertificateRequired = function(hostname, callback) {
  return callback(null, {
    keyFile: path.resolve('/ca/certs/', hostname + '.key'),
    certFile: path.resolve('/ca/certs/', hostname + '.crt')
  });
};
proxy.listen({port: 3128});

 

[링크 : https://nodejs.org/docs/latest-v8.x/api/url.html]

[링크 : https://www.npmjs.com/package/urldecode]

[링크 : https://opentutorials.org/module/938/7369]

Posted by 구차니
Programming/node.js2019. 4. 5. 15:08

머.. 별건 아니고(?)

path 모듈에서 fs 모듈로 변경되어서 에러난 놈을 열어보고 모듈을 바꾸어주면 일단 ok 인듯?

(만약 그거 하나만 문제라면..)

 

[링크 : https://github.com/horaci/node-mitm-proxy]

'Programming > node.js' 카테고리의 다른 글

node.js mkdir -p 옵션 사용하기  (0) 2019.04.10
http-mitm-proxy 예제  (0) 2019.04.08
node.js mitm proxy (for https)  (0) 2019.04.02
proxy http node.js  (0) 2019.04.01
TypeError: Converting circular structure to JSON  (0) 2019.03.27
Posted by 구차니
Programming/node.js2019. 4. 2. 16:32

NodeMITMProxyCA 라는녀석이 생성되서 찾아보니 아래의 경로에 생성을 한다.

흐음.. 서비스 용으로 만들려면 이 이름을 어떻게 바꿔치워야 겠네? ㅠㅠ

./.http-mitm-proxy/certs/ca.pem
./.http-mitm-proxy/keys/ca.private.key
./.http-mitm-proxy/keys/ca.public.key

[링크 : https://github.com/greim/hoxy]

[링크 : https://stackoverflow.com/questions/10085082/node-http-proxy-ssl-transparent]

[링크 : https://github.com/TotallyInformation/node-proxy-https-example/blob/master/proxy.js]

[링크 : https://www.npmjs.com/package/http-mitm-proxy]

 

 

아래는 span 에 들어있는 내용을 죄다 Pwned로 바꿔치기 하는 기본 예제를 변형한 녀석

 

var Proxy = require('http-mitm-proxy');
var proxy = Proxy();
var path = require('path');

proxy.use(Proxy.wildcard);

proxy.onError(function(ctx, err) {
  console.error('proxy error:', err);
});

proxy.onRequest(function(ctx, callback) {
//  if (ctx.clientToProxyRequest.headers.host == 'www.google.com'
//    && ctx.clientToProxyRequest.url.indexOf('/search') == 0
//    )
 {
    ctx.use(Proxy.gunzip);

    ctx.onResponseData(function(ctx, chunk, callback) {
//      chunk = new Buffer(chunk.toString().replace(/<h3.*?<\/h3>/g, '<h3>Pwned!</h3>'));
        console.log(chunk.toString());
      chunk = new Buffer(chunk.toString().replace(/<span.*?<\/span>/g, '<span>Pwned!</span>'));
      return callback(null, chunk);
    });
  }
  return callback();
});

proxy.onRequestData(function(ctx, chunk, callback) {
  console.log('REQUEST DATA:', chunk.toString());
  return callback(null, chunk);
});

/*
proxy.onCertificateRequired = function(hostname, callback) {
  return callback(null, {
    keyFile: path.resolve('key.pem'),
    certFile: path.resolve('cert.pem'),
    hosts: ["*"]
  });
};
*/
proxy.listen({port: 8080});

 

사용자가 생성한 인증서를 이용하여 서비스하기

[링크 : http://blog.saltfactory.net/implements-nodejs-based-https-server/]

var Proxy = require('http-mitm-proxy');
var proxy = Proxy();
var path = require('path');

proxy.use(Proxy.wildcard);

proxy.onError(function(ctx, err) {
  console.error('proxy error:', err);
});

proxy.onRequest(function(ctx, callback) {
 {
    ctx.use(Proxy.gunzip);

    ctx.onResponseData(function(ctx, chunk, callback) {
      chunk = new Buffer(chunk.toString().replace(/<span.*?<\/span>/g, '<span>Pwned!</span>'));
      return callback(null, chunk);
    });
  }
  return callback();
});

proxy.onCertificateRequired = function(hostname, callback) {
  return callback(null, {
    keyFile: path.resolve('key.pem'),
    certFile: path.resolve('cert.pem'),
    hosts: ["*.mydomain.com"]
  });
};
proxy.listen({port: 8080});

[링크 : https://github.com/horaci/node-mitm-proxy]

[링크 : https://www.npmjs.com/package/mitm-proxy]

Posted by 구차니
Programming/node.js2019. 4. 1. 10:26

http proxy는 어떻게 보면 특수한 용도의 http 서버일 뿐인데..

http.agent를 써야 하냐 말아야 하냐.. 헷갈리네

 

http는 agent 없어도 proxy 설정하면 받아들이긴 하는데..

https는 http.agent를 통해 socket으로 돌려주는 편이라 어떻게 해야 하지?

 

[링크 : https://stackoverflow.com/questions/20351637/how-to-create-a-simple-http-proxy-in-node-js]

[링크 : https://nodejs.org/api/http.html]

[링크 : https://nodejs.org/api/http.html#http_request_end_data_encoding_callback]

Posted by 구차니
Programming/node.js2019. 3. 27. 18:05

JSON.stringify() 를 하면 위와 같은 에러를 내면서 죽길래

해결책을 찾는데 circular-json 이라는 다른 패키지를 깔아서 써야 한다.

 

[링크 : https://zetawiki.com/wiki/TypeError:_Converting_circular_structure_to_JSON]

[링크 : https://zetawiki.com/wiki/Npm_circular-json]

 

진짜인진 모르겠지만 객체 내에 순환참조가 있음 그렇게 죽는다고..

[링크 : https://ohgyun.com/399]

'Programming > node.js' 카테고리의 다른 글

node.js mitm proxy (for https)  (0) 2019.04.02
proxy http node.js  (0) 2019.04.01
https proxy using node.js  (0) 2019.03.27
node.js unit test  (0) 2019.03.25
node.js http cache proxy  (0) 2019.03.20
Posted by 구차니
Programming/node.js2019. 3. 27. 17:38

stack의 것은.. 되긴 하는데 단순하게(?) https의 경우 소켓을 통해 바로 연결되는 구조로 되어있다.

http나 https 확실히 무언가 한번 걸린다는 느낌이 드는 딜레이는 어쩔수 없을려나?

 

아무튼 내가 원한건.. 얘가 아니라 직접 URL을 잡아낼수 있어야 하는 녀석... ㅠㅠ

 

// Install npm dependencies first
// npm init
// npm install --save url@0.10.3
// npm install --save http-proxy@1.11.1

var httpProxy = require("http-proxy");
var http = require("http");
var url = require("url");
var net = require('net');

var server = http.createServer(function (req, res) {
var urlObj = url.parse(req.url);
var target = urlObj.protocol + "//" + urlObj.host;

console.log("Proxy HTTP request for:", target);

var proxy = httpProxy.createProxyServer({});
proxy.on("error", function (err, req, res) {
console.log("proxy error", err);
res.end();
});

proxy.web(req, res, {target: target});
}).listen(8080); //this is the port your clients will connect to

var regex_hostport = /^([^:]+)(:([0-9]+))?$/;

var getHostPortFromString = function (hostString, defaultPort) {
var host = hostString;
var port = defaultPort;

var result = regex_hostport.exec(hostString);
if (result != null) {
host = result[1];
if (result[2] != null) {
port = result[3];
}
}

return ( [host, port] );
};

server.addListener('connect', function (req, socket, bodyhead) {
var hostPort = getHostPortFromString(req.url, 443);
var hostDomain = hostPort[0];
var port = parseInt(hostPort[1]);
console.log("Proxying HTTPS request for:", hostDomain, port);

var proxySocket = new net.Socket();
proxySocket.connect(port, hostDomain, function () {
proxySocket.write(bodyhead);
socket.write("HTTP/" + req.httpVersion + " 200 Connection established\r\n\r\n");
}
);

proxySocket.on('data', function (chunk) {
socket.write(chunk);
});

proxySocket.on('end', function () {
socket.end();
});

proxySocket.on('error', function () {
socket.write("HTTP/" + req.httpVersion + " 500 Connection error\r\n\r\n");
socket.end();
});

socket.on('data', function (chunk) {
proxySocket.write(chunk);
});

socket.on('end', function () {
proxySocket.end();
});

socket.on('error', function () {
proxySocket.end();
});

});


[링크 : 
https://stackoverflow.com/questions/8165570/https-proxy-server-in-node-js/32104777]

[링크 : https://www.npmjs.com/package/httpp-proxy]

 

이거랑 위에꺼랑 어떻게 믹스하지? ㅠㅠ

[링크 : http://blog.saltfactory.net/implements-nodejs-based-https-server/]

 

+

2019.04.02

취향대로 좀 정리한 버전

var http = require('http');
var httpProxy = require('http-proxy');
var url = require('url');
var net = require('net');

var server = http.createServer(onReq);
server.addListener('connect', onConn);
server.listen(8080);

function onReq(req, res)
{
        var urlObj = url.parse(req.url);
        var target = urlObj.protocol + "//" + urlObj.host;
        console.log(urlObj.href);

        var proxy = httpProxy.createProxyServer({});
        proxy.on("error", function (err, req, res) {
                console.log("proxy error", err);
                res.end();
        });

        proxy.web(req, res, {target: target});
}

function onConn(req, socket, bodyhead)
{
        var hostPort = getHostPortFromString(req.url, 443);
        var hostDomain = hostPort[0];
        var port = parseInt(hostPort[1]);
        console.log("Proxying HTTPS request for:", hostDomain, port);

        var proxySocket = new net.Socket();
        proxySocket.connect(port, hostDomain, function () {
                proxySocket.write(bodyhead);
                socket.write("HTTP/" + req.httpVersion + " 200 Connection established\r\n\r\n");
        });

        proxySocket.on('data', function (chunk) {
                //console.log(chunk.toString());
                socket.write(chunk);
        });

        proxySocket.on('end', function () {
                socket.end();
        });

        proxySocket.on('error', function () {
                socket.write("HTTP/" + req.httpVersion + " 500 Connection error\r\n\r\n");
                socket.end();
        });

        socket.on('data', function (chunk) {
                //console.log(chunk.toString());
                proxySocket.write(chunk);
        });

        socket.on('end', function () {
                proxySocket.end();
        });

        socket.on('error', function () {
                proxySocket.end();
        });
}

{
}

var regex_hostport = /^([^:]+)(:([0-9]+))?$/;

var getHostPortFromString = function (hostString, defaultPort)
{
        var host = hostString;
        var port = defaultPort;
        var result = regex_hostport.exec(hostString);
        if (result != null)
        {
                host = result[1];
                 if (result[2] != null) { port = result[3]; }
        }
        return ( [host, port] );
};

'Programming > node.js' 카테고리의 다른 글

proxy http node.js  (0) 2019.04.01
TypeError: Converting circular structure to JSON  (0) 2019.03.27
node.js unit test  (0) 2019.03.25
node.js http cache proxy  (0) 2019.03.20
node.js 사용자 모듈 만들기  (0) 2019.03.13
Posted by 구차니
Programming/node.js2019. 3. 25. 19:01

mocha 패키지

CUnit이니 JUnit 이니 듣긴했는데 안써봐서..

그래도 한번 서버 어플리케이션을 만드니 써봐야겠...지? ㅠㅠ


[링크 : https://www.npmjs.com/package/mocha]

[링크 : https://mochajs.org/#getting-started]

[링크 : http://blog.jeonghwan.net/mocha/]

[링크 : https://blog.outsider.ne.kr/770]

[링크 : http://webframeworks.kr/tutorials/expressjs/expressjs_test_code/]

'Programming > node.js' 카테고리의 다른 글

TypeError: Converting circular structure to JSON  (0) 2019.03.27
https proxy using node.js  (0) 2019.03.27
node.js http cache proxy  (0) 2019.03.20
node.js 사용자 모듈 만들기  (0) 2019.03.13
ckeditor 와 php, node.js 연동  (0) 2019.03.11
Posted by 구차니
Programming/node.js2019. 3. 20. 18:54

squid 프록시 설정 만지다가 빡쳐서

어짜피 프록시 HTTP 서버라던가 이런걸텐데 그럼 단순(?)하게

HTTP 서버로 구성해서 해당 URL을 파싱 해서

로컬 캐시에 없으면 요청하고 저장후 전달해주면 되는거 아냐? 라는 생각에 검색해보니 똭!


[링크 : https://www.npmjs.com/package/caching-proxy]


'Programming > node.js' 카테고리의 다른 글

https proxy using node.js  (0) 2019.03.27
node.js unit test  (0) 2019.03.25
node.js 사용자 모듈 만들기  (0) 2019.03.13
ckeditor 와 php, node.js 연동  (0) 2019.03.11
floala 에디터 + node.js  (0) 2019.03.08
Posted by 구차니
Programming/node.js2019. 3. 13. 13:47

전에 적었나? 기억 안나니 다시 씀


express를 쓰다 보면 가장 마지막 줄에

module.exports = router; 

요런게 보이는데 모듈로 정의해주는 녀석이다.


여러가지 방법들이 보이는데, 취향대로 쓰면 될 듯

(개인적으로는 작성하고 모듈로 변환하는 쪽이라서 가장 아래꺼를 주로 쓰게 될 듯)

export.func_name = function () {}


module.exports = {

   funcname : function() {}

};


function funcname() {};

module.exports = {

   funcname : funcname

}; 


[링크 : https://hongku.tistory.com/92]

[링크 : https://winmargo.tistory.com/173] DAO

[링크 : https://jiwondh.github.io/2017/01/17/create-module/]

[링크 : https://doitnow-man.tistory.com/161]

'Programming > node.js' 카테고리의 다른 글

node.js unit test  (0) 2019.03.25
node.js http cache proxy  (0) 2019.03.20
ckeditor 와 php, node.js 연동  (0) 2019.03.11
floala 에디터 + node.js  (0) 2019.03.08
wysiwyg editor / node.js  (0) 2019.02.26
Posted by 구차니