一、开始一个node.js的WebHook的项目
相关配置DEMO
package.json
注意文件内秘钥配置为123,通过启动参数配置(Set SECRET_TOKEN=123)&& node index.js
{
"name": "webhook.v2.demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "(Set SECRET_TOKEN=123)&& node index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Coding/Webhook.v2.Demo.git"
},
"keywords": [
"Coding.net",
"Webhook"
],
"author": "wusisu <i@wusisu.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/Coding/Webhook.v2.Demo/issues"
},
"homepage": "https://github.com/Coding/Webhook.v2.Demo#readme",
"dependencies": {
"body-parser": "^1.18.2",
"crypto": "^1.0.1",
"express": "^4.16.3",
"node-cmd": "^3.0.0"
}
}
index.js
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const cmd = require('node-cmd');
const verifyWebhook = (req) => {
if (!req.headers['user-agent'].includes('Coding.net Hook')) {
return false;
}
// Compare their hmac signature to our hmac signature
// (hmac = hash-based message authentication code)
const theirSignature = req.headers['x-coding-signature'];
console.log(theirSignature);
const payload = req.body;
const secret = process.env.SECRET_TOKEN;
const ourSignature = `sha1=${crypto.createHmac('sha1', secret).update(payload).digest('hex')}`;
return crypto.timingSafeEqual(Buffer.from(theirSignature), Buffer.from(ourSignature));
};
const app = express();
app.use(bodyParser.text({ type : '*/*' }));
const notAuthorized = (req, res) => {
console.log('Someone who is NOT Coding is calling, redirect them');
res.redirect(301, '/'); // Redirect to domain root
};
const authorizationSuccessful = () => {
console.log('Coding is calling, do something here');
// TODO: Do something here
//此处执行CMD相关命令即可
cmd.get(
'notepad',//画图板
function (data) {
console.log("data")
}
);
cmd.get(
'C:\\Windows\\System32\\Calc.exe', //计算器
function (data) {
console.log("cacul")
}
);
};
app.post('*', (req, res) => {
if (verifyWebhook(req)) {
// Coding calling
authorizationSuccessful();
console.log('req', req);
console.log('res', res);
res.writeHead(200, { 'Content-Type' : 'text/plain' });
res.end('Thanks Coding <3');
} else {
// Someone else calling
notAuthorized(req, res);
}
});
app.all('*', notAuthorized); // Only webhook requests allowed at this address
app.listen(3000);
console.log('Webhook service running at http://localhost:3000');
//console.info('secret', process.env.SECRET_TOKEN);
二、在coading的项目做相关配置
URL填写你的webhook项目访问地址
秘钥填写,package.json里面配置的(如:123)
配置成功后,可以在列表页面点击“测试”。