179 lines
11 KiB
TypeScript
179 lines
11 KiB
TypeScript
import { createHmac, randomUUID } from 'node:crypto';
|
|
import type { Demand } from '../demand.ts';
|
|
import type { FeishuDelivery, FeishuDeliveryFilter, FeishuStatus } from '../feishu.ts';
|
|
import { appPath } from '../base-path.ts';
|
|
import { AuthError } from './auth.ts';
|
|
import { applicationOrigin, getDatabase } from './database.ts';
|
|
import { feishuBotConfig, feishuCallbackUrl, feishuJson, feishuLoginConfigured } from './feishu-config.ts';
|
|
|
|
const MAX_ATTEMPTS = 5;
|
|
type NotificationRow = { id: string; target_key: string; content: string; attempts: number; lease_token: string };
|
|
|
|
export function signFeishuMessage(timestamp: string, secret: string): string {
|
|
return createHmac('sha256', `${timestamp}\n${secret}`).update('').digest('base64');
|
|
}
|
|
|
|
/** Must run inside the demand write transaction so failed writes never generate messages. */
|
|
export function queueDemandNotification(demand: Demand): void {
|
|
if (demand.status === '草稿') return;
|
|
// A malformed notification configuration must not prevent saving a business record.
|
|
let config;
|
|
try { config = feishuBotConfig(); } catch { return; }
|
|
if (!config) return;
|
|
const event = demand.history.at(-1);
|
|
if (!event) return;
|
|
const link = applicationOrigin() + appPath('/?demand=' + encodeURIComponent(demand.id));
|
|
const content = [
|
|
`需有序 · ${event.action}`, demand.fields.title, `需求:${demand.id} · 第 ${demand.revision} 次保存`,
|
|
`当前状态:${demand.status}`, `操作人:${event.actor}`,
|
|
`开发责任人:${demand.review?.developer.displayName || '待分配'}`, `时间:${event.time}`, `查看需求:${link}`,
|
|
].join('\n');
|
|
getDatabase().prepare(`INSERT OR IGNORE INTO feishu_notifications (id, demand_id, revision, target_key, content, next_attempt_at, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)`).bind(randomUUID(), demand.id, demand.revision, config.targetKey, content, Date.now(), new Date().toISOString()).run();
|
|
}
|
|
|
|
async function sendText(content: string): Promise<void> {
|
|
const config = feishuBotConfig();
|
|
if (!config) throw new Error('尚未配置飞书群机器人。');
|
|
const timestamp = String(Math.floor(Date.now() / 1000));
|
|
const result = await feishuJson(config.webhook, {
|
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ msg_type: 'post', content: plainTextPost(content),
|
|
...(config.secret ? { timestamp, sign: signFeishuMessage(timestamp, config.secret) } : {}) }),
|
|
});
|
|
const code = result.code ?? result.StatusCode;
|
|
if (code !== 0) throw new Error(`飞书机器人拒绝消息(错误码 ${typeof code === 'number' ? code : '未知'}),请检查签名、关键词及 IP 限制。`);
|
|
}
|
|
|
|
/** Typed text nodes cannot execute Feishu's text-message <at> markup, including queued legacy messages. */
|
|
function plainTextPost(content: string) {
|
|
const lines = content.split('\n');
|
|
return { post: { zh_cn: { content: lines.map((line, index) => {
|
|
const prefix = '查看需求:';
|
|
if (index === lines.length - 1 && line.startsWith(prefix)) {
|
|
const href = line.slice(prefix.length);
|
|
// Only the server-generated final detail link becomes a link node.
|
|
if (href.startsWith(applicationOrigin() + appPath('/?demand='))) return [{ tag: 'a', text: '查看需求', href }];
|
|
}
|
|
return [{ tag: 'text', text: line, un_escape: false }];
|
|
}) } } };
|
|
}
|
|
|
|
export async function deliverNextFeishuNotification(): Promise<boolean> {
|
|
let config;
|
|
try { config = feishuBotConfig(); } catch { return false; }
|
|
if (!config) return false;
|
|
const db = getDatabase();
|
|
const now = Date.now();
|
|
const row = db.transaction(() => {
|
|
db.prepare(`UPDATE feishu_notifications SET status = 'failed', lease_token = NULL, last_error = '机器人地址已变更,旧通知已停止发送。'
|
|
WHERE status IN ('pending','sending') AND target_key != ?`).bind(config.targetKey).run();
|
|
db.prepare(`UPDATE feishu_notifications SET status = 'failed', lease_token = NULL, last_error = '发送中断且已达到重试上限,请检查后手动重试。'
|
|
WHERE status = 'sending' AND next_attempt_at <= ? AND attempts >= ?`).bind(now, MAX_ATTEMPTS).run();
|
|
const candidate = db.prepare(`SELECT id FROM feishu_notifications WHERE status IN ('pending','sending') AND next_attempt_at <= ?
|
|
AND target_key = ? ORDER BY created_at ASC LIMIT 1`).bind(now, config.targetKey).first<{ id: string }>();
|
|
if (!candidate) return null;
|
|
const lease = randomUUID();
|
|
db.prepare(`UPDATE feishu_notifications SET status = 'sending', attempts = attempts + 1, lease_token = ?, next_attempt_at = ? WHERE id = ?`)
|
|
.bind(lease, now + 60_000, candidate.id).run();
|
|
return db.prepare('SELECT * FROM feishu_notifications WHERE id = ?').bind(candidate.id).first<NotificationRow>();
|
|
});
|
|
if (!row) return false;
|
|
try {
|
|
await sendText(row.content);
|
|
db.prepare(`UPDATE feishu_notifications SET status = 'sent', sent_at = ?, last_error = NULL, lease_token = NULL WHERE id = ? AND lease_token = ?`)
|
|
.bind(new Date().toISOString(), row.id, row.lease_token).run();
|
|
} catch (error) {
|
|
// Fetch/network errors can contain a secret URL; retain only our known, sanitized messages.
|
|
const message = error instanceof Error && /^飞书(服务返回 HTTP \d+。|机器人拒绝消息(错误码 (\d+|未知)))/.test(error.message)
|
|
? error.message : '飞书消息发送失败或超时,请检查网络和机器人配置。';
|
|
db.prepare(`UPDATE feishu_notifications SET status = ?, last_error = ?, lease_token = NULL, next_attempt_at = ? WHERE id = ? AND lease_token = ?`)
|
|
.bind(row.attempts >= MAX_ATTEMPTS ? 'failed' : 'pending', message, Date.now() + Math.min(30_000 * 2 ** (row.attempts - 1), 15 * 60_000), row.id, row.lease_token).run();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
type DeliveryCursor = { createdAt: string; id: string };
|
|
export type FeishuDeliveryQuery = { filter: FeishuDeliveryFilter; cursor: DeliveryCursor | null };
|
|
export function parseFeishuDeliveryQuery(params: URLSearchParams): FeishuDeliveryQuery {
|
|
const filter = params.get('filter') || 'all';
|
|
if (filter !== 'all' && filter !== 'failed') throw new AuthError('通知筛选条件无效。');
|
|
const encoded = params.get('cursor');
|
|
let cursor: DeliveryCursor | null = null;
|
|
if (encoded) {
|
|
try {
|
|
if (encoded.length > 512 || !/^[A-Za-z0-9_-]+$/.test(encoded)) throw new Error();
|
|
const value: unknown = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
|
|
if (!value || typeof value !== 'object' || !('createdAt' in value) || !('id' in value) ||
|
|
typeof value.createdAt !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value.createdAt) ||
|
|
!Number.isFinite(Date.parse(value.createdAt)) || typeof value.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/.test(value.id)) throw new Error();
|
|
cursor = { createdAt: value.createdAt, id: value.id };
|
|
} catch { throw new AuthError('通知分页参数无效,请返回第一页后重试。'); }
|
|
}
|
|
return { filter, cursor };
|
|
}
|
|
|
|
export function feishuStatus(query: FeishuDeliveryQuery = { filter: 'all', cursor: null }): FeishuStatus {
|
|
let config = null;
|
|
let configurationError = null;
|
|
try { config = feishuBotConfig(); } catch (error) { configurationError = (error as Error).message; }
|
|
if (Boolean(process.env.FEISHU_APP_ID?.trim()) !== Boolean(process.env.FEISHU_APP_SECRET?.trim())) configurationError = '飞书登录需要同时配置 App ID 和 App Secret。';
|
|
const conditions: string[] = [];
|
|
const bindings: string[] = [];
|
|
if (query.filter === 'failed') conditions.push("status = 'failed'");
|
|
if (query.cursor) {
|
|
conditions.push('(created_at < ? OR (created_at = ? AND id < ?))');
|
|
bindings.push(query.cursor.createdAt, query.cursor.createdAt, query.cursor.id);
|
|
}
|
|
const rows = getDatabase().prepare(`SELECT id, demand_id AS demandId, revision, status, attempts, last_error AS lastError, created_at AS createdAt, sent_at AS sentAt
|
|
FROM feishu_notifications ${conditions.length ? 'WHERE ' + conditions.join(' AND ') : ''}
|
|
ORDER BY created_at DESC, id DESC LIMIT 51`).bind(...bindings).all<FeishuDelivery>().results;
|
|
const deliveries = rows.slice(0, 50).map(row => ({ ...row }));
|
|
const last = deliveries.at(-1);
|
|
return {
|
|
loginConfigured: feishuLoginConfigured(), callbackUrl: feishuCallbackUrl(), tenantRestricted: Boolean(process.env.FEISHU_TENANT_KEY?.trim()),
|
|
botConfigured: Boolean(config), botSigned: Boolean(config?.secret), configurationError,
|
|
deliveries, deliveryFilter: query.filter,
|
|
nextCursor: rows.length > 50 && last ? Buffer.from(JSON.stringify({ createdAt: last.createdAt, id: last.id })).toString('base64url') : null,
|
|
failedCount: getDatabase().prepare("SELECT COUNT(*) AS count FROM feishu_notifications WHERE status = 'failed'").first<{ count: number }>()!.count,
|
|
};
|
|
}
|
|
|
|
export function retryFeishuNotification(id: unknown): void {
|
|
if (typeof id !== 'string' || id.length > 128) throw new AuthError('通知编号无效。');
|
|
const config = feishuBotConfig();
|
|
if (!config) throw new AuthError('请先配置群机器人。');
|
|
const result = getDatabase().prepare(`UPDATE feishu_notifications SET status = 'pending', attempts = 0, next_attempt_at = ?, last_error = NULL
|
|
WHERE id = ? AND status = 'failed' AND target_key = ?`).bind(Date.now(), id, config.targetKey).run();
|
|
if (!result.meta.changes) throw new AuthError('只能重试当前机器人发送失败的通知。', 409);
|
|
}
|
|
|
|
export async function testFeishuBot(): Promise<void> {
|
|
if (!feishuBotConfig()) throw new AuthError('请先配置群机器人。');
|
|
const db = getDatabase();
|
|
db.transaction(() => {
|
|
const last = db.prepare("SELECT window_start FROM login_limits WHERE key = 'feishu-bot-test'").first<{ window_start: number }>();
|
|
if (last && Date.now() - last.window_start < 30_000) throw new AuthError('测试消息每 30 秒可发送一次。', 429);
|
|
db.prepare("INSERT OR REPLACE INTO login_limits (key, window_start, attempts) VALUES ('feishu-bot-test', ?, 1)").bind(Date.now()).run();
|
|
});
|
|
try { await sendText('需有序 · 飞书群机器人连接测试\n收到此消息表示通知通道已连通。'); }
|
|
catch { throw new AuthError('测试消息未确认发送成功,请检查 Webhook、签名、关键词、IP 限制及服务器网络。', 502); }
|
|
}
|
|
|
|
let workerStarted = false;
|
|
export function startFeishuNotificationWorker(): void {
|
|
if (workerStarted || !process.env.FEISHU_BOT_WEBHOOK?.trim()) return;
|
|
workerStarted = true;
|
|
let busy = false;
|
|
const tick = async () => {
|
|
if (busy) return;
|
|
busy = true;
|
|
try { await deliverNextFeishuNotification(); }
|
|
catch { console.error('Feishu notification worker could not access the notification queue.'); }
|
|
finally { busy = false; }
|
|
};
|
|
const timer = setInterval(() => { void tick(); }, 3000);
|
|
timer.unref();
|
|
void tick();
|
|
}
|