-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
693 lines (618 loc) · 24 KB
/
Copy pathworker.js
File metadata and controls
693 lines (618 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
const PUSHPLUS_BASE_URL = 'https://www.pushplus.plus';
const TELEGRAM_MAX_LENGTH = 3900;
const FORWARDED_TTL_SECONDS = 60 * 60 * 24 * 180;
const INBOX_TTL_SECONDS = 60 * 60 * 6;
const DEFAULT_CLEANUP_RETENTION_DAYS = 90;
const DEFAULT_CLEANUP_PAGE_SIZE = 50;
const DEFAULT_CLEANUP_MAX_PAGES = 10;
const DEFAULT_CLEANUP_MAX_DELETES = 20;
function jsonResponse(body, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json; charset=utf-8' },
});
}
function pushPlusSuccessResponse() {
return new Response('{"code": 200, "msg": "success"}', {
status: 200,
headers: {
'content-type': 'application/json; charset=utf-8',
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, HEAD, POST, OPTIONS',
'access-control-allow-headers': 'content-type, authorization',
},
});
}
function decodeHtmlEntities(text) {
return String(text || '')
.replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)))
.replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16)))
.replace(/ /gi, ' ')
.replace(/</gi, '<')
.replace(/>/gi, '>')
.replace(/"/gi, '"')
.replace(/'/g, "'")
.replace(/&/gi, '&');
}
function htmlToText(html) {
return decodeHtmlEntities(String(html || '')
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ')
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p\s*>/gi, '\n')
.replace(/<\/div\s*>/gi, '\n')
.replace(/<\/li\s*>/gi, '\n')
.replace(/<[^>]+>/g, ' '))
.replace(/[ \t\f\v]+/g, ' ')
.replace(/\n\s+/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
function pickField(text, labels) {
const source = String(text || '');
for (const label of labels) {
const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const match = source.match(new RegExp(`${escaped}\\s*[::]\\s*([^\\n\\r]+)`));
if (match) return match[1].trim();
}
return '';
}
function parseSmsFields(text) {
return {
sender: pickField(text, ['发件号码', '发信号码', '发送号码', 'sender', 'from']),
sentAt: pickField(text, ['发件时间', '发信时间', '发送时间', 'sentAt', 'time']),
};
}
function compactText(text) {
return String(text || '').replace(/\s+/g, '');
}
function listValue(value) {
if (Array.isArray(value)) return value.filter(item => item !== undefined && item !== null && item !== '');
if (value === undefined || value === null || value === '') return [];
return [value];
}
function splitCsv(value) {
return String(value || '')
.split(',')
.map(item => item.trim())
.filter(Boolean);
}
function collectValues(rule, keys) {
return keys.flatMap(key => listValue(rule[key]));
}
function includesAll(source, expected) {
const normalized = compactText(source);
return expected.every(item => normalized.includes(compactText(item)));
}
function includesAny(source, expected) {
if (!expected.length) return true;
const normalized = compactText(source);
return expected.some(item => normalized.includes(compactText(item)));
}
function isTruthy(value) {
return /^(1|true|yes)$/i.test(String(value || ''));
}
function numberEnv(env, name, fallback, { min = 0, max = Number.MAX_SAFE_INTEGER } = {}) {
const raw = env[name];
if (raw === undefined || raw === null || raw === '') return fallback;
const parsed = Number(raw);
if (!Number.isFinite(parsed)) throw new Error(`Invalid numeric env ${name}: ${raw}`);
return Math.max(min, Math.min(Math.floor(parsed), max));
}
function parsePushPlusUpdateTime(value) {
if (value === undefined || value === null || value === '') return 0;
if (typeof value === 'number') return value < 1e12 ? value * 1000 : value;
const text = String(value).trim();
if (/^\d+$/.test(text)) {
const timestamp = Number(text);
return timestamp < 1e12 ? timestamp * 1000 : timestamp;
}
if (/([zZ]|[+-]\d\d:?\d\d)$/.test(text)) {
const parsed = Date.parse(text);
return Number.isNaN(parsed) ? 0 : parsed;
}
const m = text.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/);
if (m) {
const [, year, month, day, hour, minute, second = '0'] = m;
return Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour) - 8, Number(minute), Number(second));
}
const parsed = Date.parse(text);
return Number.isNaN(parsed) ? 0 : parsed;
}
function messageMatchesRule(message, rule) {
const text = typeof message === 'string' ? message : message?.text || '';
const title = typeof message === 'string' ? '' : message?.title || '';
const fields = parseSmsFields(text);
const sender = fields.sender || (typeof message === 'string' ? '' : message?.sender || '');
const senderIncludes = collectValues(rule, ['sender', 'senderIncludes']);
if (senderIncludes.length && !includesAny(sender || text, senderIncludes)) return false;
const titleIncludesAll = collectValues(rule, ['titleIncludes', 'titleIncludesAll']);
if (titleIncludesAll.length && !includesAll(title, titleIncludesAll)) return false;
const titleIncludesAny = collectValues(rule, ['titleIncludesAny']);
if (titleIncludesAny.length && !includesAny(title, titleIncludesAny)) return false;
const textIncludesAll = collectValues(rule, ['textIncludes', 'textIncludesAll', 'bodyIncludes', 'bodyIncludesAll']);
if (textIncludesAll.length && !includesAll(text, textIncludesAll)) return false;
const textIncludesAny = collectValues(rule, ['textIncludesAny', 'bodyIncludesAny']);
if (textIncludesAny.length && !includesAny(text, textIncludesAny)) return false;
return true;
}
function telecomClaimPresetRules(env) {
const sender = env.TELECOM_SMS_SENDER || '10001';
const confirmTextIncludes = ['【办理提醒】', '验证码是', '中国电信北京公司', '办理'];
if (env.TELECOM_CONFIRM_PRODUCT_KEYWORD) confirmTextIncludes.push(env.TELECOM_CONFIRM_PRODUCT_KEYWORD);
if (env.TELECOM_CONFIRM_PLAN_ID) confirmTextIncludes.push(env.TELECOM_CONFIRM_PLAN_ID);
return [
{
name: 'telecom-claim-login',
action: 'silence',
store: true,
senderIncludes: sender,
textIncludesAll: ['验证码', '感谢使用北京电信掌上营业厅'],
},
{
name: 'telecom-claim-confirm',
action: 'silence',
store: true,
senderIncludes: sender,
textIncludesAll: confirmTextIncludes,
},
];
}
function parseCustomRules(value) {
if (!value) return [];
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed : [parsed];
}
function loadInterceptRules(env) {
const presets = splitCsv(env.SMS_INTERCEPT_PRESETS);
if (isTruthy(env.TELECOM_CLAIM_SILENT)) presets.push('telecom-claim-silent');
const rules = [];
for (const preset of presets) {
if (preset === 'telecom-claim-silent') {
rules.push(...telecomClaimPresetRules(env));
}
}
rules.push(...parseCustomRules(env.SMS_INTERCEPT_RULES));
return rules;
}
function findInterceptRule(message, env) {
return loadInterceptRules(env).find(rule => messageMatchesRule(message, rule)) || null;
}
function interceptAction(rule) {
return String(rule?.action || 'silence').toLowerCase();
}
function interceptShouldStore(rule) {
return rule?.store === true || /store/.test(interceptAction(rule));
}
function interceptShouldSilence(rule) {
return /silence/.test(interceptAction(rule));
}
function isLabeledLine(line, labels) {
return labels.some(label => {
const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`^${escaped}\\s*[::]`).test(line);
});
}
function extractSmsContent(text) {
const lines = String(text || '')
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean);
const metadataLabels = [
'标题',
'链接',
'发件号码',
'发信号码',
'发送号码',
'发件时间',
'发信时间',
'发送时间',
'本机号码',
'开机时长',
'运营商',
'信号',
'sender',
'from',
'sentAt',
'time',
];
const contentLines = [];
for (const line of lines) {
if (/^#SMS\b/i.test(line)) {
if (contentLines.length) break;
continue;
}
if (isLabeledLine(line, metadataLabels)) {
if (contentLines.length) break;
continue;
}
contentLines.push(line);
}
return contentLines.join('\n');
}
function escapeTelegramHtml(text) {
return String(text || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function buildTelegramText(message) {
const fields = parseSmsFields(message.text);
const smsContent = extractSmsContent(message.text);
return [
'📩 <b>PushPlus SMS</b>',
`发件人:${escapeTelegramHtml(fields.sender || '-')}`,
`发件时间:${escapeTelegramHtml(fields.sentAt || '-')}`,
'',
'<b>短信内容:</b>',
escapeTelegramHtml(smsContent || '-'),
].join('\n');
}
function splitTelegramText(text, maxLength = TELEGRAM_MAX_LENGTH) {
const source = String(text || '');
if (source.length <= maxLength) return [source];
const chunks = [];
let rest = source;
while (rest.length > maxLength) {
let cut = rest.lastIndexOf('\n', maxLength);
if (cut < Math.floor(maxLength * 0.6)) cut = maxLength;
chunks.push(rest.slice(0, cut));
rest = rest.slice(cut).replace(/^\n+/, '');
}
if (rest) chunks.push(rest);
return chunks;
}
async function sha256Hex(input) {
const data = new TextEncoder().encode(String(input || ''));
const digest = await crypto.subtle.digest('SHA-256', data);
return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join('');
}
async function dedupeKey(shortCode, env) {
return `pushplus:${await sha256Hex(`${env.STATE_SECRET || ''}:${shortCode}`)}`;
}
async function inboxKey(sourceId, receivedAt, env) {
return `inbox:${String(receivedAt || Date.now()).padStart(13, '0')}:${await sha256Hex(`${env.STATE_SECRET || ''}:${sourceId}`)}`;
}
function pushPlusUrl(env, pathname) {
const baseUrl = env.PUSHPLUS_BASE_URL || PUSHPLUS_BASE_URL;
const base = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
return new URL(pathname, base);
}
async function fetchPushPlusDetail(env, shortCode) {
const url = pushPlusUrl(env, `/shortMessage/${encodeURIComponent(shortCode)}`);
const res = await fetch(url, { headers: { accept: 'text/html, text/plain;q=0.9, */*;q=0.8' } });
if (!res.ok) throw new Error(`PushPlus detail HTTP ${res.status}`);
return htmlToText(await res.text());
}
async function pushPlusJson(url, options = {}) {
const res = await fetch(url, options);
const text = await res.text();
let data = {};
try {
data = text ? JSON.parse(text) : {};
} catch {
data = { raw: text };
}
if (!res.ok) throw new Error(`PushPlus HTTP ${res.status} ${new URL(url).pathname}`);
if (data?.code !== 200) throw new Error(`PushPlus API failed: ${data?.msg || 'unknown error'}`);
return data;
}
async function getPushPlusAccessKey(env) {
requireEnv(env, 'PUSHPLUS_TOKEN');
requireEnv(env, 'PUSHPLUS_SECRET_KEY');
const data = await pushPlusJson(pushPlusUrl(env, '/api/common/openApi/getAccessKey'), {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ token: env.PUSHPLUS_TOKEN, secretKey: env.PUSHPLUS_SECRET_KEY }),
});
const accessKey = data?.data?.accessKey;
if (!accessKey) throw new Error('PushPlus access key response missing accessKey');
return accessKey;
}
async function listPushPlusMessages(env, accessKey, current, pageSize) {
const data = await pushPlusJson(pushPlusUrl(env, '/api/open/message/list'), {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json',
'access-key': accessKey,
},
body: JSON.stringify({ current, pageSize }),
});
return {
items: data?.data?.list || [],
pages: Number(data?.data?.pages || 0),
};
}
async function deletePushPlusMessage(env, accessKey, shortCode) {
const url = pushPlusUrl(env, '/api/open/message/deleteMessage');
url.searchParams.set('shortCode', shortCode);
await pushPlusJson(url, {
method: 'DELETE',
headers: { accept: 'application/json', 'access-key': accessKey },
});
}
async function alreadyForwarded(shortCode, env) {
requireEnv(env, 'STATE_SECRET');
if (!env.FORWARDED_KV) throw new Error('Missing KV binding: FORWARDED_KV');
return Boolean(await env.FORWARDED_KV.get(await dedupeKey(shortCode, env)));
}
async function cleanupPushPlusMessages(env) {
if (!isTruthy(env.PUSHPLUS_CLEANUP_ENABLED)) {
return { enabled: false, scanned: 0, candidates: 0, deleted: 0, failed: 0 };
}
const retentionDays = numberEnv(env, 'PUSHPLUS_CLEANUP_RETENTION_DAYS', DEFAULT_CLEANUP_RETENTION_DAYS, { min: 1, max: 3650 });
const pageSize = numberEnv(env, 'PUSHPLUS_CLEANUP_PAGE_SIZE', DEFAULT_CLEANUP_PAGE_SIZE, { min: 1, max: 50 });
const maxPages = numberEnv(env, 'PUSHPLUS_CLEANUP_MAX_PAGES', DEFAULT_CLEANUP_MAX_PAGES, { min: 1, max: 100 });
const maxDeletes = numberEnv(env, 'PUSHPLUS_CLEANUP_MAX_DELETES', DEFAULT_CLEANUP_MAX_DELETES, { min: 1, max: 50 });
const requireForwarded = env.PUSHPLUS_CLEANUP_REQUIRE_FORWARDED === undefined
? true
: isTruthy(env.PUSHPLUS_CLEANUP_REQUIRE_FORWARDED);
const titleKeyword = env.PUSHPLUS_CLEANUP_TITLE_KEYWORD || env.MESSAGE_TITLE_KEYWORD || '';
const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1000;
const accessKey = await getPushPlusAccessKey(env);
const candidates = [];
let scanned = 0;
for (let current = 1; current <= maxPages && candidates.length < maxDeletes; current += 1) {
const { items, pages } = await listPushPlusMessages(env, accessKey, current, pageSize);
if (!items.length) break;
scanned += items.length;
for (const item of items) {
if (candidates.length >= maxDeletes) break;
const shortCode = item?.shortCode || '';
if (!shortCode) continue;
if (titleKeyword && !String(item.title || '').includes(titleKeyword)) continue;
const updatedAt = parsePushPlusUpdateTime(item.updateTime);
if (!updatedAt || updatedAt >= cutoff) continue;
if (requireForwarded && !await alreadyForwarded(shortCode, env)) continue;
candidates.push({
shortCode,
title: item.title || '',
updateTime: item.updateTime || '',
});
}
if (pages && current >= pages) break;
}
let deleted = 0;
let failed = 0;
for (const item of candidates) {
try {
await deletePushPlusMessage(env, accessKey, item.shortCode);
deleted += 1;
} catch (err) {
failed += 1;
console.error(`PushPlus cleanup delete failed: ${err.message}`);
}
}
return { enabled: true, scanned, candidates: candidates.length, deleted, failed };
}
async function sendTelegram({ env, text }) {
const url = `https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/sendMessage`;
const res = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
chat_id: env.TELEGRAM_CHAT_ID,
text,
parse_mode: 'HTML',
disable_web_page_preview: true,
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || data.ok === false) {
throw new Error(`Telegram sendMessage failed: ${data.description || res.status}`);
}
}
function requireEnv(env, name) {
if (!env[name]) throw new Error(`Missing env: ${name}`);
}
function inboxAuthToken(env) {
return env.INBOX_TOKEN || '';
}
function authorizeInboxRequest(request, env, url) {
const expected = inboxAuthToken(env);
if (!expected) return false;
const auth = request.headers.get('authorization') || '';
if (auth.toLowerCase().startsWith('bearer ') && auth.slice(7).trim() === expected) return true;
return url.searchParams.get('token') === expected;
}
async function storeInboxMessage(env, message) {
if (!env.FORWARDED_KV) throw new Error('Missing KV binding: FORWARDED_KV');
const text = message.text || '';
if (!text) return;
const fields = parseSmsFields(text);
const timestamp = Number(message.receivedAt);
const receivedAt = Number.isFinite(timestamp) ? timestamp : Date.now();
const sourceId = message.sourceId || message.shortCode || message.url || await sha256Hex(`${message.title || ''}\n${text}`);
await env.FORWARDED_KV.put(await inboxKey(sourceId, receivedAt, env), JSON.stringify({
id: sourceId,
sender: fields.sender || '',
text,
receivedAt,
title: message.title || '',
}), { expirationTtl: INBOX_TTL_SECONDS });
}
async function processMessages(request, env, url) {
requireEnv(env, 'STATE_SECRET');
if (!env.FORWARDED_KV) throw new Error('Missing KV binding: FORWARDED_KV');
if (!authorizeInboxRequest(request, env, url)) {
return jsonResponse({ code: 401, msg: 'unauthorized' }, 401);
}
const since = Number(url.searchParams.get('since') || 0);
const sender = url.searchParams.get('sender') || '';
const limit = Math.max(1, Math.min(Number(url.searchParams.get('limit') || 30), 100));
const list = await env.FORWARDED_KV.list({ prefix: 'inbox:' });
const messages = [];
for (const key of list.keys) {
const raw = await env.FORWARDED_KV.get(key.name);
if (!raw) continue;
const msg = JSON.parse(raw);
if (since && Number(msg.receivedAt || 0) < since) continue;
if (sender && !String(msg.sender || msg.text || '').includes(sender)) continue;
messages.push(msg);
}
messages.sort((a, b) => Number(b.receivedAt || 0) - Number(a.receivedAt || 0));
return jsonResponse({ messages: messages.slice(0, limit) });
}
async function forwardPushPlusMessage(env, message) {
requireEnv(env, 'STATE_SECRET');
if (!env.FORWARDED_KV) throw new Error('Missing KV binding: FORWARDED_KV');
const sourceId = message.sourceId || message.shortCode || message.url || await sha256Hex(`${message.title || ''}\n${message.text || ''}`);
if (!sourceId) return false;
const key = await dedupeKey(sourceId, env);
if (await env.FORWARDED_KV.get(key)) return false;
let text = message.text || '';
if (!text && message.shortCode) {
text = await fetchPushPlusDetail(env, message.shortCode);
}
if (!text) return false;
const interceptRule = findInterceptRule({ ...message, text }, env);
if (interceptRule) {
if (interceptShouldStore(interceptRule)) {
await storeInboxMessage(env, { ...message, text });
}
if (interceptShouldSilence(interceptRule)) {
await env.FORWARDED_KV.put(key, `intercept:${interceptRule.name || 'silence'}`, { expirationTtl: FORWARDED_TTL_SECONDS });
return false;
}
}
if (env.MESSAGE_TITLE_KEYWORD && !String(message.title || '').includes(env.MESSAGE_TITLE_KEYWORD)) {
await env.FORWARDED_KV.put(key, 'ignored', { expirationTtl: 60 * 60 * 24 * 30 });
return false;
}
if (env.MESSAGE_BODY_KEYWORD && !text.includes(env.MESSAGE_BODY_KEYWORD)) {
await env.FORWARDED_KV.put(key, 'ignored', { expirationTtl: 60 * 60 * 24 * 30 });
return false;
}
requireEnv(env, 'TELEGRAM_BOT_TOKEN');
requireEnv(env, 'TELEGRAM_CHAT_ID');
const telegramMessage = { title: message.title || '短信转发', text };
for (const chunk of splitTelegramText(buildTelegramText(telegramMessage))) {
await sendTelegram({ env, text: chunk });
}
await env.FORWARDED_KV.put(key, new Date().toISOString(), { expirationTtl: FORWARDED_TTL_SECONDS });
return true;
}
function callbackToken(request, url) {
const auth = request.headers.get('authorization') || '';
if (auth.toLowerCase().startsWith('bearer ')) return auth.slice(7).trim();
for (const pathPrefix of ['/pushplus/callback/', '/pushplus/webhook/']) {
if (url.pathname.startsWith(pathPrefix)) {
return decodeURIComponent(url.pathname.slice(pathPrefix.length));
}
}
return url.searchParams.get('token') || '';
}
function shortCodeFromUrl(url) {
const match = String(url || '').match(/\/shortMessage\/([^/?#]+)/);
return match ? decodeURIComponent(match[1]) : '';
}
async function parseWebhookPayload(request) {
const contentType = request.headers.get('content-type') || '';
const raw = await request.text();
if (contentType.includes('application/json')) {
return JSON.parse(raw || '{}');
}
if (contentType.includes('application/x-www-form-urlencoded')) {
return Object.fromEntries(new URLSearchParams(raw));
}
return { content: raw };
}
async function processCallback(request, env, url) {
requireEnv(env, 'CALLBACK_TOKEN');
requireEnv(env, 'STATE_SECRET');
if (!env.FORWARDED_KV) throw new Error('Missing KV binding: FORWARDED_KV');
const payload = await request.json().catch(() => ({}));
const messageInfo = payload.messageInfo || {};
const shortCode = messageInfo.shortCode || payload.shortCode || '';
const sendStatus = Number(messageInfo.sendStatus ?? payload.sendStatus ?? 2);
if (!shortCode) return;
if (sendStatus !== 2) return;
if (callbackToken(request, url) !== env.CALLBACK_TOKEN) {
console.warn('PushPlus callback token mismatch; skipped');
return;
}
await forwardPushPlusMessage(env, { shortCode, title: payload.title || '短信转发' });
}
async function processWebhook(request, env, url) {
requireEnv(env, 'CALLBACK_TOKEN');
if (callbackToken(request, url) !== env.CALLBACK_TOKEN) {
return jsonResponse({ code: 401, msg: 'unauthorized' }, 401);
}
if (request.method !== 'POST') return pushPlusSuccessResponse();
const payload = await parseWebhookPayload(request);
const content = payload.content || payload.text || payload.message || '';
const title = payload.title || payload.messageTitle || pickField(content, ['标题', 'title']) || '短信转发';
const urlValue = payload.url || payload.messageUrl || pickField(content, ['链接', 'url']) || '';
const text = htmlToText(content);
await forwardPushPlusMessage(env, {
sourceId: payload.shortCode || shortCodeFromUrl(urlValue) || urlValue,
shortCode: payload.shortCode || shortCodeFromUrl(urlValue),
title,
text,
url: urlValue,
});
return pushPlusSuccessResponse();
}
function handleCallback(request, env, ctx) {
const url = new URL(request.url);
console.log(JSON.stringify({
event: 'pushplus_callback_request',
method: request.method,
pathKind: url.pathname.startsWith('/pushplus/callback/') ? 'path-token' : 'base',
hasQueryToken: url.searchParams.has('token'),
contentType: request.headers.get('content-type') || '',
userAgent: request.headers.get('user-agent') || '',
}));
if (request.method === 'POST') {
ctx.waitUntil(processCallback(request.clone(), env, url).catch(err => {
console.error(`PushPlus callback processing failed: ${err.message}`);
}));
}
return pushPlusSuccessResponse();
}
export default {
async scheduled(_event, env, ctx) {
ctx.waitUntil(cleanupPushPlusMessages(env)
.then(result => {
console.log(JSON.stringify({ event: 'pushplus_cleanup', ...result }));
})
.catch(err => {
console.error(`PushPlus cleanup failed: ${err.message}`);
}));
},
async fetch(request, env, ctx) {
const url = new URL(request.url);
if (request.method === 'GET' && url.pathname === '/health') {
return jsonResponse({ code: 200, msg: 'ok' });
}
if (url.pathname === '/') {
return pushPlusSuccessResponse();
}
if (url.pathname === '/pushplus/callback' || url.pathname.startsWith('/pushplus/callback/')) {
try {
return handleCallback(request, env, ctx);
} catch (err) {
console.error(err.message);
return jsonResponse({ code: 500, msg: 'internal error' }, 500);
}
}
if (url.pathname === '/pushplus/webhook' || url.pathname.startsWith('/pushplus/webhook/')) {
try {
return await processWebhook(request, env, url);
} catch (err) {
console.error(err.message);
return jsonResponse({ code: 500, msg: 'internal error' }, 500);
}
}
if (url.pathname === '/messages' || url.pathname === '/pushplus/messages') {
try {
return await processMessages(request, env, url);
} catch (err) {
console.error(err.message);
return jsonResponse({ code: 500, msg: 'internal error' }, 500);
}
}
return jsonResponse({ code: 404, msg: 'not found' }, 404);
},
};