-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
155 lines (125 loc) · 5.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
const { EmbedBuilder, WebhookClient } = require('discord.js');
const Gravatar = require('./utils/gravatar');
const path = require('path');
const express = require('express');
const pino = require('pino');
const fs = require('fs');
let configPath = '/home/container/config.json';
if (fs.existsSync(path.join(__dirname, 'config.json')))
configPath = path.join(__dirname, 'config.json');
const { port, tokens } = require(configPath);
const maskSensitiveInfo = (value) => {
if (!value)
return value;
if (value.length <= 6)
return value;
return value.slice(0, -6) + '*******';
}
const logger = pino({
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'SYS:standard',
ignore: 'pid,hostname',
customColors: 'info:blue,warn:yellow,error:red'
}
}
});
const HEADER = `
██████╗ ██╗████████╗██╗ █████╗ ██████╗ ███╗ ███╗ ██████╗ ███╗ ██╗██╗████████╗ ██████╗ ██████╗
██╔════╝ ██║╚══██╔══╝██║ ██╔══██╗██╔══██╗ ████╗ ████║██╔═══██╗████╗ ██║██║╚══██╔══╝██╔═══██╗██╔══██╗
██║ ███╗██║ ██║ ██║ ███████║██████╔╝ ██╔████╔██║██║ ██║██╔██╗ ██║██║ ██║ ██║ ██║██████╔╝
██║ ██║██║ ██║ ██║ ██╔══██║██╔══██╗ ██║╚██╔╝██║██║ ██║██║╚██╗██║██║ ██║ ██║ ██║██╔══██╗
╚██████╔╝██║ ██║ ███████╗██║ ██║██████╔╝ ██║ ╚═╝ ██║╚██████╔╝██║ ╚████║██║ ██║ ╚██████╔╝██║ ██║
╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
`;
const MAX_DESCRIPTION_LENGTH = 2000;
const app = express();
app.use(express.json());
const EMOJIS = {
success: '✅',
error: '❌',
warning: '⚠️',
webhook: '🔗',
server: '🖥️',
event: '📡'
};
function verifyGitLabWebhook(req, res, next) {
const signature = req.get('X-Gitlab-Token');
if (!(signature in tokens)) {
logger.error(
`${EMOJIS.error} Unauthorized Access Attempt!
- IP: ${req.ip}
- Method: ${req.method}
- Path: ${req.path}
- Invalid GitLab Token: ${maskSensitiveInfo(signature) || 'No token provided'}`
);
return res.status(401).send('Unauthorized');
}
res.discordWebhooks = tokens[signature];
logger.info(
`${EMOJIS.webhook} GitLab Webhook Verified
- Token: ${maskSensitiveInfo(signature)}
- Connected Discord Webhooks: ${res.discordWebhooks.map(maskSensitiveInfo)}`
);
next();
}
app.post('/webhook', verifyGitLabWebhook, async (req, res) => {
const payload = req.body;
const objectKind = payload.object_kind;
logger.info(
`${EMOJIS.event} GitLab Event Received
- Type: ${objectKind}
- Project: ${payload.project?.name || 'Unknown'}
- Sender: ${payload.user_name || 'Unknown User'}`
);
if (objectKind === "build" || objectKind === "deployment") {
logger.warn(`${EMOJIS.warning} Skipping event: ${objectKind}`);
return;
}
try {
const event = (objectKind === "tag_push" || objectKind === "push") ? "push_tag" : objectKind;
const handlerPath = path.join(__dirname, 'endpoints', `${event.toLowerCase()}.js`);
const { eventHandler } = require(handlerPath);
const embedData = await eventHandler(payload);
const embed = new EmbedBuilder()
.setAuthor({ name: embedData.username, iconURL: Gravatar.getGravatarUrl(embedData.email) })
.setFooter({ text: payload.project.name })
.setColor("#237feb")
.setTimestamp()
.setTitle(embedData.title)
.setURL(embedData.url);
if (embedData.fields && embedData.fields.length > 0)
embed.setFields(embedData.fields);
if (embedData.description && (embedData.description.length > 0 && embedData.description.length < MAX_DESCRIPTION_LENGTH))
embed.setDescription(embedData.description);
for (const webhook of res.discordWebhooks) {
const webhookClient = new WebhookClient({ url: webhook });
await webhookClient.send({ embeds: [embed] });
logger.info(
`${EMOJIS.success} Discord Webhook Dispatch
- Destination: ${maskSensitiveInfo(new URL(webhook).hostname)}
- Event Type: ${objectKind}`
);
}
res.sendStatus(200);
} catch (error) {
logger.error(
`${EMOJIS.error} Event Processing Error
- Event Type: ${objectKind}
- Error Message: ${error.message}
- Stack Trace: ${error.stack}`
);
res.status(500).send('Internal Server Error');
}
});
app.listen(port, () => {
console.log(HEADER);
logger.info(
`${EMOJIS.server} GitLab Webhook Monitor Initialized
- Listening Port: ${port}
- Configured Tokens: ${maskSensitiveInfo(Object.keys(tokens).join(', '))}`
);
});
module.exports = { app, maskSensitiveInfo };