Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 87 additions & 10 deletions src/services/notify/serverchan.js
Original file line number Diff line number Diff line change
@@ -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://<uid>.max.ft07.com/<sendkey>.send`;非法格式直接返回错误,不回退到 Turbo。
* - `sctp` 前缀:Server酱 3,匹配 `^sctp(\d+)t`,
* 路由至 `https://<uid>.push.ft07.com/send/<sendkey>.send`;非法格式直接返回错误,不回退到 Turbo。
* - 其他(如 `SCT...`):Server酱 Turbo,路由至 `https://sctapi.ftqq.com/<sendkey>.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)
);
}
},

Expand Down
2 changes: 1 addition & 1 deletion src/views/configPage.html
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,7 @@ <h4 class="text-md font-medium text-gray-900 mb-3">Server酱 配置</h4>
</button>
</div>
<p id="SERVERCHAN_SENDKEYStatus" class="mt-1 text-xs text-gray-500">加载中...</p>
<p class="mt-1 text-sm text-gray-500">从 <a href="https://sct.ftqq.com/" target="_blank" rel="noopener noreferrer" class="text-indigo-600 hover:text-indigo-800">Server酱</a> 获取 SendKey</p>
<p class="mt-1 text-sm text-gray-500">支持 Server酱 Turbo(<code>SCT...</code>)、Server酱 3(<code>sctp...</code>)与 <a href="https://doc.max.ft07.com/" target="_blank" rel="noopener noreferrer" class="text-indigo-600 hover:text-indigo-800">Server酱 Max</a>(<code>scx-...</code>),可从 <a href="https://sct.ftqq.com/" target="_blank" rel="noopener noreferrer" class="text-indigo-600 hover:text-indigo-800">Server酱</a> 获取 SendKey</p>
</div>
</div>
<div class="flex justify-end">
Expand Down
171 changes: 170 additions & 1 deletion tests/services/notify/channels.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 路由至 <uid>.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 路由至 <uid>.push.ft07.com/send/<key>.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/<key>.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;
Expand Down
Loading