From 60c9669abd1cbbbd920dbe30e25343330eebc168 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 14 Sep 2026 19:34:29 +0800 Subject: [PATCH] feat(core): allow custom request headers on notification channels Operators can attach Authorization and other headers to a webhook channel so authenticated providers work without a separate proxy. Fixes #451 --- packages/core/src/notifications/config.ts | 29 +++++++ packages/core/src/notifications/manager.ts | 10 +-- .../core/tests/notifications-config.test.ts | 30 +++++++ .../core/tests/notifications-manager.test.ts | 17 ++++ .../settings/notification-channel-dialog.tsx | 85 ++++++++++++++++++- packages/webui/src/types.ts | 1 + 6 files changed, 166 insertions(+), 6 deletions(-) diff --git a/packages/core/src/notifications/config.ts b/packages/core/src/notifications/config.ts index 7fe91419..8753851b 100644 --- a/packages/core/src/notifications/config.ts +++ b/packages/core/src/notifications/config.ts @@ -31,6 +31,10 @@ export const CHANNEL_ID_RE = /^[\w.-]+$/; const CHANNEL_ID_MAX = 64; const CHANNEL_NAME_MAX = 128; const BODY_TEMPLATE_MAX = 8192; +const HEADER_NAME_MAX = 128; +const HEADER_VALUE_MAX = 1024; +const HEADERS_MAX = 16; +const HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; /** event ∈ {offline, online}; rendered verbatim into `{event}`. */ export type NotificationEvent = 'offline' | 'online'; @@ -41,6 +45,8 @@ export interface NotificationChannel { url: string; bodyTemplate: string; enabled: boolean; + /** Extra outbound request headers (Authorization, etc.). */ + headers?: Record; } export interface NotificationsConfig { @@ -120,6 +126,27 @@ function isHttpUrl(value: string): boolean { /** A channel is usable only with a valid id AND an http(s) target — anything * else is unusable, so the whole entry is dropped (total normalize). */ +function normalizeHeaders(value: unknown): Record | undefined { + if (!isObject(value)) return undefined; + const out: Record = {}; + const seen = new Set(); + for (const [rawName, rawValue] of Object.entries(value)) { + if (Object.keys(out).length >= HEADERS_MAX) break; + if (typeof rawValue !== 'string') continue; + const name = rawName.trim(); + if (name.length === 0 || name.length > HEADER_NAME_MAX) continue; + if (!HEADER_NAME_RE.test(name)) continue; + const folded = name.toLowerCase(); + if (seen.has(folded)) continue; + const headerValue = rawValue.trim(); + if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) continue; + if (headerValue.includes('\r') || headerValue.includes('\n')) continue; + seen.add(folded); + out[name] = headerValue; + } + return Object.keys(out).length > 0 ? out : undefined; +} + function normalizeChannel(raw: unknown): NotificationChannel | null { if (!isObject(raw)) return null; const id = normalizeChannelId(raw.id); @@ -127,12 +154,14 @@ function normalizeChannel(raw: unknown): NotificationChannel | null { const url = typeof raw.url === 'string' ? raw.url.trim() : ''; if (!isHttpUrl(url)) return null; const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id; + const headers = normalizeHeaders(raw.headers); return { id, name, url, bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX), enabled: boolOr(raw.enabled, true), + ...(headers ? { headers } : {}), }; } diff --git a/packages/core/src/notifications/manager.ts b/packages/core/src/notifications/manager.ts index cd9b932e..c75c457a 100644 --- a/packages/core/src/notifications/manager.ts +++ b/packages/core/src/notifications/manager.ts @@ -49,7 +49,7 @@ export interface NotificationManagerDeps { /** The channel ids a UIN has opted into. */ loadChannelIds: (uin: string) => string[]; /** Outbound delivery — never throws; failures come back as `{ ok: false }`. */ - post: (url: string, body: string) => Promise; + post: (url: string, body: string, headers?: Record) => Promise; now: () => number; historyLimit?: number; } @@ -165,7 +165,7 @@ export class NotificationManager { const body = renderTemplate(ch.bodyTemplate, vars); let result: PostResult; try { - result = await this.deps.post(ch.url, body); + result = await this.deps.post(ch.url, body, ch.headers); } catch (err) { // The injected post is contracted not to throw, but guard anyway. result = { ok: false, error: errMsg(err) }; @@ -204,7 +204,7 @@ export class NotificationManager { time: new Date(this.deps.now()).toISOString(), }); try { - return { ...(await this.deps.post(channel.url, body)), found: true }; + return { ...(await this.deps.post(channel.url, body, channel.headers)), found: true }; } catch (err) { return { ok: false, found: true, error: errMsg(err) }; } @@ -234,11 +234,11 @@ export class NotificationManager { /** Default outbound POST: a single attempt with a timeout, JSON content-type * (the common case for 钉钉/Discord/飞书). Never throws. */ export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] { - return async (url, body) => { + return async (url, body, headers) => { try { const res = await fetch(url, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', ...headers }, body, signal: AbortSignal.timeout(timeoutMs), }); diff --git a/packages/core/tests/notifications-config.test.ts b/packages/core/tests/notifications-config.test.ts index e3a75b9f..13d88cd5 100644 --- a/packages/core/tests/notifications-config.test.ts +++ b/packages/core/tests/notifications-config.test.ts @@ -137,6 +137,36 @@ describe('normalizeNotificationsConfig — total normalize', () => { expect(channels[0].enabled).toBe(true); expect(channels[0].name).toBe('c1'); expect(channels[0].bodyTemplate).toBe(DEFAULT_BODY_TEMPLATE); + expect(channels[0].headers).toBeUndefined(); + }); + + it('keeps valid request headers and drops unsafe or empty ones', () => { + const { channels } = normalizeNotificationsConfig({ + channels: [{ + id: 'feishu', + url: 'https://open.feishu.cn/hook', + headers: { + Authorization: 'Bearer secret', + 'X-Custom': 'ok', + 'Bad Name': 'x', + '': 'x', + Inject: 'line\r\nX-Evil: 1', + Empty: ' ', + NotString: 1, + } as Record, + }], + }); + expect(channels[0].headers).toEqual({ + Authorization: 'Bearer secret', + 'X-Custom': 'ok', + }); + }); + + it('omits an empty headers object after normalize', () => { + const { channels } = normalizeNotificationsConfig({ + channels: [{ id: 'c1', url: 'https://a.com', headers: { 'Bad Name': 'x' } }], + }); + expect(channels[0].headers).toBeUndefined(); }); }); diff --git a/packages/core/tests/notifications-manager.test.ts b/packages/core/tests/notifications-manager.test.ts index 2f5e37f3..1a2b9ded 100644 --- a/packages/core/tests/notifications-manager.test.ts +++ b/packages/core/tests/notifications-manager.test.ts @@ -57,6 +57,23 @@ describe('NotificationManager — dispatch + history', () => { expect(posts).toEqual([{ url: 'https://hook.example/c1', body: 'offline:123:123' }]); }); + it('forwards channel request headers to the post collaborator', async () => { + const posts: { url: string; body: string; headers?: Record }[] = []; + const { mgr } = setup({ + loadConfig: () => ({ + version: 1, + debounceSeconds: 30, + channels: [ch({ headers: { Authorization: 'Bearer secret' } })], + }), + post: async (url, body, headers) => { + posts.push({ url, body, headers }); + return { ok: true, status: 200 }; + }, + }); + await mgr.notify('123', 'offline'); + expect(posts[0]?.headers).toEqual({ Authorization: 'Bearer secret' }); + }); + it('uses the nickname captured on an online/offline edge', async () => { const { posts, mgr } = setup(); mgr.handleOnline('123', 'Alice'); // caches nickname; cold online → no post diff --git a/packages/webui/src/components/settings/notification-channel-dialog.tsx b/packages/webui/src/components/settings/notification-channel-dialog.tsx index 6c71cb3f..446bfb9c 100644 --- a/packages/webui/src/components/settings/notification-channel-dialog.tsx +++ b/packages/webui/src/components/settings/notification-channel-dialog.tsx @@ -3,6 +3,7 @@ // The channel id is the stable key per-account opt-ins reference, so it's // editable only on create and locked on edit. import { useState } from 'react'; +import { Plus, Trash2 } from 'lucide-react'; import { Modal } from '@/components/interior/modal'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -12,6 +13,27 @@ import { ToggleSwitch } from '@/components/ui/toggle-switch'; import { cn } from '@/lib/utils'; import type { NotificationChannel } from '@/types'; +interface HeaderRow { + name: string; + value: string; +} + +function headersToRows(headers?: Record): HeaderRow[] { + const rows = Object.entries(headers ?? {}).map(([name, value]) => ({ name, value })); + return rows.length > 0 ? rows : [{ name: '', value: '' }]; +} + +function rowsToHeaders(rows: HeaderRow[]): Record | undefined { + const out: Record = {}; + for (const row of rows) { + const name = row.name.trim(); + const value = row.value.trim(); + if (!name || !value) continue; + out[name] = value; + } + return Object.keys(out).length > 0 ? out : undefined; +} + const CHANNEL_ID_RE = /^[\w.-]+$/; function isHttpUrl(u: string): boolean { try { @@ -37,7 +59,11 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps) const { open, onOpenChange, isEdit, initial, otherIds, onSubmit } = props; // Parent unmounts on close, so each open re-seeds via lazy init. const [draft, setDraft] = useState(initial); + const [headerRows, setHeaderRows] = useState(() => headersToRows(initial.headers)); const patch = (p: Partial) => setDraft({ ...draft, ...p }); + const patchHeader = (index: number, p: Partial) => { + setHeaderRows(headerRows.map((row, i) => (i === index ? { ...row, ...p } : row))); + }; const id = draft.id.trim(); const idBlank = id.length === 0; @@ -72,7 +98,13 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps) + +
+ {headerRows.map((row, i) => ( +
+ patchHeader(i, { name: e.target.value })} + className="font-mono text-xs" + /> + patchHeader(i, { value: e.target.value })} + className="font-mono text-xs" + /> + +
+ ))} +
+

+ 可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。 +

+ +