diff --git a/src/services/notify/serverchan.js b/src/services/notify/serverchan.js index 0e04b7c5..7d49857b 100644 --- a/src/services/notify/serverchan.js +++ b/src/services/notify/serverchan.js @@ -1,40 +1,117 @@ // @ts-check /** - * Server酱 3 通知渠道 + * Server酱通知渠道(兼容 Server酱 Max / Server酱 3 / Server酱 Turbo) */ import { ok, fail, errorMessage } from './channel.js'; +const SCX_SENDKEY_RE = /^scx-([1-9][0-9]{0,19})-(.+)$/; +const SCTP_SENDKEY_RE = /^sctp(\d+)t/; + +/** + * 根据 SendKey 解析 Server酱 请求地址。 + * + * - `scx-` 前缀:Server酱 Max,严格校验 `^scx-([1-9][0-9]{0,19})-(.+)$`(区分大小写), + * 路由至 `https://.max.ft07.com/.send`;非法格式直接返回错误,不回退到 Turbo。 + * - `sctp` 前缀:Server酱 3,匹配 `^sctp(\d+)t`, + * 路由至 `https://.push.ft07.com/send/.send`;非法格式直接返回错误,不回退到 Turbo。 + * - 其他(如 `SCT...`):Server酱 Turbo,路由至 `https://sctapi.ftqq.com/.send`。 + * + * @param {unknown} rawSendkey + * @returns {{ ok: boolean, sendkey?: string, endpoint?: string, error?: string }} + */ +export function resolveServerChanEndpoint(rawSendkey) { + const sendkey = typeof rawSendkey === 'string' ? rawSendkey.trim() : ''; + if (!sendkey) { + return { ok: false, error: '缺少 SERVERCHAN_SENDKEY' }; + } + + if (sendkey.startsWith('scx-')) { + const match = SCX_SENDKEY_RE.exec(sendkey); + if (!match) { + return { ok: false, error: '无效的 Server酱 Max SendKey 格式' }; + } + return { + ok: true, + sendkey, + endpoint: `https://${match[1]}.max.ft07.com/${sendkey}.send` + }; + } + + if (sendkey.startsWith('sctp')) { + const match = SCTP_SENDKEY_RE.exec(sendkey); + if (!match) { + return { ok: false, error: '无效的 Server酱 3 SendKey 格式' }; + } + return { + ok: true, + sendkey, + endpoint: `https://${match[1]}.push.ft07.com/send/${sendkey}.send` + }; + } + + return { + ok: true, + sendkey, + endpoint: `https://sctapi.ftqq.com/${sendkey}.send` + }; +} + +/** + * 脱敏可能包含 SendKey 或完整请求地址的诊断文本。 + * + * @param {string} text + * @param {string} sendkey + * @param {string} endpoint + * @returns {string} + */ +function redactSensitive(text, sendkey, endpoint) { + let out = String(text || ''); + if (endpoint) out = out.replaceAll(endpoint, '[REDACTED_URL]'); + if (sendkey) out = out.replaceAll(sendkey, '[REDACTED]'); + return out; +} + /** @type {import('./channel.js').Channel} */ export const serverChanChannel = { name: 'serverchan', validateConfig(config) { - if (!config.SERVERCHAN_SENDKEY) return { ok: false, error: '缺少 SERVERCHAN_SENDKEY' }; + const resolved = resolveServerChanEndpoint(config?.SERVERCHAN_SENDKEY); + if (!resolved.ok) return { ok: false, error: resolved.error }; return { ok: true }; }, async send(payload, config) { - const v = serverChanChannel.validateConfig(config); - if (!v.ok) return fail('serverchan', v.error || '配置无效'); + const resolved = resolveServerChanEndpoint(config?.SERVERCHAN_SENDKEY); + if (!resolved.ok) return fail('serverchan', resolved.error || '配置无效'); - const endpoint = `https://sctapi.ftqq.com/${config.SERVERCHAN_SENDKEY}.send`; const body = new URLSearchParams({ title: payload.title || '订阅提醒', desp: `## ${payload.title || '订阅提醒'}\n\n${payload.content || ''}` }); try { - const r = await fetch(endpoint, { + const r = await fetch(resolved.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() }); const result = await r.json().catch(() => ({})); - return result && result.code === 0 - ? ok('serverchan', result) - : fail('serverchan', `Server酱返回 code=${result?.code} ${result?.message || ''}`, result); + const responseCode = typeof result?.code === 'number' ? result.code : null; + const safeMessage = redactSensitive(result?.message || '', resolved.sendkey, resolved.endpoint); + const diagnostic = { httpStatus: r.status, code: responseCode }; + return r.ok && responseCode === 0 + ? ok('serverchan', diagnostic) + : fail( + 'serverchan', + `Server酱返回 HTTP ${r.status},code=${responseCode ?? '未知'}${safeMessage ? ` ${safeMessage}` : ''}`, + diagnostic + ); } catch (err) { - return fail('serverchan', errorMessage(err)); + return fail( + 'serverchan', + redactSensitive(errorMessage(err), resolved.sendkey, resolved.endpoint) + ); } }, diff --git a/src/views/configPage.html b/src/views/configPage.html index d2d22551..ba6c0b55 100644 --- a/src/views/configPage.html +++ b/src/views/configPage.html @@ -630,7 +630,7 @@

Server酱 配置

加载中...

-

从 Server酱 获取 SendKey

+

支持 Server酱 Turbo(SCT...)、Server酱 3(sctp...)与 Server酱 Max(scx-...),可从 Server酱 获取 SendKey

diff --git a/tests/services/notify/channels.test.js b/tests/services/notify/channels.test.js index d5f23458..080471e4 100644 --- a/tests/services/notify/channels.test.js +++ b/tests/services/notify/channels.test.js @@ -18,7 +18,7 @@ import { notifyxChannel } from '../../../src/services/notify/notifyx.js'; import { barkChannel } from '../../../src/services/notify/bark.js'; import { wecomChannel } from '../../../src/services/notify/wechat.js'; import { gotifyChannel } from '../../../src/services/notify/gotify.js'; -import { serverChanChannel } from '../../../src/services/notify/serverchan.js'; +import { serverChanChannel, resolveServerChanEndpoint } from '../../../src/services/notify/serverchan.js'; import { pushplusChannel } from '../../../src/services/notify/pushplus.js'; import { wpushChannel } from '../../../src/services/notify/wpush.js'; import { emailChannel } from '../../../src/services/notify/email.js'; @@ -440,6 +440,175 @@ describe('wpushChannel', () => { }); }); +describe('serverChanChannel(Turbo / Server酱 3 / Max 路由与脱敏)', () => { + it('resolveServerChanEndpoint:正确路由 Max / SC3 / Turbo 并自动去除首尾空白、严格保留大小写', () => { + const maxKey = 'scx-12345-AbCdEfGhIjKlMnOpQrStUvWx'; + const maxRes = resolveServerChanEndpoint(` ${maxKey} `); + expect(maxRes).toEqual({ + ok: true, + sendkey: maxKey, + endpoint: 'https://12345.max.ft07.com/scx-12345-AbCdEfGhIjKlMnOpQrStUvWx.send' + }); + + const sc3Key = 'sctp12345tAbCdEf'; + expect(resolveServerChanEndpoint(sc3Key)).toEqual({ + ok: true, + sendkey: sc3Key, + endpoint: 'https://12345.push.ft07.com/send/sctp12345tAbCdEf.send' + }); + + const turboKey = 'SCT12345TAbCdEf'; + expect(resolveServerChanEndpoint(turboKey)).toEqual({ + ok: true, + sendkey: turboKey, + endpoint: 'https://sctapi.ftqq.com/SCT12345TAbCdEf.send' + }); + }); + + it('send:Server酱 Max 路由至 .max.ft07.com 并发送表单 POST', async () => { + const captured = vi.fn(); + vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { + captured(url, init); + return jsonResponse({ code: 0, message: '', data: { pushid: '1' } }); + }); + + const sendkey = 'scx-12345-AbCdEfGhIjKlMnOpQrStUvWx'; + const r = await serverChanChannel.send( + { title: '订阅提醒', content: 'Netflix 将于明天到期' }, + { SERVERCHAN_SENDKEY: ` ${sendkey} ` } + ); + + expect(r.success).toBe(true); + expect(r.channel).toBe('serverchan'); + expect(captured).toHaveBeenCalledTimes(1); + const [url, init] = captured.mock.calls[0]; + expect(url).toBe('https://12345.max.ft07.com/scx-12345-AbCdEfGhIjKlMnOpQrStUvWx.send'); + expect(init.method).toBe('POST'); + expect(init.headers['Content-Type']).toBe('application/x-www-form-urlencoded'); + const params = new URLSearchParams(init.body); + expect(params.get('title')).toBe('订阅提醒'); + expect(params.get('desp')).toContain('Netflix 将于明天到期'); + }); + + it('send:Server酱 3 路由至 .push.ft07.com/send/.send', async () => { + const captured = vi.fn(); + vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { + captured(url, init); + return jsonResponse({ code: 0, message: '' }); + }); + + const r = await serverChanChannel.send( + { title: 'SC3 标题', content: 'SC3 内容' }, + { SERVERCHAN_SENDKEY: 'sctp12345tAbCdEf' } + ); + + expect(r.success).toBe(true); + const [url, init] = captured.mock.calls[0]; + expect(url).toBe('https://12345.push.ft07.com/send/sctp12345tAbCdEf.send'); + expect(init.method).toBe('POST'); + expect(init.headers['Content-Type']).toBe('application/x-www-form-urlencoded'); + const params = new URLSearchParams(init.body); + expect(params.get('title')).toBe('SC3 标题'); + expect(params.get('desp')).toContain('SC3 内容'); + }); + + it('send:Server酱 Turbo 路由至 sctapi.ftqq.com/.send', async () => { + const captured = vi.fn(); + vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { + captured(url, init); + return jsonResponse({ code: 0, message: '' }); + }); + + const r = await serverChanChannel.send( + { title: 'Turbo 标题', content: 'Turbo 内容' }, + { SERVERCHAN_SENDKEY: 'SCT12345TAbCdEf' } + ); + + expect(r.success).toBe(true); + const [url, init] = captured.mock.calls[0]; + expect(url).toBe('https://sctapi.ftqq.com/SCT12345TAbCdEf.send'); + expect(init.method).toBe('POST'); + expect(init.headers['Content-Type']).toBe('application/x-www-form-urlencoded'); + }); + + it.each([ + 'scx-0-abc', + 'scx-abc-def', + 'scx-1-', + 'scx-1', + 'scx-123456789012345678901-abc' + ])('非法 scx- SendKey (%s):显式报错、不回退 sctapi 且错误信息不泄露密钥', async (badKey) => { + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + + const v = serverChanChannel.validateConfig({ SERVERCHAN_SENDKEY: badKey }); + expect(v.ok).toBe(false); + expect(v.error).toBeTruthy(); + expect(v.error).not.toContain(badKey); + + const r = await serverChanChannel.send( + { title: 'T', content: 'C' }, + { SERVERCHAN_SENDKEY: badKey } + ); + expect(r.success).toBe(false); + expect(r.error).toBeTruthy(); + expect(r.error).not.toContain(badKey); + expect(r.error).not.toContain('sctapi.ftqq.com'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it.each(['sctpabc', 'sctp-123', 'sctp123'])('非法 sctp SendKey (%s):显式报错、不回退 sctapi 且不泄露密钥', async (badKey) => { + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + + const v = serverChanChannel.validateConfig({ SERVERCHAN_SENDKEY: badKey }); + expect(v.ok).toBe(false); + expect(v.error).not.toContain(badKey); + + const r = await serverChanChannel.send( + { title: 'T', content: 'C' }, + { SERVERCHAN_SENDKEY: badKey } + ); + expect(r.success).toBe(false); + expect(r.error).not.toContain(badKey); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('空白 SendKey → 失败且不发起请求', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + expect(serverChanChannel.validateConfig({ SERVERCHAN_SENDKEY: ' ' }).ok).toBe(false); + const r = await serverChanChannel.send({ title: 'T', content: 'C' }, { SERVERCHAN_SENDKEY: ' ' }); + expect(r.success).toBe(false); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('上游响应或网络异常回显 SendKey/URL 时脱敏且日志不泄露密钥', async () => { + const sendkey = 'scx-12345-AbCdEfGhIjKlMnOpQrStUvWx'; + const endpoint = `https://12345.max.ft07.com/${sendkey}.send`; + + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce( + jsonResponse({ code: 40001, message: `bad key ${sendkey} at ${endpoint}`, sendkey }, { status: 400 }) + ); + await dispatch( + { title: '测试', content: '正文' }, + { ENABLED_NOTIFIERS: ['serverchan'], SERVERCHAN_SENDKEY: sendkey }, + { env, subId: 'scx-sub' } + ); + const logs = await query(env, { subId: 'scx-sub' }); + expect(logs).toHaveLength(1); + expect(logs[0].status).toBe('failed'); + expect(JSON.stringify(logs)).not.toContain(sendkey); + expect(JSON.stringify(logs)).not.toContain(endpoint); + + vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new Error(`fetch failed for ${endpoint}`)); + const netRes = await serverChanChannel.send( + { title: '测试', content: '正文' }, + { SERVERCHAN_SENDKEY: sendkey } + ); + expect(netRes.success).toBe(false); + expect(netRes.error).not.toContain(sendkey); + expect(netRes.error).not.toContain(endpoint); + }); +}); + describe('渠道边界加固与脱敏回归测试', () => { it('ntfyChannel 中文标题采用 RFC 2047 编码,构造 Headers 不抛 ByteString TypeError', async () => { let capturedHeaders = null;