chore: CRM-NEW baseline

This commit is contained in:
wangliang
2026-10-23 10:35:28 +08:00
commit aa499f6dbf
111 changed files with 15126 additions and 0 deletions
+118
View File
@@ -0,0 +1,118 @@
'use strict';
/**
* IMAP ID 注入代理(专治 163 "Unsafe Login")
*
* 背景:LibreDesk 的 go-imap 客户端不发 IMAP ID 命令,163 会在 SELECT 时返回
* "NO SELECT Unsafe Login",导致邮箱无法收取。
*
* 本代理:明文监听 1993,TLS 连接上游 imap.163.com:993;
* 在客户端发 SELECT/EXAMINE 之前,自动发送一条 ID 命令并吞掉它的响应。
* 仅用于本地/内网 POC,不要在公网暴露。
*/
const net = require('net');
const tls = require('tls');
const LISTEN_PORT = Number(process.env.LISTEN_PORT || 1993);
const UPSTREAM_HOST = process.env.UPSTREAM_HOST || 'imap.163.com';
const UPSTREAM_PORT = Number(process.env.UPSTREAM_PORT || 993);
const ID_LINE = process.env.ID_LINE || '("name" "libredesk" "version" "2.9" "vendor" "libredesk")';
let connSeq = 0;
function log(...args) {
console.log(new Date().toISOString(), '[imap-id-proxy]', ...args);
}
function pipeLineSplitter(onLine) {
let buf = '';
return {
push(chunk) {
buf += chunk.toString('latin1');
let idx;
while ((idx = buf.indexOf('\r\n')) >= 0) {
const line = buf.slice(0, idx);
buf = buf.slice(idx + 2);
onLine(line);
}
},
};
}
const server = net.createServer((client) => {
const id = ++connSeq;
const tag = `P${id}`;
let injected = false;
let waitingId = false;
const pendingFromClient = [];
let upstreamWrite = null;
log(`conn ${id} opened`);
const upstream = tls.connect({ host: UPSTREAM_HOST, port: UPSTREAM_PORT, servername: UPSTREAM_HOST }, () => {
log(`conn ${id} upstream TLS ready`);
});
upstream.setEncoding('latin1');
client.setEncoding('latin1');
upstreamWrite = (line) => upstream.write(`${line}\r\n`);
const clientLines = pipeLineSplitter((line) => {
const upper = line.toUpperCase();
const isMailboxCmd = /^\S+\s+(SELECT|EXAMINE)\b/.test(upper);
if (!injected && isMailboxCmd) {
injected = true;
waitingId = true;
pendingFromClient.push(line);
log(`conn ${id} injecting ID before: ${line.slice(0, 40)}`);
upstream.write(`${tag} ID ${ID_LINE}\r\n`);
return;
}
if (waitingId) {
pendingFromClient.push(line);
return;
}
upstream.write(`${line}\r\n`);
});
const upstreamLines = pipeLineSplitter((line) => {
if (waitingId) {
if (line.startsWith('* ID ')) return; // 吞掉 untagged ID 响应
if (/^P\d+\s+(OK|NO|BAD)\b/i.test(line)) {
const ok = /^P\d+\s+OK\b/i.test(line);
log(`conn ${id} ID response: ${line.slice(0, 60)}`);
waitingId = false;
if (!ok) {
// ID 被拒也继续转发,让上层自己报错
client.write(`${line}\r\n`);
}
while (pendingFromClient.length) upstream.write(`${pendingFromClient.shift()}\r\n`);
return;
}
// 其它服务器响应(如 * OK)先转发
client.write(`${line}\r\n`);
return;
}
client.write(`${line}\r\n`);
});
client.on('data', (chunk) => clientLines.push(chunk));
upstream.on('data', (chunk) => upstreamLines.push(chunk));
const close = (why) => {
log(`conn ${id} closed (${why})`);
client.destroy();
upstream.destroy();
};
client.on('error', (e) => close(`client error ${e.message}`));
upstream.on('error', (e) => {
log(`conn ${id} upstream error ${e.message}`);
client.destroy();
});
client.on('close', () => upstream.destroy());
upstream.on('close', () => client.destroy());
});
server.listen(LISTEN_PORT, '0.0.0.0', () => {
log(`listening :${LISTEN_PORT} -> ${UPSTREAM_HOST}:${UPSTREAM_PORT} (TLS)`);
});
+65
View File
@@ -0,0 +1,65 @@
'use strict';
/**
* 公网网关:只把 WhatsApp webhook 和帮助中心暴露给 Cloudflare Tunnel,
* 其余路径(尤其 /api/v1/* 管理接口、admin UI)一律 404,避免整站公网裸奔。
*
* cloudflared (quick tunnel) -> public-gateway:9001 -> libredesk:9000
*/
const http = require('http');
const PORT = Number(process.env.PORT || 9001);
const UPSTREAM = new URL(process.env.UPSTREAM || 'http://libredesk:9000');
// 公网允许的路径前缀
const ALLOW = [
'/webhooks/whatsapp/', // Meta 回调
'/hc/', // 帮助中心(AI 引用链接)
'/widget.js',
'/widget', // widget iframe 页面
'/static/public/', // widget 静态资源
];
function allowed(pathname) {
return ALLOW.some((p) => pathname === p || pathname.startsWith(p));
}
const server = http.createServer((req, res) => {
const pathname = (req.url || '/').split('?')[0];
if (!allowed(pathname)) {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.end('not found');
return;
}
const headers = { ...req.headers };
delete headers.host;
headers.host = UPSTREAM.host;
const proxy = http.request(
{
protocol: UPSTREAM.protocol,
hostname: UPSTREAM.hostname,
port: UPSTREAM.port || 80,
method: req.method,
path: req.url,
headers,
},
(upRes) => {
res.writeHead(upRes.statusCode || 502, upRes.headers);
upRes.pipe(res);
}
);
proxy.on('error', (err) => {
console.error('[public-gateway] upstream error', pathname, err.message);
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
res.end('bad gateway');
});
req.pipe(proxy);
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`[public-gateway] listening :${PORT} -> ${UPSTREAM.origin} (allow: ${ALLOW.join(', ')})`);
});