307 lines
13 KiB
JavaScript
307 lines
13 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* gitea-mail-notify —— 把 Gitea 的 push 事件转成邮件,投递到 Mailcow 邮箱。
|
||
*
|
||
* Gitea → 仓库设置 → Web 钩子 → 添加 Web 钩子(Gitea):
|
||
* 目标 URL: http://127.0.0.1:8095/hook/<secret>
|
||
* 触发条件: 推送事件
|
||
* 数据格式: application/json
|
||
*
|
||
* 配置(环境变量或 /etc/gitea-mail-notify.json):
|
||
* port, host, secret,
|
||
* smtpHost(127.0.0.1), smtpPort(587), smtpUser, smtpPass, smtpSecure(starttls|ssl|none)
|
||
* mailFrom, mailTo, subjectPrefix
|
||
*/
|
||
import { createServer } from 'node:http'
|
||
import { connect } from 'node:net'
|
||
import { TLSSocket } from 'node:tls'
|
||
import { readFileSync, existsSync } from 'node:fs'
|
||
|
||
const CONFIG_FILE = process.env.CONFIG_FILE || '/etc/gitea-mail-notify.json'
|
||
const fileCfg = existsSync(CONFIG_FILE) ? JSON.parse(readFileSync(CONFIG_FILE, 'utf8')) : {}
|
||
const pick = (env, key, def) => process.env[env] || fileCfg[key] || def
|
||
|
||
const cfg = {
|
||
port: Number(pick('PORT', 'port', 8095)),
|
||
host: pick('HOST', 'host', '127.0.0.1'),
|
||
secret: pick('SECRET', 'secret', ''),
|
||
smtpHost: pick('SMTP_HOST', 'smtpHost', '127.0.0.1'),
|
||
smtpPort: Number(pick('SMTP_PORT', 'smtpPort', 587)),
|
||
smtpUser: pick('SMTP_USER', 'smtpUser', ''),
|
||
smtpPass: pick('SMTP_PASS', 'smtpPass', ''),
|
||
smtpSecure: pick('SMTP_SECURE', 'smtpSecure', 'starttls'), // starttls | ssl | none
|
||
mailFrom: pick('MAIL_FROM', 'mailFrom', 'gitea@localhost'),
|
||
mailTo: String(pick('MAIL_TO', 'mailTo', 'gitea@localhost')).split(',').map((s) => s.trim()).filter(Boolean),
|
||
prefix: pick('SUBJECT_PREFIX', 'subjectPrefix', '[Gitea]'),
|
||
}
|
||
|
||
if (!cfg.secret) {
|
||
console.error('[fatal] 缺少 secret:写进 /etc/gitea-mail-notify.json 或设 SECRET')
|
||
process.exit(1)
|
||
}
|
||
|
||
const log = (...a) => console.log(new Date().toISOString(), ...a)
|
||
|
||
/* ============ 极简 SMTP 客户端(支持 starttls / ssl / 明文 + AUTH LOGIN) ============ */
|
||
class Smtp {
|
||
constructor() {
|
||
this.buf = ''
|
||
this.waiter = null
|
||
}
|
||
|
||
async connect() {
|
||
await new Promise((resolve, reject) => {
|
||
const onErr = (e) => { reject(e) }
|
||
this.raw = connect({ host: cfg.smtpHost, port: cfg.smtpPort })
|
||
this.raw.once('error', onErr)
|
||
this.raw.once('connect', () => { this.raw.removeListener('error', onErr); resolve() })
|
||
})
|
||
this.raw.setEncoding('utf8')
|
||
this.raw.setTimeout(20000, () => this.fail(new Error('SMTP 空闲超时')))
|
||
this.raw.on('data', (c) => this.onData(c))
|
||
this.raw.on('error', (e) => this.fail(e))
|
||
this.raw.on('close', () => this.fail(new Error('SMTP 连接被关闭')))
|
||
|
||
if (cfg.smtpSecure === 'ssl') {
|
||
const plain = this.raw
|
||
this.raw = new TLSSocket(plain, { rejectUnauthorized: false, servername: cfg.smtpHost })
|
||
this.raw.setEncoding('utf8')
|
||
this.raw.on('data', (c) => this.onData(c))
|
||
this.raw.on('error', (e) => this.fail(e))
|
||
this.raw.on('close', () => this.fail(new Error('SMTP 连接被关闭')))
|
||
}
|
||
|
||
await this.expect(220)
|
||
const ehlo = await this.cmd(`EHLO gitea-mail-notify`, 250)
|
||
|
||
if (cfg.smtpSecure === 'starttls') {
|
||
if (!/STARTTLS/i.test(ehlo)) throw new Error('服务器不支持 STARTTLS')
|
||
await this.cmd('STARTTLS', 220)
|
||
const plain = this.raw
|
||
this.raw = new TLSSocket(plain, { rejectUnauthorized: false, servername: cfg.smtpHost })
|
||
this.raw.setEncoding('utf8')
|
||
this.raw.on('data', (c) => this.onData(c))
|
||
this.raw.on('error', (e) => this.fail(e))
|
||
this.raw.on('close', () => this.fail(new Error('SMTP 连接被关闭')))
|
||
this.buf = ''
|
||
await this.cmd('EHLO gitea-mail-notify', 250)
|
||
}
|
||
|
||
if (cfg.smtpUser) {
|
||
await this.cmd('AUTH LOGIN', 334)
|
||
await this.cmd(Buffer.from(cfg.smtpUser).toString('base64'), 334)
|
||
await this.cmd(Buffer.from(cfg.smtpPass).toString('base64'), 235)
|
||
}
|
||
}
|
||
|
||
onData(chunk) {
|
||
this.buf += chunk
|
||
const lines = []
|
||
while (true) {
|
||
const i = this.buf.indexOf('\r\n')
|
||
if (i < 0) break
|
||
lines.push(this.buf.slice(0, i))
|
||
this.buf = this.buf.slice(i + 2)
|
||
}
|
||
if (!lines.length) return
|
||
// 多行响应的最后一行为 "250 xxx",前面的都是 "250-xxx"
|
||
const last = lines[lines.length - 1]
|
||
if (/^\d{3}-/.test(last)) return // 还没结束,继续等
|
||
this.lastCode = Number(last.slice(0, 3))
|
||
this.lastText = lines.join('\n')
|
||
const w = this.waiter
|
||
this.waiter = null
|
||
if (w) w.resolve(this.lastText)
|
||
}
|
||
|
||
fail(err) {
|
||
const w = this.waiter
|
||
this.waiter = null
|
||
if (w) w.reject(err)
|
||
}
|
||
|
||
expect(code) {
|
||
return new Promise((resolve, reject) => {
|
||
this.waiter = { resolve: (text) => (this.lastCode === code ? resolve(text) : reject(new Error(`期望 ${code},收到 ${this.lastCode}:${text}`))), reject }
|
||
})
|
||
}
|
||
|
||
async cmd(line, code) {
|
||
const p = this.expect(code)
|
||
this.raw.write(line + '\r\n')
|
||
return p
|
||
}
|
||
|
||
async sendMail({ from, to, data }) {
|
||
await this.cmd(`MAIL FROM:<${from}>`, 250)
|
||
for (const rcpt of to) await this.cmd(`RCPT TO:<${rcpt}>`, 250)
|
||
await this.cmd('DATA', 354)
|
||
const p = this.expect(250)
|
||
this.raw.write(data.replace(/\r?\n/g, '\r\n') + '\r\n.\r\n')
|
||
await p
|
||
await this.cmd('QUIT', 221).catch(() => {})
|
||
this.raw.end()
|
||
}
|
||
}
|
||
|
||
/* ============ 邮件内容 ============ */
|
||
const esc = (s = '') => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))
|
||
const sha = (s = '') => String(s).slice(0, 7)
|
||
const branchOf = (ref = '') => String(ref).replace('refs/heads/', '').replace('refs/tags/', '')
|
||
const trim = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s)
|
||
const wrap76 = (b64) => b64.replace(/(.{76})/g, '$1\r\n')
|
||
const encodeHeader = (s) => (/^[\x20-\x7e]*$/.test(s) ? s : '=?UTF-8?B?' + Buffer.from(s, 'utf8').toString('base64') + '?=')
|
||
|
||
function buildMail(payload) {
|
||
const repo = payload.repository || {}
|
||
const repoName = repo.full_name || repo.name || 'unknown/repo'
|
||
const branch = branchOf(payload.ref)
|
||
const commits = Array.isArray(payload.commits) ? payload.commits : []
|
||
const pusher = (payload.pusher && (payload.pusher.login || payload.pusher.username)) || 'someone'
|
||
const isTag = String(payload.ref || '').startsWith('refs/tags/')
|
||
const head = commits[commits.length - 1] || {}
|
||
const firstLine = (head.message || '').split('\n')[0] || (isTag ? '新标签 ' + branch : '更新')
|
||
const subject = `${cfg.prefix} ${repoName} · ${pusher} → ${branch}:${commits.length || 1} 个提交 · ${trim(firstLine, 50)}`
|
||
const compareUrl = payload.compare_url || (repo.html_url ? `${repo.html_url}/commits/${branch}` : '')
|
||
|
||
const text = [
|
||
`${repoName} 有新提交`,
|
||
'',
|
||
`推送人:${pusher}`,
|
||
`分支:${branch}${isTag ? '(标签)' : ''}`,
|
||
`提交数:${commits.length}`,
|
||
compareUrl ? `对比:${compareUrl}` : '',
|
||
'',
|
||
...commits.map((c) => {
|
||
const msg = (c.message || '').split('\n')[0]
|
||
const who = (c.author && (c.author.name || c.author.username)) || ''
|
||
return `- ${sha(c.id)} ${msg}${who ? ' —— ' + who : ''}\n ${c.url || ''}`
|
||
}),
|
||
'',
|
||
'—— 由 gitea-mail-notify 自动发送',
|
||
].filter((x) => x !== '').join('\n')
|
||
|
||
const rows = commits.map((c) => {
|
||
const files = [].concat(c.added || [], c.removed || [], c.modified || [])
|
||
return `<tr>
|
||
<td style="padding:8px 10px;border-bottom:1px solid #eef1f6;font-family:ui-monospace,Menlo,monospace;font-size:13px;white-space:nowrap">
|
||
<a href="${esc(c.url)}" style="color:#3a67f0;text-decoration:none">${sha(esc(c.id))}</a></td>
|
||
<td style="padding:8px 10px;border-bottom:1px solid #eef1f6;font-size:14px;color:#1a2035">${esc((c.message || '').split('\n')[0])}</td>
|
||
<td style="padding:8px 10px;border-bottom:1px solid #eef1f6;font-size:12px;color:#6b7893;white-space:nowrap">${esc((c.author && (c.author.name || c.author.username)) || '')}</td>
|
||
<td style="padding:8px 10px;border-bottom:1px solid #eef1f6;font-size:12px;color:#6b7893;white-space:nowrap">${files.length} 个文件</td>
|
||
</tr>`
|
||
}).join('')
|
||
|
||
const html = `<!doctype html><html><body style="margin:0;padding:24px;background:#f4f6fb;font-family:-apple-system,'Segoe UI',Roboto,'PingFang SC','Microsoft YaHei',sans-serif">
|
||
<div style="max-width:680px;margin:0 auto;background:#fff;border-radius:14px;overflow:hidden;border:1px solid #e6e9f0">
|
||
<div style="padding:18px 22px;background:linear-gradient(120deg,#3a67f0,#0c9fb2);color:#fff">
|
||
<div style="font-size:11px;letter-spacing:.16em;opacity:.85">GITEA · 仓库更新</div>
|
||
<div style="font-size:20px;font-weight:700;margin-top:6px">${esc(repoName)}</div>
|
||
<div style="font-size:13px;opacity:.92;margin-top:4px">${esc(pusher)} 推送到 <b>${esc(branch)}</b>${isTag ? '(标签)' : ''} · ${commits.length} 个提交</div>
|
||
</div>
|
||
<table style="width:100%;border-collapse:collapse">
|
||
<thead><tr style="background:#f9fafc">
|
||
<th align="left" style="padding:10px;font-size:12px;color:#6b7893">提交</th>
|
||
<th align="left" style="padding:10px;font-size:12px;color:#6b7893">说明</th>
|
||
<th align="left" style="padding:10px;font-size:12px;color:#6b7893">作者</th>
|
||
<th align="left" style="padding:10px;font-size:12px;color:#6b7893">改动</th>
|
||
</tr></thead>
|
||
<tbody>${rows || '<tr><td colspan="4" style="padding:14px;color:#6b7893">没有提交明细</td></tr>'}</tbody>
|
||
</table>
|
||
<div style="padding:16px 22px">
|
||
${compareUrl ? `<a href="${esc(compareUrl)}" style="display:inline-block;padding:9px 16px;background:#3a67f0;color:#fff;border-radius:8px;text-decoration:none;font-size:13px">看这次改动</a>` : ''}
|
||
<p style="font-size:12px;color:#a0aec0;margin:14px 0 0">这封邮件由 gitea-mail-notify 自动发出。</p>
|
||
</div>
|
||
</div></body></html>`
|
||
|
||
const boundary = 'gmn_' + Date.now().toString(36)
|
||
const mime = [
|
||
`From: ${cfg.mailFrom}`,
|
||
`To: ${cfg.mailTo.join(', ')}`,
|
||
`Subject: ${encodeHeader(subject)}`,
|
||
'MIME-Version: 1.0',
|
||
`Date: ${new Date().toUTCString()}`,
|
||
`Message-ID: <${Date.now()}.${Math.random().toString(36).slice(2)}@gitea-mail-notify>`,
|
||
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
||
'',
|
||
`--${boundary}`,
|
||
'Content-Type: text/plain; charset=utf-8',
|
||
'Content-Transfer-Encoding: base64',
|
||
'',
|
||
wrap76(Buffer.from(text, 'utf8').toString('base64')),
|
||
`--${boundary}`,
|
||
'Content-Type: text/html; charset=utf-8',
|
||
'Content-Transfer-Encoding: base64',
|
||
'',
|
||
wrap76(Buffer.from(html, 'utf8').toString('base64')),
|
||
`--${boundary}--`,
|
||
'',
|
||
].join('\r\n')
|
||
|
||
return { subject, mime }
|
||
}
|
||
|
||
/* ============ 发送队列 ============ */
|
||
const queue = []
|
||
let busy = false
|
||
let sent = 0
|
||
let failed = 0
|
||
|
||
async function drain() {
|
||
if (busy) return
|
||
busy = true
|
||
while (queue.length) {
|
||
const job = queue.shift()
|
||
try {
|
||
const smtp = new Smtp()
|
||
await smtp.connect()
|
||
await smtp.sendMail({ from: cfg.mailFrom, to: cfg.mailTo, data: job.mime })
|
||
sent++
|
||
log('sent', job.subject)
|
||
} catch (err) {
|
||
failed++
|
||
log('send failed:', err.message)
|
||
}
|
||
}
|
||
busy = false
|
||
}
|
||
|
||
/* ============ HTTP ============ */
|
||
const server = createServer((req, res) => {
|
||
const url = new URL(req.url, 'http://localhost')
|
||
const json = (code, obj) => { res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(obj)) }
|
||
|
||
if (req.method === 'GET' && url.pathname === '/health') {
|
||
return json(200, { ok: true, sent, failed, queued: queue.length, mailFrom: cfg.mailFrom, mailTo: cfg.mailTo, smtp: `${cfg.smtpHost}:${cfg.smtpPort}/${cfg.smtpSecure}` })
|
||
}
|
||
|
||
if (req.method === 'POST' && url.pathname.startsWith('/hook/')) {
|
||
if (url.pathname.slice(6) !== cfg.secret) return json(403, { ok: false, error: 'bad token' })
|
||
let size = 0
|
||
const chunks = []
|
||
req.on('data', (c) => {
|
||
size += c.length
|
||
if (size > 2 * 1024 * 1024) { req.destroy(); return }
|
||
chunks.push(c)
|
||
})
|
||
req.on('end', () => {
|
||
let payload
|
||
try { payload = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return json(400, { ok: false, error: 'bad json' }) }
|
||
const event = req.headers['x-gitea-event'] || 'push'
|
||
if (event !== 'push') return json(200, { ok: true, ignored: event })
|
||
if (!payload.commits || !payload.commits.length) return json(200, { ok: true, ignored: 'empty push' })
|
||
const mail = buildMail(payload)
|
||
queue.push(mail)
|
||
json(200, { ok: true, queued: queue.length, subject: mail.subject })
|
||
drain()
|
||
})
|
||
return
|
||
}
|
||
|
||
json(404, { ok: false })
|
||
})
|
||
|
||
server.listen(cfg.port, cfg.host, () => {
|
||
log(`listening http://${cfg.host}:${cfg.port} · smtp ${cfg.smtpHost}:${cfg.smtpPort}/${cfg.smtpSecure} · ${cfg.mailFrom} → ${cfg.mailTo.join(', ')}`)
|
||
})
|