feat(notifications): P3 HTTP face — channel config CRUD + recent + test-send

Bearer-gated WebUI routes:
- GET/POST /api/notifications/config — read/normalize the global channel store
  (whole-config CRUD, mirroring the ui-config pattern).
- GET /api/notifications/recent?limit=N — in-memory delivery history (≤100).
- POST /api/notifications/test {channelId} — one-off test to a single channel
  (ignores enabled/opt-in, sample vars, reuses render+POST, not recorded).

NotificationManager.testSend() added; initWebUI takes the manager (optional).
Tests: testSend unit coverage. 16 manager tests green, typecheck clean.
Adversarial review: 0 blockers / 0 should-fix / 0 nits.
This commit is contained in:
DrSmoothl committed 2026-06-16 19:30:54 +08:00
1 parent 30bcd97a3f
commit c0af18e1c2
4 files changed
+131 -1

No files matched your search

+1 -1
View File
@@ -48,7 +48,7 @@ async function main() {
) {
try {
const { initWebUI } = await import('./webui/server');
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager);
} catch (err) {
log.error('Failed to start WebUI: ', err);
}
@@ -182,6 +182,31 @@ export class NotificationManager {
}
}
/** Send a one-off test to a single channel by id — ignores `enabled` and the
* per-UIN opt-in (you test a channel before wiring it up), with sample
* variables. Reuses the real render+POST path; NOT recorded to history.
* `found:false` means the channel id is unknown. */
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
let channel: NotificationChannel | undefined;
try {
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
} catch (err) {
return { ok: false, found: false, error: errMsg(err) };
}
if (!channel) return { ok: false, found: false };
const body = renderTemplate(channel.bodyTemplate, {
uin: '10000',
nickname: '测试账号',
event: 'offline',
time: new Date(this.deps.now()).toISOString(),
});
try {
return { ...(await this.deps.post(channel.url, body)), found: true };
} catch (err) {
return { ok: false, found: true, error: errMsg(err) };
}
}
private record(rec: DeliveryRecord): void {
this.history.push(rec);
if (this.history.length > this.historyLimit) {
+57
View File
@@ -25,6 +25,8 @@ import {
writeBackgroundImage,
} from './ui-config';
import { getUpdateInfo } from './update-check';
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
import type { NotificationManager } from '../notifications/manager';
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -102,6 +104,7 @@ export async function initWebUI(
desiredPort: number = 5099,
oneBotManager: OneBotManager,
hookManager?: HookManager,
notificationManager?: NotificationManager,
): Promise<{ port: number }> {
const auth = WebuiAuth.load();
const initialPassword = auth.takeInitialPassword();
@@ -543,6 +546,60 @@ export async function initWebUI(
}
});
// ─── Notifications (account up/down → webhook) ───────────────────────────
// Global channel store (config/notifications.json); per-UIN opt-in lives in
// OneBotConfig.notifications.channelIds. All bearer-gated — channel URLs can
// embed secrets, so none of this is exposed unauthenticated.
app.get('/api/notifications/config', (c) => c.json({ config: loadNotificationsConfig() }));
app.post('/api/notifications/config', async (c) => {
const declaredLen = Number(c.req.header('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > 512 * 1024) {
return c.json({ success: false, message: '配置过大' }, 413);
}
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
try {
const config = saveNotificationsConfig(body);
return c.json({ success: true, config });
} catch (err) {
log.warn('save notifications config failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
});
app.get('/api/notifications/recent', (c) => {
if (!notificationManager) return c.json({ recent: [] });
const limitRaw = Number(c.req.query('limit'));
const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.trunc(limitRaw), 100) : 100;
return c.json({ recent: notificationManager.getRecent(limit) });
});
app.post('/api/notifications/test', async (c) => {
if (!notificationManager) return c.json({ success: false, message: '通知子系统不可用' }, 503);
let body: { channelId?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const channelId = typeof body.channelId === 'string' ? body.channelId : '';
if (!channelId) return c.json({ success: false, message: '缺少 channelId' }, 400);
const result = await notificationManager.testSend(channelId);
if (!result.found) return c.json({ success: false, message: '渠道不存在' }, 404);
return c.json({
success: result.ok,
status: result.status,
message: result.ok
? '测试发送成功'
: `测试发送失败:${result.error ?? (result.status ? `HTTP ${result.status}` : '未知错误')}`,
});
});
// ─── WebUI customization config (config/ui.json) ─────────────────────────
// Appearance (A) + layout (C). The full config is bearer-gated; only the
// cosmetic appearance subset is exposed unauthenticated for the login page.
@@ -101,6 +101,54 @@ describe('NotificationManager — dispatch + history', () => {
});
});
describe('NotificationManager.testSend', () => {
function setup(over: Partial<NotificationManagerDeps> = {}) {
const posts: { url: string; body: string }[] = [];
const cfg: NotificationsConfig = {
version: 1,
debounceSeconds: 30,
// disabled + nobody opted in — testSend must still fire it.
channels: [ch({ id: 'c1', enabled: false, bodyTemplate: 'test:{event}:{nickname}' })],
};
const deps: NotificationManagerDeps = {
loadConfig: () => cfg,
loadChannelIds: () => [],
post: async (url, body): Promise<PostResult> => {
posts.push({ url, body });
return { ok: true, status: 200 };
},
now: () => 1000,
...over,
};
return { posts, mgr: new NotificationManager(deps) };
}
it('fires a disabled / non-opted-in channel with sample vars', async () => {
const { posts, mgr } = setup();
const res = await mgr.testSend('c1');
expect(res).toMatchObject({ found: true, ok: true, status: 200 });
expect(posts).toHaveLength(1);
expect(posts[0].body).toBe('test:offline:测试账号');
});
it('returns found:false for an unknown channel and posts nothing', async () => {
const { posts, mgr } = setup();
expect(await mgr.testSend('ghost')).toMatchObject({ found: false, ok: false });
expect(posts).toEqual([]);
});
it('does not record test sends in history', async () => {
const { mgr } = setup();
await mgr.testSend('c1');
expect(mgr.getRecent()).toEqual([]);
});
it('surfaces a failed delivery without throwing', async () => {
const { mgr } = setup({ post: async (): Promise<PostResult> => ({ ok: false, status: 500, error: 'nope' }) });
expect(await mgr.testSend('c1')).toMatchObject({ found: true, ok: false, status: 500 });
});
});
describe('NotificationManager — debounce integration (fake timers)', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());