@tavlo-dsh/dsh-plugin-hooks 0.0.0-stage → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +29 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +5 -0
- package/index.js +793 -0
- package/lib/client.js +5 -0
- package/lib/client.js.LEGAL.txt +4 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
- package/src/config-store.js +804 -0
- package/src/default-scripts.js +193 -0
- package/src/dsh-hook-bridge.js +999 -0
- package/src/event-hub.js +198 -0
- package/src/hook-catalog.js +359 -0
- package/src/notification-dispatcher.js +486 -0
- package/src/script-runner.js +671 -0
- package/src/sound-manager.js +403 -0
- package/src/system-notifier.js +549 -0
- package/src/third-party-providers.js +1137 -0
|
@@ -0,0 +1,1137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Third-party hook notification provider definitions, validation, signing, and outbound HTTP adapters.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { createHmac } from 'node:crypto'
|
|
6
|
+
|
|
7
|
+
export const PROVIDER_IDS = Object.freeze([
|
|
8
|
+
'bark',
|
|
9
|
+
'dingtalk',
|
|
10
|
+
'feishu',
|
|
11
|
+
'telegram',
|
|
12
|
+
'wecom',
|
|
13
|
+
'pushplus',
|
|
14
|
+
'wxpusher',
|
|
15
|
+
'serverchan',
|
|
16
|
+
'ntfy',
|
|
17
|
+
'gotify',
|
|
18
|
+
'custom',
|
|
19
|
+
])
|
|
20
|
+
|
|
21
|
+
const MAX_RESPONSE_BYTES = 64 * 1024
|
|
22
|
+
const DEFAULT_TIMEOUT_MS = 5000
|
|
23
|
+
const MAX_MESSAGE_CHARS = 160
|
|
24
|
+
const FORBIDDEN_CUSTOM_HEADERS = new Set(['host', 'content-length', 'transfer-encoding', 'connection'])
|
|
25
|
+
const SAFE_HEADER_NAME_RE = /^[A-Za-z0-9-]+$/
|
|
26
|
+
const BARK_LEVELS = new Set(['', 'active', 'timeSensitive', 'passive', 'critical'])
|
|
27
|
+
const NTFY_AUTH_TYPES = new Set(['none', 'bearer', 'basic'])
|
|
28
|
+
const CUSTOM_METHODS = new Set(['POST', 'GET'])
|
|
29
|
+
const CUSTOM_BODY_TYPES = new Set(['json', 'form', 'text'])
|
|
30
|
+
|
|
31
|
+
export const PROVIDER_DEFINITIONS = Object.freeze([
|
|
32
|
+
Object.freeze({
|
|
33
|
+
id: 'bark',
|
|
34
|
+
labelZh: 'Bark',
|
|
35
|
+
labelEn: 'Bark',
|
|
36
|
+
fields: Object.freeze([
|
|
37
|
+
{
|
|
38
|
+
key: 'serverUrl',
|
|
39
|
+
labelZh: '服务器地址',
|
|
40
|
+
labelEn: 'Server URL',
|
|
41
|
+
kind: 'text',
|
|
42
|
+
required: false,
|
|
43
|
+
defaultValue: 'https://api.day.app',
|
|
44
|
+
placeholder: 'https://api.day.app',
|
|
45
|
+
},
|
|
46
|
+
{ key: 'deviceKey', labelZh: 'Device Key', labelEn: 'Device Key', kind: 'secret', required: true },
|
|
47
|
+
{ key: 'group', labelZh: '分组 (可选)', labelEn: 'Group (optional)', kind: 'text', required: false },
|
|
48
|
+
{ key: 'sound', labelZh: '提示音 (可选)', labelEn: 'Sound (optional)', kind: 'text', required: false },
|
|
49
|
+
{
|
|
50
|
+
key: 'level',
|
|
51
|
+
labelZh: '中断级别',
|
|
52
|
+
labelEn: 'Level',
|
|
53
|
+
kind: 'select',
|
|
54
|
+
required: false,
|
|
55
|
+
defaultValue: '',
|
|
56
|
+
options: [
|
|
57
|
+
{ value: '', labelZh: '默认', labelEn: 'Default' },
|
|
58
|
+
{ value: 'active', labelZh: 'active', labelEn: 'active' },
|
|
59
|
+
{ value: 'timeSensitive', labelZh: 'timeSensitive', labelEn: 'timeSensitive' },
|
|
60
|
+
{ value: 'passive', labelZh: 'passive', labelEn: 'passive' },
|
|
61
|
+
{ value: 'critical', labelZh: 'critical', labelEn: 'critical' },
|
|
62
|
+
],
|
|
63
|
+
},
|
|
64
|
+
{ key: 'basicUsername', labelZh: 'Basic 用户名 (可选)', labelEn: 'Basic Username', kind: 'text', required: false },
|
|
65
|
+
{ key: 'basicPassword', labelZh: 'Basic 密码 (可选)', labelEn: 'Basic Password', kind: 'secret', required: false },
|
|
66
|
+
]),
|
|
67
|
+
}),
|
|
68
|
+
Object.freeze({
|
|
69
|
+
id: 'dingtalk',
|
|
70
|
+
labelZh: '钉钉机器人',
|
|
71
|
+
labelEn: 'DingTalk',
|
|
72
|
+
fields: Object.freeze([
|
|
73
|
+
{
|
|
74
|
+
key: 'webhookUrl',
|
|
75
|
+
labelZh: 'Webhook URL',
|
|
76
|
+
labelEn: 'Webhook URL',
|
|
77
|
+
kind: 'secret',
|
|
78
|
+
required: true,
|
|
79
|
+
placeholder: 'https://oapi.dingtalk.com/robot/send?access_token=...',
|
|
80
|
+
},
|
|
81
|
+
{ key: 'secret', labelZh: '加签密钥 (可选)', labelEn: 'Signing Secret (optional)', kind: 'secret', required: false },
|
|
82
|
+
]),
|
|
83
|
+
}),
|
|
84
|
+
Object.freeze({
|
|
85
|
+
id: 'feishu',
|
|
86
|
+
labelZh: '飞书机器人',
|
|
87
|
+
labelEn: 'Feishu / Lark',
|
|
88
|
+
fields: Object.freeze([
|
|
89
|
+
{
|
|
90
|
+
key: 'webhookUrl',
|
|
91
|
+
labelZh: 'Webhook URL',
|
|
92
|
+
labelEn: 'Webhook URL',
|
|
93
|
+
kind: 'secret',
|
|
94
|
+
required: true,
|
|
95
|
+
placeholder: 'https://open.feishu.cn/open-apis/bot/v2/hook/...',
|
|
96
|
+
},
|
|
97
|
+
{ key: 'secret', labelZh: '签名密钥 (可选)', labelEn: 'Signing Secret (optional)', kind: 'secret', required: false },
|
|
98
|
+
]),
|
|
99
|
+
}),
|
|
100
|
+
Object.freeze({
|
|
101
|
+
id: 'telegram',
|
|
102
|
+
labelZh: 'Telegram',
|
|
103
|
+
labelEn: 'Telegram',
|
|
104
|
+
fields: Object.freeze([
|
|
105
|
+
{ key: 'botToken', labelZh: 'Bot Token', labelEn: 'Bot Token', kind: 'secret', required: true },
|
|
106
|
+
{ key: 'chatId', labelZh: 'Chat ID', labelEn: 'Chat ID', kind: 'text', required: true },
|
|
107
|
+
{ key: 'messageThreadId', labelZh: 'Thread ID (可选)', labelEn: 'Thread ID (optional)', kind: 'number', required: false },
|
|
108
|
+
]),
|
|
109
|
+
}),
|
|
110
|
+
Object.freeze({
|
|
111
|
+
id: 'wecom',
|
|
112
|
+
labelZh: '企业微信',
|
|
113
|
+
labelEn: 'WeCom',
|
|
114
|
+
fields: Object.freeze([
|
|
115
|
+
{
|
|
116
|
+
key: 'webhookUrl',
|
|
117
|
+
labelZh: 'Webhook URL',
|
|
118
|
+
labelEn: 'Webhook URL',
|
|
119
|
+
kind: 'secret',
|
|
120
|
+
required: true,
|
|
121
|
+
placeholder: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...',
|
|
122
|
+
},
|
|
123
|
+
]),
|
|
124
|
+
}),
|
|
125
|
+
Object.freeze({
|
|
126
|
+
id: 'pushplus',
|
|
127
|
+
labelZh: 'PushPlus',
|
|
128
|
+
labelEn: 'PushPlus',
|
|
129
|
+
fields: Object.freeze([
|
|
130
|
+
{ key: 'token', labelZh: 'Token', labelEn: 'Token', kind: 'secret', required: true },
|
|
131
|
+
{ key: 'template', labelZh: '模板', labelEn: 'Template', kind: 'text', required: false, defaultValue: 'txt' },
|
|
132
|
+
{ key: 'channel', labelZh: '发送渠道 (可选)', labelEn: 'Channel (optional)', kind: 'text', required: false },
|
|
133
|
+
{ key: 'topic', labelZh: '群组编码 (可选)', labelEn: 'Topic (optional)', kind: 'text', required: false },
|
|
134
|
+
{ key: 'webhook', labelZh: 'Webhook 编码 (可选)', labelEn: 'Webhook (optional)', kind: 'text', required: false },
|
|
135
|
+
]),
|
|
136
|
+
}),
|
|
137
|
+
Object.freeze({
|
|
138
|
+
id: 'wxpusher',
|
|
139
|
+
labelZh: 'WxPusher',
|
|
140
|
+
labelEn: 'WxPusher',
|
|
141
|
+
fields: Object.freeze([
|
|
142
|
+
{ key: 'spt', labelZh: 'SPT (推荐)', labelEn: 'SPT (recommended)', kind: 'secret', required: false },
|
|
143
|
+
{ key: 'appToken', labelZh: 'App Token (无 SPT 时必填)', labelEn: 'App Token (if no SPT)', kind: 'secret', required: false },
|
|
144
|
+
{ key: 'uids', labelZh: 'UID 列表 (逗号分隔)', labelEn: 'UIDs (CSV)', kind: 'csv', required: false },
|
|
145
|
+
{ key: 'topicIds', labelZh: 'Topic ID 列表 (逗号分隔)', labelEn: 'Topic IDs (CSV)', kind: 'numberCsv', required: false },
|
|
146
|
+
]),
|
|
147
|
+
}),
|
|
148
|
+
Object.freeze({
|
|
149
|
+
id: 'serverchan',
|
|
150
|
+
labelZh: 'Server 酱',
|
|
151
|
+
labelEn: 'ServerChan',
|
|
152
|
+
fields: Object.freeze([
|
|
153
|
+
{ key: 'sendKey', labelZh: 'SendKey', labelEn: 'SendKey', kind: 'secret', required: true },
|
|
154
|
+
]),
|
|
155
|
+
}),
|
|
156
|
+
Object.freeze({
|
|
157
|
+
id: 'ntfy',
|
|
158
|
+
labelZh: 'ntfy',
|
|
159
|
+
labelEn: 'ntfy',
|
|
160
|
+
fields: Object.freeze([
|
|
161
|
+
{
|
|
162
|
+
key: 'serverUrl',
|
|
163
|
+
labelZh: '服务器地址',
|
|
164
|
+
labelEn: 'Server URL',
|
|
165
|
+
kind: 'text',
|
|
166
|
+
required: false,
|
|
167
|
+
defaultValue: 'https://ntfy.sh',
|
|
168
|
+
placeholder: 'https://ntfy.sh',
|
|
169
|
+
},
|
|
170
|
+
{ key: 'topic', labelZh: 'Topic', labelEn: 'Topic', kind: 'secret', required: true },
|
|
171
|
+
{
|
|
172
|
+
key: 'authType',
|
|
173
|
+
labelZh: '认证方式',
|
|
174
|
+
labelEn: 'Auth Type',
|
|
175
|
+
kind: 'select',
|
|
176
|
+
required: false,
|
|
177
|
+
defaultValue: 'none',
|
|
178
|
+
options: [
|
|
179
|
+
{ value: 'none', labelZh: '无认证', labelEn: 'None' },
|
|
180
|
+
{ value: 'bearer', labelZh: 'Bearer Token', labelEn: 'Bearer Token' },
|
|
181
|
+
{ value: 'basic', labelZh: 'Basic Auth', labelEn: 'Basic Auth' },
|
|
182
|
+
],
|
|
183
|
+
},
|
|
184
|
+
{ key: 'authToken', labelZh: 'Bearer Token', labelEn: 'Bearer Token', kind: 'secret', required: false },
|
|
185
|
+
{ key: 'basicUsername', labelZh: 'Basic 用户名', labelEn: 'Basic Username', kind: 'text', required: false },
|
|
186
|
+
{ key: 'basicPassword', labelZh: 'Basic 密码', labelEn: 'Basic Password', kind: 'secret', required: false },
|
|
187
|
+
{ key: 'priority', labelZh: '优先级 (1-5)', labelEn: 'Priority (1-5)', kind: 'text', required: false },
|
|
188
|
+
{ key: 'tags', labelZh: '标签 (逗号分隔)', labelEn: 'Tags (CSV)', kind: 'text', required: false },
|
|
189
|
+
]),
|
|
190
|
+
}),
|
|
191
|
+
Object.freeze({
|
|
192
|
+
id: 'gotify',
|
|
193
|
+
labelZh: 'Gotify',
|
|
194
|
+
labelEn: 'Gotify',
|
|
195
|
+
fields: Object.freeze([
|
|
196
|
+
{
|
|
197
|
+
key: 'serverUrl',
|
|
198
|
+
labelZh: '服务器地址',
|
|
199
|
+
labelEn: 'Server URL',
|
|
200
|
+
kind: 'text',
|
|
201
|
+
required: true,
|
|
202
|
+
defaultValue: '',
|
|
203
|
+
placeholder: 'https://gotify.example.com',
|
|
204
|
+
},
|
|
205
|
+
{ key: 'appToken', labelZh: 'App Token', labelEn: 'App Token', kind: 'secret', required: true },
|
|
206
|
+
{ key: 'priority', labelZh: '优先级', labelEn: 'Priority', kind: 'number', required: false, defaultValue: 5 },
|
|
207
|
+
]),
|
|
208
|
+
}),
|
|
209
|
+
Object.freeze({
|
|
210
|
+
id: 'custom',
|
|
211
|
+
labelZh: '自定义 HTTP',
|
|
212
|
+
labelEn: 'Custom HTTP',
|
|
213
|
+
fields: Object.freeze([
|
|
214
|
+
{
|
|
215
|
+
key: 'method',
|
|
216
|
+
labelZh: '请求方法',
|
|
217
|
+
labelEn: 'Method',
|
|
218
|
+
kind: 'select',
|
|
219
|
+
required: false,
|
|
220
|
+
defaultValue: 'POST',
|
|
221
|
+
options: [
|
|
222
|
+
{ value: 'POST', labelZh: 'POST', labelEn: 'POST' },
|
|
223
|
+
{ value: 'GET', labelZh: 'GET', labelEn: 'GET' },
|
|
224
|
+
],
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
key: 'url',
|
|
228
|
+
labelZh: '请求 URL',
|
|
229
|
+
labelEn: 'URL',
|
|
230
|
+
kind: 'secret',
|
|
231
|
+
required: true,
|
|
232
|
+
placeholder: 'https://example.com/hook',
|
|
233
|
+
},
|
|
234
|
+
{
|
|
235
|
+
key: 'bodyType',
|
|
236
|
+
labelZh: '请求体格式',
|
|
237
|
+
labelEn: 'Body Type',
|
|
238
|
+
kind: 'select',
|
|
239
|
+
required: false,
|
|
240
|
+
defaultValue: 'json',
|
|
241
|
+
options: [
|
|
242
|
+
{ value: 'json', labelZh: 'JSON', labelEn: 'JSON' },
|
|
243
|
+
{ value: 'form', labelZh: 'Form (urlencoded)', labelEn: 'Form' },
|
|
244
|
+
{ value: 'text', labelZh: '纯文本', labelEn: 'Plain Text' },
|
|
245
|
+
],
|
|
246
|
+
},
|
|
247
|
+
{ key: 'query', labelZh: 'Query 参数 (每行 key=value)', labelEn: 'Query Params (key=value lines)', kind: 'kvLines', required: false },
|
|
248
|
+
{ key: 'headers', labelZh: '请求头 (每行 key=value)', labelEn: 'Headers (key=value lines)', kind: 'kvLines', required: false },
|
|
249
|
+
{
|
|
250
|
+
key: 'jsonBody',
|
|
251
|
+
labelZh: 'JSON 模板',
|
|
252
|
+
labelEn: 'JSON Body Template',
|
|
253
|
+
kind: 'textarea',
|
|
254
|
+
required: false,
|
|
255
|
+
defaultValue: '{"title":"{{title}}","body":"{{body}}"}',
|
|
256
|
+
},
|
|
257
|
+
{ key: 'formBody', labelZh: 'Form 字段 (每行 key=value)', labelEn: 'Form Body (key=value lines)', kind: 'kvLines', required: false },
|
|
258
|
+
{ key: 'textBody', labelZh: '纯文本模板', labelEn: 'Text Body Template', kind: 'textarea', required: false },
|
|
259
|
+
]),
|
|
260
|
+
}),
|
|
261
|
+
])
|
|
262
|
+
|
|
263
|
+
const PROVIDER_MAP = new Map(PROVIDER_DEFINITIONS.map((def) => [def.id, def]))
|
|
264
|
+
|
|
265
|
+
export function getProviderDefinition(provider) {
|
|
266
|
+
return typeof provider === 'string' ? PROVIDER_MAP.get(provider) : undefined
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Return the field keys marked `kind === 'secret'` for a given provider.
|
|
271
|
+
* @param {string} provider
|
|
272
|
+
* @returns {string[]}
|
|
273
|
+
*/
|
|
274
|
+
export function getSecretFieldKeys(provider) {
|
|
275
|
+
const def = getProviderDefinition(provider)
|
|
276
|
+
if (!def) return []
|
|
277
|
+
return def.fields.filter((field) => field.kind === 'secret').map((field) => field.key)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function asTrimmedString(val) {
|
|
281
|
+
return typeof val === 'string' ? val.trim() : val == null ? '' : String(val).trim()
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function parseCsvStrings(raw) {
|
|
285
|
+
if (Array.isArray(raw)) {
|
|
286
|
+
return raw.map((item) => asTrimmedString(item)).filter(Boolean)
|
|
287
|
+
}
|
|
288
|
+
if (typeof raw === 'string') {
|
|
289
|
+
return raw
|
|
290
|
+
.split(/[,,\s]+/)
|
|
291
|
+
.map((s) => s.trim())
|
|
292
|
+
.filter(Boolean)
|
|
293
|
+
}
|
|
294
|
+
return []
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function parseNumberCsv(raw) {
|
|
298
|
+
const items = Array.isArray(raw)
|
|
299
|
+
? raw
|
|
300
|
+
: typeof raw === 'string'
|
|
301
|
+
? raw.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean)
|
|
302
|
+
: []
|
|
303
|
+
const parsed = []
|
|
304
|
+
for (const item of items) {
|
|
305
|
+
const num = Number(item)
|
|
306
|
+
if (!Number.isInteger(num)) {
|
|
307
|
+
return { valid: false, values: [] }
|
|
308
|
+
}
|
|
309
|
+
parsed.push(num)
|
|
310
|
+
}
|
|
311
|
+
return { valid: true, values: parsed }
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function parseKvLines(raw) {
|
|
315
|
+
if (Array.isArray(raw)) {
|
|
316
|
+
const rows = []
|
|
317
|
+
for (const entry of raw) {
|
|
318
|
+
if (entry && typeof entry === 'object' && typeof entry.key === 'string') {
|
|
319
|
+
const key = entry.key.trim()
|
|
320
|
+
if (key) rows.push({ key, value: entry.value == null ? '' : String(entry.value) })
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return rows
|
|
324
|
+
}
|
|
325
|
+
if (typeof raw !== 'string') return []
|
|
326
|
+
const rows = []
|
|
327
|
+
for (const rawLine of raw.split(/\r?\n/)) {
|
|
328
|
+
const line = rawLine.trim()
|
|
329
|
+
if (!line) continue
|
|
330
|
+
const idx = line.indexOf('=')
|
|
331
|
+
if (idx <= 0) continue
|
|
332
|
+
const key = line.slice(0, idx).trim()
|
|
333
|
+
const value = line.slice(idx + 1).trim()
|
|
334
|
+
if (key) rows.push({ key, value })
|
|
335
|
+
}
|
|
336
|
+
return rows
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function validateHttpUrl(rawUrl, label = 'URL') {
|
|
340
|
+
const trimmed = asTrimmedString(rawUrl)
|
|
341
|
+
if (!trimmed) {
|
|
342
|
+
return { valid: false, error: `${label} is required.` }
|
|
343
|
+
}
|
|
344
|
+
let parsed
|
|
345
|
+
try {
|
|
346
|
+
parsed = new URL(trimmed)
|
|
347
|
+
} catch {
|
|
348
|
+
return { valid: false, error: `${label} is not a valid URL.` }
|
|
349
|
+
}
|
|
350
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
351
|
+
return { valid: false, error: `${label} must use http: or https: protocol.` }
|
|
352
|
+
}
|
|
353
|
+
if (!parsed.hostname) {
|
|
354
|
+
return { valid: false, error: `${label} must include a valid host.` }
|
|
355
|
+
}
|
|
356
|
+
if (parsed.username || parsed.password) {
|
|
357
|
+
return { valid: false, error: `${label} must not embed username or password credentials.` }
|
|
358
|
+
}
|
|
359
|
+
return { valid: true, url: parsed }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function validateCustomHeaders(rawHeaders) {
|
|
363
|
+
const rows = parseKvLines(rawHeaders)
|
|
364
|
+
for (const { key, value } of rows) {
|
|
365
|
+
if (!SAFE_HEADER_NAME_RE.test(key)) {
|
|
366
|
+
return { valid: false, error: `Invalid header name: ${key}` }
|
|
367
|
+
}
|
|
368
|
+
if (FORBIDDEN_CUSTOM_HEADERS.has(key.toLowerCase())) {
|
|
369
|
+
return { valid: false, error: `Header "${key}" is forbidden.` }
|
|
370
|
+
}
|
|
371
|
+
if (/[\r\n\0]/.test(value)) {
|
|
372
|
+
return { valid: false, error: `Header "${key}" contains invalid control characters.` }
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return { valid: true, rows }
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function encodeHeaderValue(val) {
|
|
379
|
+
const clean = String(val ?? '').replace(/[\r\n\0]+/g, ' ').trim()
|
|
380
|
+
if (/^[\x20-\x7e]*$/.test(clean)) return clean
|
|
381
|
+
return `=?UTF-8?B?${Buffer.from(clean, 'utf8').toString('base64')}?=`
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function truncateMessage(text) {
|
|
385
|
+
const clean = String(text ?? '')
|
|
386
|
+
.replace(/[\r\n\t\x00-\x1f\x7f]+/g, ' ')
|
|
387
|
+
.replace(/\s+/g, ' ')
|
|
388
|
+
.trim()
|
|
389
|
+
const chars = Array.from(clean)
|
|
390
|
+
return chars.length <= MAX_MESSAGE_CHARS ? clean : chars.slice(0, MAX_MESSAGE_CHARS).join('')
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Validate a merged provider configuration (non-secret fields + resolved secrets).
|
|
395
|
+
* @param {string} provider
|
|
396
|
+
* @param {Record<string, unknown>} mergedConfig
|
|
397
|
+
* @returns {{ valid: boolean, error?: string, errors?: string[] }}
|
|
398
|
+
*/
|
|
399
|
+
export function validateProviderConfig(provider, mergedConfig = {}) {
|
|
400
|
+
const def = getProviderDefinition(provider)
|
|
401
|
+
if (!def) {
|
|
402
|
+
const error = `Unknown provider: ${String(provider)}`
|
|
403
|
+
return { valid: false, error, errors: [error] }
|
|
404
|
+
}
|
|
405
|
+
if (mergedConfig !== null && mergedConfig !== undefined && (typeof mergedConfig !== 'object' || Array.isArray(mergedConfig))) {
|
|
406
|
+
const error = 'Provider configuration must be an object.'
|
|
407
|
+
return { valid: false, error, errors: [error] }
|
|
408
|
+
}
|
|
409
|
+
const cfg = mergedConfig || {}
|
|
410
|
+
const errors = []
|
|
411
|
+
|
|
412
|
+
const pushErr = (msg) => {
|
|
413
|
+
if (msg) errors.push(msg)
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
switch (provider) {
|
|
417
|
+
case 'dingtalk':
|
|
418
|
+
case 'feishu':
|
|
419
|
+
case 'wecom': {
|
|
420
|
+
const check = validateHttpUrl(cfg.webhookUrl, 'webhookUrl')
|
|
421
|
+
if (!check.valid) pushErr(check.error)
|
|
422
|
+
break
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
case 'bark': {
|
|
426
|
+
const serverUrl = asTrimmedString(cfg.serverUrl) || 'https://api.day.app'
|
|
427
|
+
const urlCheck = validateHttpUrl(serverUrl, 'serverUrl')
|
|
428
|
+
if (!urlCheck.valid) pushErr(urlCheck.error)
|
|
429
|
+
const deviceKey = asTrimmedString(cfg.deviceKey)
|
|
430
|
+
if (!deviceKey) {
|
|
431
|
+
pushErr('deviceKey is required.')
|
|
432
|
+
} else if (/[/?#\s\x00-\x1f]/.test(deviceKey)) {
|
|
433
|
+
pushErr('deviceKey contains invalid characters.')
|
|
434
|
+
}
|
|
435
|
+
const level = asTrimmedString(cfg.level)
|
|
436
|
+
if (level && !BARK_LEVELS.has(level)) {
|
|
437
|
+
pushErr(`Invalid Bark level: ${level}`)
|
|
438
|
+
}
|
|
439
|
+
const user = asTrimmedString(cfg.basicUsername)
|
|
440
|
+
const pass = asTrimmedString(cfg.basicPassword)
|
|
441
|
+
if ((user && !pass) || (!user && pass)) {
|
|
442
|
+
pushErr('Both basicUsername and basicPassword are required for Basic auth.')
|
|
443
|
+
}
|
|
444
|
+
break
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
case 'pushplus': {
|
|
448
|
+
if (!asTrimmedString(cfg.token)) {
|
|
449
|
+
pushErr('token is required.')
|
|
450
|
+
}
|
|
451
|
+
break
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
case 'wxpusher': {
|
|
455
|
+
const spt = asTrimmedString(cfg.spt)
|
|
456
|
+
const appToken = asTrimmedString(cfg.appToken)
|
|
457
|
+
if (!spt && !appToken) {
|
|
458
|
+
pushErr('WxPusher requires spt or appToken.')
|
|
459
|
+
}
|
|
460
|
+
if (cfg.topicIds !== undefined && cfg.topicIds !== null && String(cfg.topicIds).trim() !== '') {
|
|
461
|
+
const parsedTopics = parseNumberCsv(cfg.topicIds)
|
|
462
|
+
if (!parsedTopics.valid) {
|
|
463
|
+
pushErr('topicIds must be comma-separated integers.')
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
break
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
case 'serverchan': {
|
|
470
|
+
const sendKey = asTrimmedString(cfg.sendKey)
|
|
471
|
+
if (!sendKey) {
|
|
472
|
+
pushErr('sendKey is required.')
|
|
473
|
+
} else if (!/^[A-Za-z0-9_-]+$/.test(sendKey)) {
|
|
474
|
+
pushErr('sendKey contains invalid characters.')
|
|
475
|
+
}
|
|
476
|
+
break
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
case 'telegram': {
|
|
480
|
+
const botToken = asTrimmedString(cfg.botToken)
|
|
481
|
+
if (!botToken) {
|
|
482
|
+
pushErr('botToken is required.')
|
|
483
|
+
} else if (!/^[A-Za-z0-9_:-]+$/.test(botToken)) {
|
|
484
|
+
pushErr('botToken contains invalid characters.')
|
|
485
|
+
}
|
|
486
|
+
if (!asTrimmedString(cfg.chatId)) {
|
|
487
|
+
pushErr('chatId is required.')
|
|
488
|
+
}
|
|
489
|
+
const threadRaw = asTrimmedString(cfg.messageThreadId)
|
|
490
|
+
if (threadRaw && !Number.isInteger(Number(threadRaw))) {
|
|
491
|
+
pushErr('messageThreadId must be an integer.')
|
|
492
|
+
}
|
|
493
|
+
break
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
case 'ntfy': {
|
|
497
|
+
const serverUrl = asTrimmedString(cfg.serverUrl) || 'https://ntfy.sh'
|
|
498
|
+
const urlCheck = validateHttpUrl(serverUrl, 'serverUrl')
|
|
499
|
+
if (!urlCheck.valid) pushErr(urlCheck.error)
|
|
500
|
+
const topic = asTrimmedString(cfg.topic)
|
|
501
|
+
if (!topic) {
|
|
502
|
+
pushErr('topic is required.')
|
|
503
|
+
} else if (/[/?#\x00-\x1f]/.test(topic)) {
|
|
504
|
+
pushErr('topic contains invalid characters.')
|
|
505
|
+
}
|
|
506
|
+
const authType = asTrimmedString(cfg.authType) || 'none'
|
|
507
|
+
if (!NTFY_AUTH_TYPES.has(authType)) {
|
|
508
|
+
pushErr(`Invalid authType: ${authType}`)
|
|
509
|
+
} else if (authType === 'bearer' && !asTrimmedString(cfg.authToken)) {
|
|
510
|
+
pushErr('authToken is required for bearer authentication.')
|
|
511
|
+
} else if (authType === 'basic' && (!asTrimmedString(cfg.basicUsername) || !asTrimmedString(cfg.basicPassword))) {
|
|
512
|
+
pushErr('basicUsername and basicPassword are required for basic authentication.')
|
|
513
|
+
}
|
|
514
|
+
break
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
case 'gotify': {
|
|
518
|
+
const urlCheck = validateHttpUrl(cfg.serverUrl, 'serverUrl')
|
|
519
|
+
if (!urlCheck.valid) pushErr(urlCheck.error)
|
|
520
|
+
if (!asTrimmedString(cfg.appToken)) {
|
|
521
|
+
pushErr('appToken is required.')
|
|
522
|
+
}
|
|
523
|
+
const prioRaw = asTrimmedString(cfg.priority)
|
|
524
|
+
if (prioRaw && !Number.isInteger(Number(prioRaw))) {
|
|
525
|
+
pushErr('priority must be an integer.')
|
|
526
|
+
}
|
|
527
|
+
break
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
case 'custom': {
|
|
531
|
+
const method = (asTrimmedString(cfg.method) || 'POST').toUpperCase()
|
|
532
|
+
if (!CUSTOM_METHODS.has(method)) {
|
|
533
|
+
pushErr(`Unsupported HTTP method: ${method}`)
|
|
534
|
+
}
|
|
535
|
+
const urlCheck = validateHttpUrl(cfg.url, 'url')
|
|
536
|
+
if (!urlCheck.valid) pushErr(urlCheck.error)
|
|
537
|
+
const bodyType = (asTrimmedString(cfg.bodyType) || 'json').toLowerCase()
|
|
538
|
+
if (!CUSTOM_BODY_TYPES.has(bodyType)) {
|
|
539
|
+
pushErr(`Unsupported bodyType: ${bodyType}`)
|
|
540
|
+
}
|
|
541
|
+
const headerCheck = validateCustomHeaders(cfg.headers)
|
|
542
|
+
if (!headerCheck.valid) pushErr(headerCheck.error)
|
|
543
|
+
if (method === 'POST' && bodyType === 'json') {
|
|
544
|
+
const jsonTemplate = asTrimmedString(cfg.jsonBody) || '{"title":"{{title}}","body":"{{body}}"}'
|
|
545
|
+
try {
|
|
546
|
+
JSON.parse(jsonTemplate)
|
|
547
|
+
} catch {
|
|
548
|
+
pushErr('jsonBody must be valid JSON.')
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
break
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return errors.length === 0 ? { valid: true } : { valid: false, error: errors[0], errors }
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function getTemplateVars(message = {}) {
|
|
559
|
+
return {
|
|
560
|
+
title: String(message.title ?? ''),
|
|
561
|
+
body: String(message.body ?? ''),
|
|
562
|
+
event: String(message.event ?? ''),
|
|
563
|
+
source: String(message.source ?? 'DSH'),
|
|
564
|
+
project: String(message.project ?? ''),
|
|
565
|
+
time: String(message.time ?? ''),
|
|
566
|
+
id: String(message.id ?? ''),
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function applyTemplate(str, vars, { urlEncode = false } = {}) {
|
|
571
|
+
return String(str).replace(/\{\{(title|body|event|source|project|time|id)\}\}/g, (_, key) => {
|
|
572
|
+
const val = vars[key] ?? ''
|
|
573
|
+
return urlEncode ? encodeURIComponent(val) : val
|
|
574
|
+
})
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function replaceJsonLeaves(node, vars) {
|
|
578
|
+
if (typeof node === 'string') {
|
|
579
|
+
return applyTemplate(node, vars)
|
|
580
|
+
}
|
|
581
|
+
if (Array.isArray(node)) {
|
|
582
|
+
return node.map((item) => replaceJsonLeaves(item, vars))
|
|
583
|
+
}
|
|
584
|
+
if (node && typeof node === 'object') {
|
|
585
|
+
const out = {}
|
|
586
|
+
for (const [k, v] of Object.entries(node)) {
|
|
587
|
+
out[k] = replaceJsonLeaves(v, vars)
|
|
588
|
+
}
|
|
589
|
+
return out
|
|
590
|
+
}
|
|
591
|
+
return node
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function buildProviderRequest(provider, cfg, message) {
|
|
595
|
+
const title = String(message?.title ?? 'DSH Hook')
|
|
596
|
+
const body = String(message?.body ?? title)
|
|
597
|
+
|
|
598
|
+
switch (provider) {
|
|
599
|
+
case 'dingtalk': {
|
|
600
|
+
const url = new URL(asTrimmedString(cfg.webhookUrl))
|
|
601
|
+
const secret = asTrimmedString(cfg.secret)
|
|
602
|
+
if (secret) {
|
|
603
|
+
const ts = String(Date.now())
|
|
604
|
+
const sign = createHmac('sha256', secret).update(`${ts}\n${secret}`, 'utf8').digest('base64')
|
|
605
|
+
url.searchParams.set('timestamp', ts)
|
|
606
|
+
url.searchParams.set('sign', sign)
|
|
607
|
+
}
|
|
608
|
+
return {
|
|
609
|
+
url,
|
|
610
|
+
method: 'POST',
|
|
611
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
612
|
+
body: JSON.stringify({ msgtype: 'text', text: { content: body } }),
|
|
613
|
+
evaluate(status, json) {
|
|
614
|
+
const code = json?.errcode ?? null
|
|
615
|
+
const accepted = status >= 200 && status < 300 && json?.errcode === 0
|
|
616
|
+
return {
|
|
617
|
+
accepted,
|
|
618
|
+
code,
|
|
619
|
+
message: accepted ? 'OK' : truncateMessage(json?.errmsg || `DingTalk error (HTTP ${status})`),
|
|
620
|
+
deliveryId: null,
|
|
621
|
+
}
|
|
622
|
+
},
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
case 'feishu': {
|
|
627
|
+
const url = new URL(asTrimmedString(cfg.webhookUrl))
|
|
628
|
+
const secret = asTrimmedString(cfg.secret)
|
|
629
|
+
const payload = { msg_type: 'text', content: { text: body } }
|
|
630
|
+
if (secret) {
|
|
631
|
+
const ts = String(Math.floor(Date.now() / 1000))
|
|
632
|
+
const key = `${ts}\n${secret}`
|
|
633
|
+
payload.timestamp = ts
|
|
634
|
+
payload.sign = createHmac('sha256', Buffer.from(key, 'utf8')).update(Buffer.alloc(0)).digest('base64')
|
|
635
|
+
}
|
|
636
|
+
return {
|
|
637
|
+
url,
|
|
638
|
+
method: 'POST',
|
|
639
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
640
|
+
body: JSON.stringify(payload),
|
|
641
|
+
evaluate(status, json) {
|
|
642
|
+
const code = json?.code ?? null
|
|
643
|
+
const accepted = status >= 200 && status < 300 && json?.code === 0
|
|
644
|
+
return {
|
|
645
|
+
accepted,
|
|
646
|
+
code,
|
|
647
|
+
message: accepted ? 'OK' : truncateMessage(json?.msg || `Feishu error (HTTP ${status})`),
|
|
648
|
+
deliveryId: null,
|
|
649
|
+
}
|
|
650
|
+
},
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
case 'wecom': {
|
|
655
|
+
const url = new URL(asTrimmedString(cfg.webhookUrl))
|
|
656
|
+
return {
|
|
657
|
+
url,
|
|
658
|
+
method: 'POST',
|
|
659
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
660
|
+
body: JSON.stringify({ msgtype: 'text', text: { content: body } }),
|
|
661
|
+
evaluate(status, json) {
|
|
662
|
+
const code = json?.errcode ?? null
|
|
663
|
+
const accepted = status >= 200 && status < 300 && json?.errcode === 0
|
|
664
|
+
return {
|
|
665
|
+
accepted,
|
|
666
|
+
code,
|
|
667
|
+
message: accepted ? 'OK' : truncateMessage(json?.errmsg || `WeCom error (HTTP ${status})`),
|
|
668
|
+
deliveryId: null,
|
|
669
|
+
}
|
|
670
|
+
},
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
case 'bark': {
|
|
675
|
+
const base = (asTrimmedString(cfg.serverUrl) || 'https://api.day.app').replace(/\/+$/, '')
|
|
676
|
+
const url = new URL(`${base}/${encodeURIComponent(asTrimmedString(cfg.deviceKey))}`)
|
|
677
|
+
const headers = { 'Content-Type': 'application/json; charset=utf-8' }
|
|
678
|
+
const user = asTrimmedString(cfg.basicUsername)
|
|
679
|
+
const pass = asTrimmedString(cfg.basicPassword)
|
|
680
|
+
if (user && pass) {
|
|
681
|
+
headers.Authorization = `Basic ${Buffer.from(`${user}:${pass}`, 'utf8').toString('base64')}`
|
|
682
|
+
}
|
|
683
|
+
const payload = { title, body }
|
|
684
|
+
const group = asTrimmedString(cfg.group)
|
|
685
|
+
const sound = asTrimmedString(cfg.sound)
|
|
686
|
+
const level = asTrimmedString(cfg.level)
|
|
687
|
+
if (group) payload.group = group
|
|
688
|
+
if (sound) payload.sound = sound
|
|
689
|
+
if (level) payload.level = level
|
|
690
|
+
return {
|
|
691
|
+
url,
|
|
692
|
+
method: 'POST',
|
|
693
|
+
headers,
|
|
694
|
+
body: JSON.stringify(payload),
|
|
695
|
+
evaluate(status, json) {
|
|
696
|
+
const code = json?.code ?? null
|
|
697
|
+
const accepted = status >= 200 && status < 300 && json?.code === 200
|
|
698
|
+
return {
|
|
699
|
+
accepted,
|
|
700
|
+
code,
|
|
701
|
+
message: accepted ? 'OK' : truncateMessage(json?.message || `Bark error (HTTP ${status})`),
|
|
702
|
+
deliveryId: null,
|
|
703
|
+
}
|
|
704
|
+
},
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
case 'pushplus': {
|
|
709
|
+
const url = new URL('https://www.pushplus.plus/send')
|
|
710
|
+
const payload = {
|
|
711
|
+
token: asTrimmedString(cfg.token),
|
|
712
|
+
title,
|
|
713
|
+
content: body,
|
|
714
|
+
template: asTrimmedString(cfg.template) || 'txt',
|
|
715
|
+
}
|
|
716
|
+
const channel = asTrimmedString(cfg.channel)
|
|
717
|
+
const topic = asTrimmedString(cfg.topic)
|
|
718
|
+
const webhook = asTrimmedString(cfg.webhook)
|
|
719
|
+
if (channel) payload.channel = channel
|
|
720
|
+
if (topic) payload.topic = topic
|
|
721
|
+
if (webhook) payload.webhook = webhook
|
|
722
|
+
return {
|
|
723
|
+
url,
|
|
724
|
+
method: 'POST',
|
|
725
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
726
|
+
body: JSON.stringify(payload),
|
|
727
|
+
evaluate(status, json) {
|
|
728
|
+
const code = json?.code ?? null
|
|
729
|
+
const accepted = status >= 200 && status < 300 && json?.code === 200
|
|
730
|
+
return {
|
|
731
|
+
accepted,
|
|
732
|
+
code,
|
|
733
|
+
message: accepted ? 'OK' : truncateMessage(json?.msg || `PushPlus error (HTTP ${status})`),
|
|
734
|
+
deliveryId: json?.data != null ? String(json.data) : null,
|
|
735
|
+
}
|
|
736
|
+
},
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
case 'wxpusher': {
|
|
741
|
+
const url = new URL('https://wxpusher.zjiecode.com/api/send/message')
|
|
742
|
+
const payload = {
|
|
743
|
+
content: body,
|
|
744
|
+
summary: title,
|
|
745
|
+
contentType: 1,
|
|
746
|
+
}
|
|
747
|
+
const spt = asTrimmedString(cfg.spt)
|
|
748
|
+
if (spt) {
|
|
749
|
+
payload.spt = spt
|
|
750
|
+
} else {
|
|
751
|
+
payload.appToken = asTrimmedString(cfg.appToken)
|
|
752
|
+
const uids = parseCsvStrings(cfg.uids)
|
|
753
|
+
if (uids.length > 0) payload.uids = uids
|
|
754
|
+
const topicIds = parseNumberCsv(cfg.topicIds)
|
|
755
|
+
if (topicIds.valid && topicIds.values.length > 0) payload.topicIds = topicIds.values
|
|
756
|
+
}
|
|
757
|
+
return {
|
|
758
|
+
url,
|
|
759
|
+
method: 'POST',
|
|
760
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
761
|
+
body: JSON.stringify(payload),
|
|
762
|
+
evaluate(status, json) {
|
|
763
|
+
const code = json?.code ?? null
|
|
764
|
+
const accepted = status >= 200 && status < 300 && json?.code === 1000
|
|
765
|
+
return {
|
|
766
|
+
accepted,
|
|
767
|
+
code,
|
|
768
|
+
message: accepted ? 'OK' : truncateMessage(json?.msg || `WxPusher error (HTTP ${status})`),
|
|
769
|
+
deliveryId: null,
|
|
770
|
+
}
|
|
771
|
+
},
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
case 'serverchan': {
|
|
776
|
+
const sendKey = asTrimmedString(cfg.sendKey)
|
|
777
|
+
const url = sendKey.startsWith('sctp')
|
|
778
|
+
? new URL(`https://${sendKey}.push.ft07.com/send`)
|
|
779
|
+
: new URL(`https://sctapi.ftqq.com/${sendKey}.send`)
|
|
780
|
+
return {
|
|
781
|
+
url,
|
|
782
|
+
method: 'POST',
|
|
783
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
|
|
784
|
+
body: new URLSearchParams({ title, desp: body }).toString(),
|
|
785
|
+
evaluate(status, json) {
|
|
786
|
+
const code = json?.code ?? null
|
|
787
|
+
const accepted = status >= 200 && status < 300 && json?.code === 0
|
|
788
|
+
return {
|
|
789
|
+
accepted,
|
|
790
|
+
code,
|
|
791
|
+
message: accepted ? 'OK' : truncateMessage(json?.message || json?.errmsg || `ServerChan error (HTTP ${status})`),
|
|
792
|
+
deliveryId: json?.data?.pushid != null ? String(json.data.pushid) : null,
|
|
793
|
+
}
|
|
794
|
+
},
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
case 'telegram': {
|
|
799
|
+
const botToken = asTrimmedString(cfg.botToken)
|
|
800
|
+
const url = new URL(`https://api.telegram.org/bot${botToken}/sendMessage`)
|
|
801
|
+
const payload = {
|
|
802
|
+
chat_id: asTrimmedString(cfg.chatId),
|
|
803
|
+
text: body,
|
|
804
|
+
disable_web_page_preview: true,
|
|
805
|
+
}
|
|
806
|
+
const threadRaw = asTrimmedString(cfg.messageThreadId)
|
|
807
|
+
if (threadRaw) {
|
|
808
|
+
payload.message_thread_id = Number(threadRaw)
|
|
809
|
+
}
|
|
810
|
+
return {
|
|
811
|
+
url,
|
|
812
|
+
method: 'POST',
|
|
813
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
814
|
+
body: JSON.stringify(payload),
|
|
815
|
+
evaluate(status, json) {
|
|
816
|
+
const accepted = status >= 200 && status < 300 && json?.ok === true
|
|
817
|
+
return {
|
|
818
|
+
accepted,
|
|
819
|
+
code: json?.error_code ?? (accepted ? 0 : null),
|
|
820
|
+
message: accepted ? 'OK' : truncateMessage(json?.description || `Telegram error (HTTP ${status})`),
|
|
821
|
+
deliveryId: json?.result?.message_id != null ? String(json.result.message_id) : null,
|
|
822
|
+
}
|
|
823
|
+
},
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
case 'ntfy': {
|
|
828
|
+
const base = (asTrimmedString(cfg.serverUrl) || 'https://ntfy.sh').replace(/\/+$/, '')
|
|
829
|
+
const url = new URL(`${base}/${encodeURIComponent(asTrimmedString(cfg.topic))}`)
|
|
830
|
+
const headers = {
|
|
831
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
832
|
+
Title: encodeHeaderValue(title),
|
|
833
|
+
}
|
|
834
|
+
const priority = asTrimmedString(cfg.priority)
|
|
835
|
+
const tags = asTrimmedString(cfg.tags)
|
|
836
|
+
if (priority) headers.Priority = encodeHeaderValue(priority)
|
|
837
|
+
if (tags) headers.Tags = encodeHeaderValue(tags)
|
|
838
|
+
|
|
839
|
+
const authType = asTrimmedString(cfg.authType) || 'none'
|
|
840
|
+
if (authType === 'bearer') {
|
|
841
|
+
headers.Authorization = `Bearer ${asTrimmedString(cfg.authToken)}`
|
|
842
|
+
} else if (authType === 'basic') {
|
|
843
|
+
const creds = `${asTrimmedString(cfg.basicUsername)}:${asTrimmedString(cfg.basicPassword)}`
|
|
844
|
+
headers.Authorization = `Basic ${Buffer.from(creds, 'utf8').toString('base64')}`
|
|
845
|
+
}
|
|
846
|
+
return {
|
|
847
|
+
url,
|
|
848
|
+
method: 'POST',
|
|
849
|
+
headers,
|
|
850
|
+
body,
|
|
851
|
+
evaluate(status, json) {
|
|
852
|
+
const hasId = typeof json?.id === 'string' && json.id.length > 0
|
|
853
|
+
const accepted = status >= 200 && status < 300 && hasId
|
|
854
|
+
return {
|
|
855
|
+
accepted,
|
|
856
|
+
code: json?.code ?? (accepted ? status : null),
|
|
857
|
+
message: accepted ? 'OK' : truncateMessage(json?.error || `ntfy error (HTTP ${status})`),
|
|
858
|
+
deliveryId: hasId ? json.id : null,
|
|
859
|
+
}
|
|
860
|
+
},
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
case 'gotify': {
|
|
865
|
+
const base = asTrimmedString(cfg.serverUrl).replace(/\/+$/, '')
|
|
866
|
+
const url = new URL(`${base}/message`)
|
|
867
|
+
url.searchParams.set('token', asTrimmedString(cfg.appToken))
|
|
868
|
+
const priorityRaw = asTrimmedString(cfg.priority)
|
|
869
|
+
const priority = priorityRaw === '' ? 5 : Math.trunc(Number(priorityRaw))
|
|
870
|
+
return {
|
|
871
|
+
url,
|
|
872
|
+
method: 'POST',
|
|
873
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
874
|
+
body: JSON.stringify({ title, message: body, priority }),
|
|
875
|
+
evaluate(status, json) {
|
|
876
|
+
const hasId = json?.id !== undefined && json?.id !== null
|
|
877
|
+
const accepted = status >= 200 && status < 300 && hasId
|
|
878
|
+
return {
|
|
879
|
+
accepted,
|
|
880
|
+
code: json?.errorCode ?? (accepted ? status : null),
|
|
881
|
+
message: accepted ? 'OK' : truncateMessage(json?.errorDescription || json?.error || `Gotify error (HTTP ${status})`),
|
|
882
|
+
deliveryId: hasId ? String(json.id) : null,
|
|
883
|
+
}
|
|
884
|
+
},
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
case 'custom': {
|
|
889
|
+
const vars = getTemplateVars(message)
|
|
890
|
+
const method = (asTrimmedString(cfg.method) || 'POST').toUpperCase()
|
|
891
|
+
const renderedUrl = applyTemplate(asTrimmedString(cfg.url), vars, { urlEncode: true })
|
|
892
|
+
const url = new URL(renderedUrl)
|
|
893
|
+
if (url.username || url.password || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
|
|
894
|
+
throw new Error('Invalid rendered custom URL')
|
|
895
|
+
}
|
|
896
|
+
for (const { key, value } of parseKvLines(cfg.query)) {
|
|
897
|
+
url.searchParams.append(key, applyTemplate(value, vars))
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
const headers = {}
|
|
901
|
+
let hasContentType = false
|
|
902
|
+
for (const { key, value } of parseKvLines(cfg.headers)) {
|
|
903
|
+
if (key.toLowerCase() === 'content-type') hasContentType = true
|
|
904
|
+
headers[key] = encodeHeaderValue(applyTemplate(value, vars))
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
let reqBody
|
|
908
|
+
if (method === 'POST') {
|
|
909
|
+
const bodyType = (asTrimmedString(cfg.bodyType) || 'json').toLowerCase()
|
|
910
|
+
if (bodyType === 'json') {
|
|
911
|
+
if (!hasContentType) headers['Content-Type'] = 'application/json; charset=utf-8'
|
|
912
|
+
const parsed = JSON.parse(asTrimmedString(cfg.jsonBody) || '{"title":"{{title}}","body":"{{body}}"}')
|
|
913
|
+
reqBody = JSON.stringify(replaceJsonLeaves(parsed, vars))
|
|
914
|
+
} else if (bodyType === 'form') {
|
|
915
|
+
if (!hasContentType) headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
|
|
916
|
+
const params = new URLSearchParams()
|
|
917
|
+
for (const { key, value } of parseKvLines(cfg.formBody)) {
|
|
918
|
+
params.append(key, applyTemplate(value, vars))
|
|
919
|
+
}
|
|
920
|
+
reqBody = params.toString()
|
|
921
|
+
} else {
|
|
922
|
+
if (!hasContentType) headers['Content-Type'] = 'text/plain; charset=utf-8'
|
|
923
|
+
reqBody = applyTemplate(cfg.textBody == null ? '{{body}}' : String(cfg.textBody), vars)
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
return {
|
|
928
|
+
url,
|
|
929
|
+
method,
|
|
930
|
+
headers,
|
|
931
|
+
body: reqBody,
|
|
932
|
+
evaluate(status, json, rawText) {
|
|
933
|
+
const accepted = status >= 200 && status < 300
|
|
934
|
+
return {
|
|
935
|
+
accepted,
|
|
936
|
+
code: status,
|
|
937
|
+
message: accepted ? 'OK' : truncateMessage(json?.message || json?.error || rawText || `HTTP ${status}`),
|
|
938
|
+
deliveryId: json?.id != null ? String(json.id) : null,
|
|
939
|
+
}
|
|
940
|
+
},
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
default:
|
|
945
|
+
throw new Error(`Unsupported provider: ${provider}`)
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
async function readCappedBodyText(response) {
|
|
950
|
+
if (response?.body && typeof response.body.getReader === 'function') {
|
|
951
|
+
const reader = response.body.getReader()
|
|
952
|
+
const chunks = []
|
|
953
|
+
let total = 0
|
|
954
|
+
try {
|
|
955
|
+
while (true) {
|
|
956
|
+
const { done, value } = await reader.read()
|
|
957
|
+
if (done) break
|
|
958
|
+
if (!value || value.byteLength === 0) continue
|
|
959
|
+
const remaining = MAX_RESPONSE_BYTES - total
|
|
960
|
+
if (remaining <= 0) {
|
|
961
|
+
await reader.cancel().catch(() => {})
|
|
962
|
+
break
|
|
963
|
+
}
|
|
964
|
+
const slice = value.byteLength > remaining ? value.subarray(0, remaining) : value
|
|
965
|
+
chunks.push(slice)
|
|
966
|
+
total += slice.byteLength
|
|
967
|
+
if (total >= MAX_RESPONSE_BYTES) {
|
|
968
|
+
await reader.cancel().catch(() => {})
|
|
969
|
+
break
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
} finally {
|
|
973
|
+
try {
|
|
974
|
+
reader.releaseLock?.()
|
|
975
|
+
} catch {
|
|
976
|
+
// Ignore release errors
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
return Buffer.concat(chunks.map((c) => Buffer.from(c.buffer, c.byteOffset, c.byteLength))).toString('utf8')
|
|
980
|
+
}
|
|
981
|
+
if (typeof response?.text === 'function') {
|
|
982
|
+
const text = await response.text()
|
|
983
|
+
return typeof text === 'string' ? text.slice(0, MAX_RESPONSE_BYTES) : ''
|
|
984
|
+
}
|
|
985
|
+
if (typeof response?.json === 'function') {
|
|
986
|
+
const json = await response.json()
|
|
987
|
+
return JSON.stringify(json ?? null).slice(0, MAX_RESPONSE_BYTES)
|
|
988
|
+
}
|
|
989
|
+
return ''
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/**
|
|
993
|
+
* Dispatch a redacted notification message to a single third-party provider target.
|
|
994
|
+
* Never logs or returns secrets or full URLs (errors reference host only).
|
|
995
|
+
*/
|
|
996
|
+
export async function sendToProvider(
|
|
997
|
+
provider,
|
|
998
|
+
mergedConfig,
|
|
999
|
+
message,
|
|
1000
|
+
{ fetchImpl = globalThis.fetch, signal, timeoutMs = DEFAULT_TIMEOUT_MS } = {},
|
|
1001
|
+
) {
|
|
1002
|
+
const check = validateProviderConfig(provider, mergedConfig)
|
|
1003
|
+
if (!check.valid) {
|
|
1004
|
+
return {
|
|
1005
|
+
accepted: false,
|
|
1006
|
+
httpStatus: null,
|
|
1007
|
+
code: null,
|
|
1008
|
+
message: truncateMessage(check.error || 'Invalid provider configuration'),
|
|
1009
|
+
deliveryId: null,
|
|
1010
|
+
errorCode: 'provider/invalid-config',
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
if (typeof fetchImpl !== 'function') {
|
|
1014
|
+
return {
|
|
1015
|
+
accepted: false,
|
|
1016
|
+
httpStatus: null,
|
|
1017
|
+
code: null,
|
|
1018
|
+
message: 'Fetch implementation is unavailable.',
|
|
1019
|
+
deliveryId: null,
|
|
1020
|
+
errorCode: 'provider/network',
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
if (signal?.aborted) {
|
|
1024
|
+
return {
|
|
1025
|
+
accepted: false,
|
|
1026
|
+
httpStatus: null,
|
|
1027
|
+
code: null,
|
|
1028
|
+
message: 'Request aborted.',
|
|
1029
|
+
deliveryId: null,
|
|
1030
|
+
errorCode: 'provider/aborted',
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
let spec
|
|
1035
|
+
try {
|
|
1036
|
+
spec = buildProviderRequest(provider, mergedConfig || {}, message)
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
return {
|
|
1039
|
+
accepted: false,
|
|
1040
|
+
httpStatus: null,
|
|
1041
|
+
code: null,
|
|
1042
|
+
message: truncateMessage(error?.message || 'Failed to build provider request'),
|
|
1043
|
+
deliveryId: null,
|
|
1044
|
+
errorCode: 'provider/invalid-config',
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
const host = spec.url.host
|
|
1049
|
+
const boundedTimeout =
|
|
1050
|
+
Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(Math.round(timeoutMs), 60_000) : DEFAULT_TIMEOUT_MS
|
|
1051
|
+
|
|
1052
|
+
const localTimeout = new AbortController()
|
|
1053
|
+
const combinedSignal = signal ? AbortSignal.any([signal, localTimeout.signal]) : localTimeout.signal
|
|
1054
|
+
|
|
1055
|
+
let timer
|
|
1056
|
+
let onAbort
|
|
1057
|
+
const abortPromise = new Promise((_, reject) => {
|
|
1058
|
+
onAbort = () => reject(new Error(signal?.aborted ? 'aborted' : 'timeout'))
|
|
1059
|
+
combinedSignal.addEventListener('abort', onAbort, { once: true })
|
|
1060
|
+
timer = setTimeout(() => {
|
|
1061
|
+
localTimeout.abort(new DOMException(`Timed out after ${boundedTimeout}ms`, 'TimeoutError'))
|
|
1062
|
+
}, boundedTimeout)
|
|
1063
|
+
timer.unref?.()
|
|
1064
|
+
})
|
|
1065
|
+
|
|
1066
|
+
try {
|
|
1067
|
+
const execute = async () => {
|
|
1068
|
+
const response = await fetchImpl(spec.url.href, {
|
|
1069
|
+
method: spec.method,
|
|
1070
|
+
headers: spec.headers,
|
|
1071
|
+
body: spec.body,
|
|
1072
|
+
redirect: 'error',
|
|
1073
|
+
credentials: 'omit',
|
|
1074
|
+
signal: combinedSignal,
|
|
1075
|
+
})
|
|
1076
|
+
|
|
1077
|
+
const httpStatus = response?.status ?? null
|
|
1078
|
+
if (response?.redirected) {
|
|
1079
|
+
void response.body?.cancel?.().catch(() => {})
|
|
1080
|
+
return {
|
|
1081
|
+
accepted: false,
|
|
1082
|
+
httpStatus,
|
|
1083
|
+
code: null,
|
|
1084
|
+
message: `Redirect blocked for ${host}`,
|
|
1085
|
+
deliveryId: null,
|
|
1086
|
+
errorCode: 'provider/redirect',
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
const rawText = await readCappedBodyText(response)
|
|
1091
|
+
let json = null
|
|
1092
|
+
if (rawText) {
|
|
1093
|
+
try {
|
|
1094
|
+
json = JSON.parse(rawText)
|
|
1095
|
+
} catch {
|
|
1096
|
+
json = null
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
const verdict = spec.evaluate(Number(httpStatus), json, rawText)
|
|
1101
|
+
return {
|
|
1102
|
+
accepted: Boolean(verdict.accepted),
|
|
1103
|
+
httpStatus,
|
|
1104
|
+
code: verdict.code ?? null,
|
|
1105
|
+
message: truncateMessage(verdict.message || (verdict.accepted ? 'OK' : `HTTP ${httpStatus}`)),
|
|
1106
|
+
deliveryId: verdict.deliveryId ?? null,
|
|
1107
|
+
errorCode: verdict.accepted
|
|
1108
|
+
? null
|
|
1109
|
+
: httpStatus && (httpStatus < 200 || httpStatus >= 300)
|
|
1110
|
+
? 'provider/http'
|
|
1111
|
+
: 'provider/rejected',
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
return await Promise.race([execute(), abortPromise])
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
const isTimeout = localTimeout.signal.aborted || error?.name === 'TimeoutError' || error?.message === 'timeout'
|
|
1118
|
+
const isAborted = !isTimeout && Boolean(signal?.aborted)
|
|
1119
|
+
return {
|
|
1120
|
+
accepted: false,
|
|
1121
|
+
httpStatus: null,
|
|
1122
|
+
code: null,
|
|
1123
|
+
message: truncateMessage(
|
|
1124
|
+
isAborted
|
|
1125
|
+
? `Request aborted (${host})`
|
|
1126
|
+
: isTimeout
|
|
1127
|
+
? `Request timed out after ${boundedTimeout}ms (${host})`
|
|
1128
|
+
: `Network request failed (${host})`,
|
|
1129
|
+
),
|
|
1130
|
+
deliveryId: null,
|
|
1131
|
+
errorCode: isAborted ? 'provider/aborted' : isTimeout ? 'provider/timeout' : 'provider/network',
|
|
1132
|
+
}
|
|
1133
|
+
} finally {
|
|
1134
|
+
clearTimeout(timer)
|
|
1135
|
+
combinedSignal.removeEventListener('abort', onAbort)
|
|
1136
|
+
}
|
|
1137
|
+
}
|