feat(notifications): P1 config layer — global channel store + per-UIN opt-in

Global channel store at config/notifications.json, mirroring ui-config's
total-normalize + atomic-write + cached-load conventions: NotificationsConfig
(version, debounceSeconds clamp [0,3600] default 30, channels[]), a total
normalizeNotificationsConfig (drops malformed/non-http channels, dedupes by
id, strips unknown fields), and the pure renderTemplate ({key} substitution;
missing keys left as-is; no re-expansion of substituted values).

Per-UIN opt-in: OneBotConfig.notifications.channelIds (validated slugs,
last-write-wins merge across global+per-uin, deduped) in the onebot package.

Tests: 19 (core notifications-config) + 12 (onebot config), all green.
Adversarial review: 0 blockers / 0 should-fix.
This commit is contained in:
DrSmoothl committed 2026-06-16 19:02:01 +08:00
1 parent bf5978fb51
commit 34d05f41f5
5 files changed
+509 -1

No files matched your search

+233
View File
@@ -0,0 +1,233 @@
// Global notification-channel store + the pure template renderer.
//
// Mirrors the conventions of `webui/ui-config.ts` (the plan calls for this
// explicitly): every `normalize*` is TOTAL — any unknown / corrupt input
// collapses to a safe default, numbers clamp, unknown keys are dropped — and
// persistence is an atomic write (tmp → rename) behind a module-level cache.
//
// Channels are GLOBAL (defined once here); each UIN opts into a subset via
// `OneBotConfig.notifications.channelIds` (see packages/onebot/src/config.ts).
import { createLogger } from '@snowluma/common/logger';
import fs from 'fs';
import path from 'path';
const log = createLogger('Notifications.Config');
const CONFIG_DIR = 'config';
const NOTIFICATIONS_CONFIG_PATH = path.join(CONFIG_DIR, 'notifications.json');
export const NOTIFICATIONS_CONFIG_VERSION = 1 as const;
export const DEBOUNCE_SECONDS_MIN = 0;
export const DEBOUNCE_SECONDS_MAX = 3600;
export const DEFAULT_DEBOUNCE_SECONDS = 30;
/** A channel id is a slug: it is referenced by per-UIN `channelIds`, so it must
* be safe to use as a stable key. Kept in sync with `normalizeChannelIds` in
* packages/onebot/src/config.ts (cross-package; can't share without a circular
* dep — core depends on onebot, not the reverse). */
export const CHANNEL_ID_RE = /^[\w.-]+$/;
const CHANNEL_ID_MAX = 64;
const CHANNEL_NAME_MAX = 128;
const BODY_TEMPLATE_MAX = 8192;
/** event ∈ {offline, online}; rendered verbatim into `{event}`. */
export type NotificationEvent = 'offline' | 'online';
export interface NotificationChannel {
id: string;
name: string;
url: string;
bodyTemplate: string;
enabled: boolean;
}
export interface NotificationsConfig {
version: typeof NOTIFICATIONS_CONFIG_VERSION;
debounceSeconds: number;
channels: NotificationChannel[];
}
/** A neutral plaintext starting point; the WebUI ships per-vendor presets
* (钉钉/Discord/…) as frontend constants the operator can drop in. */
export const DEFAULT_BODY_TEMPLATE = '{nickname}({uin}) {event} @ {time}';
export function defaultNotificationsConfig(): NotificationsConfig {
return {
version: NOTIFICATIONS_CONFIG_VERSION,
debounceSeconds: DEFAULT_DEBOUNCE_SECONDS,
channels: [],
};
}
// ─── Template renderer ──────────────────────────────────────────────────────
/**
* Mechanical `{key}` substitution — no logic, no conditionals, no escaping.
* A key present in `vars` is replaced by its value; an unknown `{key}` is left
* untouched (原样) so a typo'd placeholder is visible rather than silently
* blanked. Pure + total (a non-string template yields '').
*/
export function renderTemplate(template: string, vars: Record<string, string>): string {
if (typeof template !== 'string') return '';
return template.replace(/\{(\w+)\}/g, (match, key: string) =>
Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : match,
);
}
// ─── Normalization helpers (replicated from ui-config conventions) ──────────
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function boolOr(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
if (!Number.isFinite(n)) return fallback;
return Math.trunc(Math.min(max, Math.max(min, n)));
}
function strOr(value: unknown, fallback: string, maxLen: number): string {
return typeof value === 'string' ? value.slice(0, maxLen) : fallback;
}
function normalizeChannelId(value: unknown): string | null {
if (typeof value !== 'string') return null;
const v = value.trim();
if (v.length === 0 || v.length > CHANNEL_ID_MAX) return null;
if (!CHANNEL_ID_RE.test(v)) return null;
return v;
}
function isHttpUrl(value: string): boolean {
try {
const u = new URL(value);
return u.protocol === 'http:' || u.protocol === 'https:';
} catch {
return false;
}
}
/** 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 normalizeChannel(raw: unknown): NotificationChannel | null {
if (!isObject(raw)) return null;
const id = normalizeChannelId(raw.id);
if (!id) return 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;
return {
id,
name,
url,
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true),
};
}
function normalizeChannels(value: unknown): NotificationChannel[] {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
const out: NotificationChannel[] = [];
for (const raw of value) {
const ch = normalizeChannel(raw);
if (!ch) continue;
if (seen.has(ch.id)) continue; // dedupe by id — first occurrence wins
seen.add(ch.id);
out.push(ch);
}
return out;
}
export function normalizeNotificationsConfig(value: unknown): NotificationsConfig {
const v = isObject(value) ? value : {};
return {
version: NOTIFICATIONS_CONFIG_VERSION,
debounceSeconds: clampInt(
v.debounceSeconds,
DEBOUNCE_SECONDS_MIN,
DEBOUNCE_SECONDS_MAX,
DEFAULT_DEBOUNCE_SECONDS,
),
channels: normalizeChannels(v.channels),
};
}
// ─── Persistence (atomic write + module-level cache) ────────────────────────
function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function atomicWrite(config: NotificationsConfig): void {
ensureConfigDir();
const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH);
}
let cached: NotificationsConfig | null = null;
/** Load + normalize the channel store, creating it from defaults if absent. */
export function loadNotificationsConfig(): NotificationsConfig {
if (cached) return cached;
ensureConfigDir();
if (!fs.existsSync(NOTIFICATIONS_CONFIG_PATH)) {
const fresh = defaultNotificationsConfig();
try {
atomicWrite(fresh);
} catch (err) {
log.warn('failed to write initial notifications.json: %s', err instanceof Error ? err.message : String(err));
}
cached = fresh;
return fresh;
}
try {
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
const normalized = normalizeNotificationsConfig(parsed);
// Self-heal on disk only if normalization changed something (corrupt/old).
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
try {
atomicWrite(normalized);
} catch {
/* best-effort self-heal */
}
}
cached = normalized;
return normalized;
} catch (err) {
log.warn('notifications.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err));
const fresh = defaultNotificationsConfig();
cached = fresh;
return fresh;
}
}
/**
* Persist a (possibly partial) client-supplied config. A missing `channels` or
* `debounceSeconds` keeps the current on-disk value — section-level merge, same
* as `saveUiConfig`. Returns the stored, normalized config.
*/
export function saveNotificationsConfig(incoming: unknown): NotificationsConfig {
const current = loadNotificationsConfig();
const v = isObject(incoming) ? incoming : {};
const next: NotificationsConfig = {
version: NOTIFICATIONS_CONFIG_VERSION,
debounceSeconds:
v.debounceSeconds !== undefined
? clampInt(v.debounceSeconds, DEBOUNCE_SECONDS_MIN, DEBOUNCE_SECONDS_MAX, DEFAULT_DEBOUNCE_SECONDS)
: current.debounceSeconds,
channels: Array.isArray(v.channels) ? normalizeChannels(v.channels) : current.channels,
};
atomicWrite(next);
cached = next;
return next;
}
@@ -0,0 +1,185 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import {
DEFAULT_BODY_TEMPLATE,
DEFAULT_DEBOUNCE_SECONDS,
defaultNotificationsConfig,
normalizeNotificationsConfig,
renderTemplate,
} from '../src/notifications/config';
describe('renderTemplate — mechanical {key} substitution', () => {
it('replaces present variables', () => {
expect(
renderTemplate('{nickname}({uin}) {event} @ {time}', {
nickname: 'Bob',
uin: '123',
event: 'offline',
time: '12:00',
}),
).toBe('Bob(123) offline @ 12:00');
});
it('leaves missing placeholders untouched (原样)', () => {
expect(renderTemplate('{a}-{b}', { a: 'x' })).toBe('x-{b}');
});
it('replaces repeated occurrences', () => {
expect(renderTemplate('{x}{x}', { x: 'ab' })).toBe('abab');
});
it('leaves text with no placeholders unchanged', () => {
expect(renderTemplate('hello', { x: '1' })).toBe('hello');
});
it('does no logic — an empty value substitutes as empty', () => {
expect(renderTemplate('[{x}]', { x: '' })).toBe('[]');
});
it('is total — a non-string template yields an empty string', () => {
expect(renderTemplate(undefined as unknown as string, {})).toBe('');
});
it('does NOT re-expand a substituted value that itself contains a placeholder', () => {
// Load-bearing invariant: replacement text is never re-scanned. A refactor
// to a recursive/loop replace would break this while passing every other test.
expect(renderTemplate('{a}', { a: '{b}', b: 'NESTED' })).toBe('{b}');
});
});
describe('normalizeNotificationsConfig — total normalize', () => {
it('collapses garbage / non-objects to the full default', () => {
const d = defaultNotificationsConfig();
for (const junk of [undefined, null, 42, 'nope', []]) {
expect(normalizeNotificationsConfig(junk)).toEqual(d);
}
});
it('forces version to 1 regardless of input', () => {
expect(normalizeNotificationsConfig({ version: 99 }).version).toBe(1);
});
it('clamps + truncates debounceSeconds into [0, 3600]', () => {
expect(normalizeNotificationsConfig({ debounceSeconds: -5 }).debounceSeconds).toBe(0);
expect(normalizeNotificationsConfig({ debounceSeconds: 99999 }).debounceSeconds).toBe(3600);
expect(normalizeNotificationsConfig({ debounceSeconds: 30.9 }).debounceSeconds).toBe(30);
expect(normalizeNotificationsConfig({ debounceSeconds: '45' }).debounceSeconds).toBe(45);
expect(normalizeNotificationsConfig({ debounceSeconds: 'x' }).debounceSeconds).toBe(DEFAULT_DEBOUNCE_SECONDS);
});
it('drops a non-array channels value', () => {
expect(normalizeNotificationsConfig({ channels: 'nope' }).channels).toEqual([]);
});
it('keeps a valid channel and strips unknown fields', () => {
const { channels } = normalizeNotificationsConfig({
channels: [
{
id: 'dingtalk',
name: 'DingTalk',
url: 'https://oapi.dingtalk.com/robot/send',
bodyTemplate: '{event}',
enabled: true,
evil: 'x',
extra: 1,
},
],
});
expect(channels).toEqual([
{
id: 'dingtalk',
name: 'DingTalk',
url: 'https://oapi.dingtalk.com/robot/send',
bodyTemplate: '{event}',
enabled: true,
},
]);
});
it('drops channels lacking a valid id or http(s) url', () => {
const { channels } = normalizeNotificationsConfig({
channels: [
{ id: '', url: 'https://a.com' }, // empty id
{ id: 'bad id!', url: 'https://a.com' }, // invalid slug
{ id: 'noUrl' }, // missing url
{ id: 'ftp', url: 'ftp://a.com' }, // non-http scheme
{ id: 'ok', url: 'http://a.com' }, // valid
],
});
expect(channels.map((c) => c.id)).toEqual(['ok']);
});
it('dedupes channels by id (first occurrence wins)', () => {
const { channels } = normalizeNotificationsConfig({
channels: [
{ id: 'dup', url: 'https://a.com', name: 'first' },
{ id: 'dup', url: 'https://b.com', name: 'second' },
],
});
expect(channels).toHaveLength(1);
expect(channels[0].name).toBe('first');
expect(channels[0].url).toBe('https://a.com');
});
it('defaults enabled=true, name→id, and bodyTemplate→default', () => {
const { channels } = normalizeNotificationsConfig({ channels: [{ id: 'c1', url: 'https://a.com' }] });
expect(channels[0].enabled).toBe(true);
expect(channels[0].name).toBe('c1');
expect(channels[0].bodyTemplate).toBe(DEFAULT_BODY_TEMPLATE);
});
});
describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () => {
let tmp: string;
let prevCwd: string;
beforeEach(() => {
prevCwd = process.cwd();
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-notif-'));
process.chdir(tmp);
vi.resetModules();
});
afterEach(() => {
process.chdir(prevCwd);
fs.rmSync(tmp, { recursive: true, force: true });
});
it('creates a default config file when absent', async () => {
const mod = await import('../src/notifications/config');
const cfg = mod.loadNotificationsConfig();
expect(cfg).toEqual(mod.defaultNotificationsConfig());
expect(fs.existsSync(path.join('config', 'notifications.json'))).toBe(true);
});
it('round-trips a saved config across a fresh module load', async () => {
const mod = await import('../src/notifications/config');
const saved = mod.saveNotificationsConfig({
debounceSeconds: 60,
channels: [{ id: 'c1', name: 'C1', url: 'https://a.com/hook', bodyTemplate: '{event}', enabled: false }],
});
expect(saved.debounceSeconds).toBe(60);
expect(saved.channels).toHaveLength(1);
vi.resetModules();
const mod2 = await import('../src/notifications/config');
expect(mod2.loadNotificationsConfig()).toEqual(saved);
});
it('section-merges partial saves (debounce-only keeps channels)', async () => {
const mod = await import('../src/notifications/config');
mod.saveNotificationsConfig({ channels: [{ id: 'c1', url: 'https://a.com' }] });
const after = mod.saveNotificationsConfig({ debounceSeconds: 120 });
expect(after.debounceSeconds).toBe(120);
expect(after.channels.map((c) => c.id)).toEqual(['c1']);
});
it('self-heals an unreadable file on load', async () => {
fs.mkdirSync('config', { recursive: true });
fs.writeFileSync(path.join('config', 'notifications.json'), '{ not valid json', 'utf8');
const mod = await import('../src/notifications/config');
expect(mod.loadNotificationsConfig()).toEqual(mod.defaultNotificationsConfig());
});
});
+37 -1
View File
@@ -56,6 +56,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
},
musicSignUrl: '',
statusCommand: makeDefaultStatusCommand(),
notifications: { channelIds: [] },
};
}
@@ -113,6 +114,7 @@ function toJsonObject(config: OneBotConfig): JsonObject {
swallow: config.statusCommand.swallow,
cooldownSeconds: config.statusCommand.cooldownSeconds,
},
notifications: { channelIds: config.notifications?.channelIds ?? [] },
};
}
@@ -196,7 +198,41 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
}
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
return { networks, musicSignUrl, statusCommand: parseStatusCommand(sources) };
return {
networks,
musicSignUrl,
statusCommand: parseStatusCommand(sources),
notifications: parseNotifications(sources),
};
}
/** Last-write-wins merge of `notifications.channelIds` across config sources,
* each id validated as a slug + deduped. Mirrors the channel-id rule in
* packages/core/src/notifications/config.ts (CHANNEL_ID_RE) — duplicated
* deliberately: core depends on onebot, so onebot cannot import from core. */
function parseNotifications(sources: JsonObject[]): { channelIds: string[] } {
let channelIds: string[] = [];
for (const src of sources) {
const raw = src.notifications;
if (!isObject(raw)) continue;
if (Array.isArray(raw.channelIds)) channelIds = normalizeChannelIds(raw.channelIds);
}
return { channelIds };
}
function normalizeChannelIds(value: unknown): string[] {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
const out: string[] = [];
for (const item of value) {
if (typeof item !== 'string') continue;
const v = item.trim();
if (!v || v.length > 64 || !/^[\w.-]+$/.test(v)) continue;
if (seen.has(v)) continue;
seen.add(v);
out.push(v);
}
return out;
}
/** Last-write-wins merge of `statusCommand` across config sources, with
+4
View File
@@ -86,6 +86,10 @@ export interface OneBotConfig {
musicSignUrl?: string;
/** Built-in `#sl` status command settings. Always present after normalization. */
statusCommand: StatusCommandConfig;
/** Which GLOBAL notification channels this account opts into (channel ids are
* validated slugs; channels themselves live in config/notifications.json).
* Always present after normalization. */
notifications?: { channelIds: string[] };
}
export interface MessageMeta {
+50
View File
@@ -26,6 +26,7 @@ describe('makeDefaultOneBotConfig', () => {
expect(config.networks.wsClients).toEqual([]);
expect(config.musicSignUrl).toBe('');
expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
expect(config.notifications).toEqual({ channelIds: [] });
});
});
@@ -222,3 +223,52 @@ describe('loadOneBotConfig', () => {
});
});
describe('OneBotConfig.notifications (per-UIN channel opt-in)', () => {
let tempDir: string;
let prevCwd: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-notif-'));
prevCwd = process.cwd();
process.chdir(tempDir);
});
afterEach(() => {
process.chdir(prevCwd);
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('defaults to an empty channelIds list when absent', () => {
const config = loadOneBotConfig('20001');
expect(config.notifications).toEqual({ channelIds: [] });
});
it('validates, dedupes and drops bad channel ids', () => {
const uin = '20002';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, `onebot_${uin}.json`),
JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
notifications: { channelIds: ['dingtalk', 'dingtalk', 'bad id!', '', 42, 'feishu'] },
}),
);
const config = loadOneBotConfig(uin);
expect(config.notifications?.channelIds).toEqual(['dingtalk', 'feishu']);
});
it('round-trips channelIds through save/load and persists them', () => {
const uin = '20003';
const config = makeDefaultOneBotConfig();
config.notifications = { channelIds: ['discord', 'serverchan'] };
saveOneBotConfig(uin, config);
const reloaded = loadOneBotConfig(uin);
expect(reloaded.notifications?.channelIds).toEqual(['discord', 'serverchan']);
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'));
expect(onDisk.notifications).toEqual({ channelIds: ['discord', 'serverchan'] });
});
});