@pacoyang/wechaty-puppet-wechat 0.28.7 → 0.28.8
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/dist/src/bridge.d.ts +41 -1
- package/dist/src/bridge.d.ts.map +1 -1
- package/dist/src/bridge.js +135 -0
- package/dist/src/bridge.js.map +1 -1
- package/dist/src/config.d.ts +0 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/config.js +5 -5
- package/dist/src/config.js.map +1 -1
- package/dist/src/puppet-wechat.d.ts +32 -3
- package/dist/src/puppet-wechat.d.ts.map +1 -1
- package/dist/src/puppet-wechat.js +187 -7
- package/dist/src/puppet-wechat.js.map +1 -1
- package/dist/src/pure-function-helpers/is-type.js +2 -3
- package/dist/src/pure-function-helpers/is-type.js.map +1 -1
- package/dist/src/pure-function-helpers/message-extname.js +1 -2
- package/dist/src/pure-function-helpers/message-extname.js.map +1 -1
- package/dist/src/pure-function-helpers/message-filename.js +1 -2
- package/dist/src/pure-function-helpers/message-filename.js.map +1 -1
- package/dist/src/pure-function-helpers/message-raw-payload-parser.js +1 -2
- package/dist/src/pure-function-helpers/message-raw-payload-parser.js.map +1 -1
- package/dist/src/pure-function-helpers/normalize-scan-status.js +1 -2
- package/dist/src/pure-function-helpers/normalize-scan-status.js.map +1 -1
- package/dist/src/pure-function-helpers/web-message-type.js +1 -2
- package/dist/src/pure-function-helpers/web-message-type.js.map +1 -1
- package/dist/src/pure-function-helpers/xml.js +6 -7
- package/dist/src/pure-function-helpers/xml.js.map +1 -1
- package/dist/src/session-monitor.d.ts +16 -0
- package/dist/src/session-monitor.d.ts.map +1 -1
- package/dist/src/session-monitor.js +55 -4
- package/dist/src/session-monitor.js.map +1 -1
- package/dist/src/session-monitor.spec.d.ts +3 -0
- package/dist/src/session-monitor.spec.d.ts.map +1 -0
- package/dist/src/session-monitor.spec.js +65 -0
- package/dist/src/session-monitor.spec.js.map +1 -0
- package/package.json +1 -1
- package/src/bridge.ts +154 -0
- package/src/puppet-wechat.ts +212 -17
- package/src/session-monitor.spec.ts +80 -0
- package/src/session-monitor.ts +55 -1
package/src/puppet-wechat.ts
CHANGED
|
@@ -91,10 +91,14 @@ import {
|
|
|
91
91
|
Bridge,
|
|
92
92
|
BrowserHealth,
|
|
93
93
|
Cookie,
|
|
94
|
+
LoginPageState,
|
|
94
95
|
} from './bridge'
|
|
95
96
|
import {
|
|
96
97
|
ApiAnswer,
|
|
98
|
+
REFUSED_AFTER,
|
|
97
99
|
SessionHealth,
|
|
100
|
+
isRefusalCandidate,
|
|
101
|
+
refusedSession,
|
|
98
102
|
} from './session-monitor'
|
|
99
103
|
import {
|
|
100
104
|
Event,
|
|
@@ -115,18 +119,29 @@ import {
|
|
|
115
119
|
export type ScanFoodType = 'scan' | 'login' | 'logout'
|
|
116
120
|
|
|
117
121
|
export interface PuppetWeChatHealth {
|
|
118
|
-
logonoff
|
|
119
|
-
pageAlive
|
|
122
|
+
logonoff : boolean,
|
|
123
|
+
pageAlive : boolean,
|
|
120
124
|
// what the page itself says (read from it, null while it loads)
|
|
121
|
-
page
|
|
125
|
+
page : null | BrowserHealth,
|
|
126
|
+
// what the login page is showing while logged out (null when logged in or loading)
|
|
127
|
+
loginPage : null | LoginPageState,
|
|
122
128
|
// what the session's own requests say (watched from outside the page)
|
|
123
|
-
session
|
|
124
|
-
error?
|
|
125
|
-
cookieNames
|
|
126
|
-
hasDataTicket
|
|
129
|
+
session : SessionHealth,
|
|
130
|
+
error? : string,
|
|
131
|
+
cookieNames : string[],
|
|
132
|
+
hasDataTicket : boolean,
|
|
133
|
+
// whether wxuin and webwx_auth_ticket are present to request phone confirmation
|
|
134
|
+
hasPhoneTicket : boolean,
|
|
127
135
|
lastSyncCheckFailure? : { retcode: string, selector: string, time: number },
|
|
128
136
|
}
|
|
129
137
|
|
|
138
|
+
export interface PhoneConfirmResult {
|
|
139
|
+
mode : 'phone' | 'qrcode',
|
|
140
|
+
canConfirmOnPhone : boolean,
|
|
141
|
+
waitingForPhone : boolean,
|
|
142
|
+
qrcodeUrl : null | string,
|
|
143
|
+
}
|
|
144
|
+
|
|
130
145
|
const HEALTH_CHECK_INTERVAL = 60 * 1000
|
|
131
146
|
// synccheck is a long poll answered within ~25s, so minutes of silence
|
|
132
147
|
// mean the web app stopped syncing.
|
|
@@ -156,6 +171,13 @@ const HEALTH_LOG_INTERVAL = 60 * 60 * 1000
|
|
|
156
171
|
// out and reload to the QR code instead, once such answers have been seen
|
|
157
172
|
// to mean what they say.
|
|
158
173
|
const END_SESSION_ON_RET = process.env.WECHATY_PUPPET_WECHAT_END_SESSION_ON_RET === '1'
|
|
174
|
+
// A session the server refuses (see refusedSession) is left for a new login
|
|
175
|
+
// unless this is 0: then it is only reported, as before.
|
|
176
|
+
const END_REFUSED_SESSION = process.env.WECHATY_PUPPET_WECHAT_END_REFUSED_SESSION !== '0'
|
|
177
|
+
// Keep the login page quiet while waiting for a person to trigger login from
|
|
178
|
+
// the console, instead of reloading every 2 minutes in the background. Set to
|
|
179
|
+
// 1 to restore the legacy scan watchdog reload loop.
|
|
180
|
+
const SCAN_WATCHDOG_ENABLED = process.env.WECHATY_PUPPET_WECHAT_SCAN_WATCHDOG === '1'
|
|
159
181
|
|
|
160
182
|
export class PuppetWeChat extends Puppet {
|
|
161
183
|
|
|
@@ -197,7 +219,11 @@ export class PuppetWeChat extends Puppet {
|
|
|
197
219
|
const SCAN_TIMEOUT = 2 * 60 * 1000 // 2 minutes
|
|
198
220
|
this.scanWatchdog = new Watchdog<ScanFoodType>(SCAN_TIMEOUT, 'Scan')
|
|
199
221
|
|
|
200
|
-
|
|
222
|
+
if (SCAN_WATCHDOG_ENABLED) {
|
|
223
|
+
this.initWatchdogForScan()
|
|
224
|
+
} else {
|
|
225
|
+
this.scanWatchdog.sleep()
|
|
226
|
+
}
|
|
201
227
|
}
|
|
202
228
|
|
|
203
229
|
public async start (): Promise<void> {
|
|
@@ -255,7 +281,9 @@ export class PuppetWeChat extends Puppet {
|
|
|
255
281
|
})
|
|
256
282
|
})
|
|
257
283
|
|
|
258
|
-
|
|
284
|
+
if (SCAN_WATCHDOG_ENABLED) {
|
|
285
|
+
this.initScanWatchdogReset()
|
|
286
|
+
}
|
|
259
287
|
this.startHealthCheck()
|
|
260
288
|
|
|
261
289
|
log.verbose('PuppetWeChat', 'start() done')
|
|
@@ -410,7 +438,9 @@ export class PuppetWeChat extends Puppet {
|
|
|
410
438
|
const report: PuppetWeChatHealth = {
|
|
411
439
|
cookieNames : [],
|
|
412
440
|
hasDataTicket : false,
|
|
441
|
+
hasPhoneTicket : false,
|
|
413
442
|
lastSyncCheckFailure : this.lastSyncCheckFailure,
|
|
443
|
+
loginPage : null,
|
|
414
444
|
logonoff : this.logonoff(),
|
|
415
445
|
page : null,
|
|
416
446
|
pageAlive : false,
|
|
@@ -424,12 +454,21 @@ export class PuppetWeChat extends Puppet {
|
|
|
424
454
|
return report
|
|
425
455
|
}
|
|
426
456
|
try {
|
|
427
|
-
const cookieList
|
|
428
|
-
report.cookieNames
|
|
429
|
-
report.hasDataTicket
|
|
457
|
+
const cookieList = await this.bridge.cookies()
|
|
458
|
+
report.cookieNames = cookieList.map(c => c.name)
|
|
459
|
+
report.hasDataTicket = cookieList.some(c => c.name === 'webwx_data_ticket' && !!c.value)
|
|
460
|
+
report.hasPhoneTicket = cookieList.some(c => c.name === 'wxuin' && !!c.value)
|
|
461
|
+
&& cookieList.some(c => c.name === 'webwx_auth_ticket' && !!c.value)
|
|
430
462
|
} catch (e) {
|
|
431
463
|
report.error = (e && e.message) || String(e)
|
|
432
464
|
}
|
|
465
|
+
if (!report.logonoff) {
|
|
466
|
+
try {
|
|
467
|
+
report.loginPage = await this.bridge.loginPageState()
|
|
468
|
+
} catch (e) {
|
|
469
|
+
// page may be navigating
|
|
470
|
+
}
|
|
471
|
+
}
|
|
433
472
|
return report
|
|
434
473
|
}
|
|
435
474
|
|
|
@@ -497,6 +536,17 @@ export class PuppetWeChat extends Puppet {
|
|
|
497
536
|
this.healthClear('session')
|
|
498
537
|
}
|
|
499
538
|
|
|
539
|
+
const refused = refusedSession(session)
|
|
540
|
+
if (refused) {
|
|
541
|
+
if (END_REFUSED_SESSION) {
|
|
542
|
+
await this.sessionEnded(`the server refuses the session: ${refused}`)
|
|
543
|
+
return
|
|
544
|
+
}
|
|
545
|
+
this.healthAlert('refused', `the server refuses the session: ${refused}. Messages are neither sent nor received.`)
|
|
546
|
+
} else {
|
|
547
|
+
this.healthClear('refused')
|
|
548
|
+
}
|
|
549
|
+
|
|
500
550
|
// before the first answer, count from the login
|
|
501
551
|
const lastSyncCheck = sync ? sync.time : session.since
|
|
502
552
|
if (now - lastSyncCheck > SYNC_STALL_TIMEOUT) {
|
|
@@ -509,7 +559,20 @@ export class PuppetWeChat extends Puppet {
|
|
|
509
559
|
|
|
510
560
|
for (const [kind, answer] of [['webwxsync', session.lastSync], ['send', session.lastSend]] as const) {
|
|
511
561
|
if (answer && answer.failures >= API_FAILURES_ALERT) {
|
|
512
|
-
|
|
562
|
+
// When automatic ending of refused sessions is on, stay quiet during
|
|
563
|
+
// the 3-minute refusal grace window instead of sending a noisy API
|
|
564
|
+
// alert right before sessionEnded(). If failures stay below the
|
|
565
|
+
// refusal count past REFUSED_AFTER, alert normally.
|
|
566
|
+
const inRefusalGrace = END_REFUSED_SESSION
|
|
567
|
+
&& isRefusalCandidate(answer)
|
|
568
|
+
&& answer.failingSince !== null
|
|
569
|
+
&& (now - answer.failingSince) < REFUSED_AFTER
|
|
570
|
+
if (inRefusalGrace) {
|
|
571
|
+
log.warn('PuppetWeChat', 'health: %s failing with Ret %s (%s in a row), waiting for refusal threshold',
|
|
572
|
+
answer.api, answer.ret, answer.failures)
|
|
573
|
+
} else {
|
|
574
|
+
this.healthAlert(kind, `${answer.api} keeps failing: ${answer.ret}, ${answer.failures} times in a row`)
|
|
575
|
+
}
|
|
513
576
|
} else {
|
|
514
577
|
this.healthClear(kind)
|
|
515
578
|
}
|
|
@@ -556,8 +619,10 @@ export class PuppetWeChat extends Puppet {
|
|
|
556
619
|
/**
|
|
557
620
|
* The server ended the session: mark the bot logged out with the reason.
|
|
558
621
|
* The web app goes to its login page by itself after a synccheck retcode.
|
|
559
|
-
* It stays where it is after a failing webwxsync or send
|
|
560
|
-
*
|
|
622
|
+
* It stays where it is after a failing webwxsync or send: then the
|
|
623
|
+
* session's cookies are dropped, which brings the login page (a plain
|
|
624
|
+
* reload would bring back the same session), where the page waits quietly
|
|
625
|
+
* until a person triggers login confirmation or a QR code from the console.
|
|
561
626
|
*/
|
|
562
627
|
private async sessionEnded (reason: string, reload = true): Promise<void> {
|
|
563
628
|
if (!this.id) {
|
|
@@ -568,9 +633,139 @@ export class PuppetWeChat extends Puppet {
|
|
|
568
633
|
if (!reload) {
|
|
569
634
|
return
|
|
570
635
|
}
|
|
571
|
-
|
|
572
|
-
|
|
636
|
+
try {
|
|
637
|
+
await this.bridge.dropSession()
|
|
638
|
+
await this.saveCookie().catch(e => {
|
|
639
|
+
log.error('PuppetWeChat', 'sessionEnded() saveCookie() rejection: %s', e && e.message)
|
|
640
|
+
})
|
|
641
|
+
} catch (e) {
|
|
642
|
+
log.error('PuppetWeChat', 'sessionEnded() dropSession() rejection: %s', e && e.message)
|
|
643
|
+
try {
|
|
644
|
+
await this.bridge.reload()
|
|
645
|
+
} catch (e) {
|
|
646
|
+
log.error('PuppetWeChat', 'sessionEnded() reload rejection: %s', e && e.message)
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
private async waitForLoginPage (
|
|
652
|
+
predicate: (state: LoginPageState) => boolean = () => true,
|
|
653
|
+
timeoutMs = 8000,
|
|
654
|
+
): Promise<null | LoginPageState> {
|
|
655
|
+
const deadline = Date.now() + timeoutMs
|
|
656
|
+
let last: null | LoginPageState = null
|
|
657
|
+
while (Date.now() < deadline) {
|
|
658
|
+
if (this.logonoff()) {
|
|
659
|
+
return null
|
|
660
|
+
}
|
|
661
|
+
try {
|
|
662
|
+
last = await this.bridge.loginPageState()
|
|
663
|
+
if (last && predicate(last)) {
|
|
664
|
+
return last
|
|
665
|
+
}
|
|
666
|
+
} catch (e) {
|
|
667
|
+
// page may still be navigating
|
|
668
|
+
}
|
|
669
|
+
await new Promise(resolve => setTimeout(resolve, 400))
|
|
670
|
+
}
|
|
671
|
+
return last
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Drop the current web session (even if the page still thinks it is logged
|
|
676
|
+
* in) and land on the login page without automatically nagging the phone.
|
|
677
|
+
*/
|
|
678
|
+
public async forceRelogin (preferQrcode = false): Promise<null | LoginPageState> {
|
|
679
|
+
if (this.id) {
|
|
680
|
+
this.logoutLocally('manual relogin')
|
|
681
|
+
}
|
|
682
|
+
await this.bridge.dropSession(preferQrcode)
|
|
683
|
+
await this.saveCookie().catch(e => {
|
|
684
|
+
log.error('PuppetWeChat', 'forceRelogin() saveCookie() rejection: %s', e && e.message)
|
|
573
685
|
})
|
|
686
|
+
return this.waitForLoginPage()
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* Trigger a one-tap phone login confirmation on demand. If the server
|
|
691
|
+
* refuses or no phone auth ticket is present, falls back to a fresh QR code
|
|
692
|
+
* and reports which mode is now active on the login page.
|
|
693
|
+
*/
|
|
694
|
+
public async requestPhoneConfirm (): Promise<PhoneConfirmResult> {
|
|
695
|
+
if (this.id) {
|
|
696
|
+
await this.forceRelogin(false)
|
|
697
|
+
}
|
|
698
|
+
let state = await this.waitForLoginPage(() => true, 4000)
|
|
699
|
+
if (!state) {
|
|
700
|
+
state = await this.forceRelogin(false)
|
|
701
|
+
}
|
|
702
|
+
if (!state) {
|
|
703
|
+
throw new Error('Login page is not ready yet')
|
|
704
|
+
}
|
|
705
|
+
if (!state.canConfirmOnPhone) {
|
|
706
|
+
const offered = await this.bridge.offerConfirmOnPhone()
|
|
707
|
+
if (!offered) {
|
|
708
|
+
const qr = await this.requestLoginQrcode()
|
|
709
|
+
return {
|
|
710
|
+
canConfirmOnPhone : false,
|
|
711
|
+
mode : 'qrcode',
|
|
712
|
+
qrcodeUrl : qr.qrcodeUrl,
|
|
713
|
+
waitingForPhone : false,
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
await this.bridge.reload()
|
|
717
|
+
state = await this.waitForLoginPage(s => s.canConfirmOnPhone || s.hasQrcode)
|
|
718
|
+
}
|
|
719
|
+
if (!state || !state.canConfirmOnPhone) {
|
|
720
|
+
const qr = await this.requestLoginQrcode()
|
|
721
|
+
return {
|
|
722
|
+
canConfirmOnPhone : false,
|
|
723
|
+
mode : 'qrcode',
|
|
724
|
+
qrcodeUrl : qr.qrcodeUrl,
|
|
725
|
+
waitingForPhone : false,
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
await this.bridge.pushLoginConfirm()
|
|
729
|
+
// Give webwxpushloginurl a moment to either start waiting on the phone or
|
|
730
|
+
// fall back to showing a QR code if the server refused the auth ticket.
|
|
731
|
+
await new Promise(resolve => setTimeout(resolve, 1500))
|
|
732
|
+
if (this.logonoff()) {
|
|
733
|
+
return {
|
|
734
|
+
canConfirmOnPhone : true,
|
|
735
|
+
mode : 'phone',
|
|
736
|
+
qrcodeUrl : null,
|
|
737
|
+
waitingForPhone : false,
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
const after = await this.waitForLoginPage(s => s.waitingForPhone || s.hasQrcode, 4000) || state
|
|
741
|
+
if (this.logonoff() || after.waitingForPhone) {
|
|
742
|
+
return {
|
|
743
|
+
canConfirmOnPhone : true,
|
|
744
|
+
mode : 'phone',
|
|
745
|
+
qrcodeUrl : null,
|
|
746
|
+
waitingForPhone : !this.logonoff(),
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
return {
|
|
750
|
+
canConfirmOnPhone : !!after.canConfirmOnPhone,
|
|
751
|
+
mode : 'qrcode',
|
|
752
|
+
qrcodeUrl : after.qrcodeUrl,
|
|
753
|
+
waitingForPhone : false,
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Show a fresh QR code on the login page on demand (dropping the current
|
|
759
|
+
* session first if still logged in).
|
|
760
|
+
*/
|
|
761
|
+
public async requestLoginQrcode (): Promise<{ qrcodeUrl: null | string }> {
|
|
762
|
+
if (this.id) {
|
|
763
|
+
await this.forceRelogin(true)
|
|
764
|
+
} else {
|
|
765
|
+
await this.bridge.showLoginQrcode()
|
|
766
|
+
}
|
|
767
|
+
const state = await this.waitForLoginPage(s => s.hasQrcode && !!s.qrcodeUrl)
|
|
768
|
+
return { qrcodeUrl: state ? state.qrcodeUrl : null }
|
|
574
769
|
}
|
|
575
770
|
|
|
576
771
|
/**
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
#!/usr/bin/env ts-node
|
|
2
|
+
|
|
3
|
+
import test from 'blue-tape'
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
ApiAnswer,
|
|
7
|
+
REFUSED_AFTER,
|
|
8
|
+
REFUSED_SEND_FAILURES,
|
|
9
|
+
REFUSED_SYNC_FAILURES,
|
|
10
|
+
SessionHealth,
|
|
11
|
+
SessionMonitor,
|
|
12
|
+
isRefusalCandidate,
|
|
13
|
+
refusedSession,
|
|
14
|
+
} from './session-monitor'
|
|
15
|
+
|
|
16
|
+
function health (lastSync: null | ApiAnswer, lastSend: null | ApiAnswer = null, now = Date.now()): SessionHealth {
|
|
17
|
+
return {
|
|
18
|
+
lastReceived : null,
|
|
19
|
+
lastSend,
|
|
20
|
+
lastSync,
|
|
21
|
+
now,
|
|
22
|
+
sentWithoutSync : null,
|
|
23
|
+
since : now - 3600 * 1000,
|
|
24
|
+
syncCheck : null,
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function answer (api: string, ret: string, failures: number, failingFor: number, now = Date.now()): ApiAnswer {
|
|
29
|
+
return { api, failingSince: failures ? now - failingFor : null, failures, ret, time: now }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
test('SessionMonitor remembers when a failing streak started', async t => {
|
|
33
|
+
const monitor = new SessionMonitor()
|
|
34
|
+
const first = monitor.onApiAnswer('webwxsync', '3', Date.now())
|
|
35
|
+
t.equal(first.failures, 1, 'first failure counted')
|
|
36
|
+
t.ok(first.failingSince, 'streak start set')
|
|
37
|
+
|
|
38
|
+
const second = monitor.onApiAnswer('webwxsync', '3', Date.now())
|
|
39
|
+
t.equal(second.failures, 2, 'second failure counted')
|
|
40
|
+
t.equal(second.failingSince, first.failingSince, 'streak start kept')
|
|
41
|
+
|
|
42
|
+
const ok = monitor.onApiAnswer('webwxsync', '0', Date.now())
|
|
43
|
+
t.equal(ok.failingSince, null, 'a success ends the streak')
|
|
44
|
+
const again = monitor.onApiAnswer('webwxsync', '3', Date.now())
|
|
45
|
+
t.ok(again.failingSince && again.failingSince >= ok.time, 'a new streak starts after the success')
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
test('refusedSession() on the 2026-12-06 pattern: webwxsync Ret 3 for minutes', async t => {
|
|
49
|
+
const reason = refusedSession(health(answer('webwxsync', '3', 40000, 4 * 3600 * 1000)))
|
|
50
|
+
t.ok(reason, 'refused')
|
|
51
|
+
t.ok(reason && /webwxsync answered Ret 3/.test(reason), 'reason names the call and Ret: ' + reason)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
test('refusedSession() waits for both enough failures and enough time', async t => {
|
|
55
|
+
t.notOk(refusedSession(health(answer('webwxsync', '3', REFUSED_SYNC_FAILURES - 1, REFUSED_AFTER * 2))), 'too few failures')
|
|
56
|
+
t.notOk(refusedSession(health(answer('webwxsync', '3', 500, REFUSED_AFTER - 1000))), 'not long enough')
|
|
57
|
+
t.ok(refusedSession(health(answer('webwxsync', '3', REFUSED_SYNC_FAILURES, REFUSED_AFTER))), 'both reached')
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
test('refusedSession() ignores what does not come from the server, and rate limiting', async t => {
|
|
61
|
+
t.notOk(refusedSession(health(answer('webwxsync', 'request failed: net::ERR_ABORTED', 500, REFUSED_AFTER * 2))), 'network failure')
|
|
62
|
+
t.notOk(refusedSession(health(answer('webwxsync', '1205', 500, REFUSED_AFTER * 2))), '1205 is rate limiting')
|
|
63
|
+
t.notOk(refusedSession(health(answer('webwxsync', '0', 0, 0))), 'working session')
|
|
64
|
+
t.notOk(refusedSession(health(null)), 'nothing seen yet')
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test('refusedSession() on sends alone', async t => {
|
|
68
|
+
const sync = answer('webwxsync', '0', 0, 0)
|
|
69
|
+
t.notOk(refusedSession(health(sync, answer('webwxsendmsg', '3', REFUSED_SEND_FAILURES - 1, REFUSED_AFTER * 2))), 'too few sends')
|
|
70
|
+
t.ok(refusedSession(health(sync, answer('webwxsendmsg', '3', REFUSED_SEND_FAILURES, REFUSED_AFTER))), 'sends refused for long enough')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
test('isRefusalCandidate() distinguishes server refusals from rate limiting and network errors', async t => {
|
|
74
|
+
t.ok(isRefusalCandidate(answer('webwxsync', '3', 3, 60 * 1000)), 'Ret 3 is a refusal candidate')
|
|
75
|
+
t.ok(isRefusalCandidate(answer('webwxsendappmsg', '-1', 3, 60 * 1000)), 'Ret -1 is a refusal candidate')
|
|
76
|
+
t.notOk(isRefusalCandidate(answer('webwxsendmsg', '1205', 3, 60 * 1000)), '1205 is rate limiting')
|
|
77
|
+
t.notOk(isRefusalCandidate(answer('webwxsync', 'request failed: net::ERR_ABORTED', 3, 60 * 1000)), 'network error is not a refusal')
|
|
78
|
+
t.notOk(isRefusalCandidate(answer('webwxsync', '0', 0, 0)), 'success is not a refusal')
|
|
79
|
+
t.notOk(isRefusalCandidate(null), 'null is not a refusal')
|
|
80
|
+
})
|
package/src/session-monitor.ts
CHANGED
|
@@ -20,6 +20,8 @@ export interface ApiAnswer {
|
|
|
20
20
|
api : string,
|
|
21
21
|
// failed answers in a row for this kind of call (webwxsync, or any send)
|
|
22
22
|
failures : number,
|
|
23
|
+
// when the first of those failed answers came, null after a success
|
|
24
|
+
failingSince : null | number,
|
|
23
25
|
// BaseResponse.Ret, or what went wrong with the request itself
|
|
24
26
|
ret : string,
|
|
25
27
|
time : number,
|
|
@@ -64,6 +66,54 @@ export function parseSyncCheck (body: string): undefined | { retcode: string, se
|
|
|
64
66
|
return match ? { retcode: match[1], selector: match[2] } : undefined
|
|
65
67
|
}
|
|
66
68
|
|
|
69
|
+
// A session the server stopped serving keeps answering synccheck as usual,
|
|
70
|
+
// while webwxsync and every send answer an error (seen: BaseResponse.Ret 3,
|
|
71
|
+
// with the session's Sid still recognised: a wrong Sid answers 1101). The
|
|
72
|
+
// web app retries webwxsync a few times a second and never leaves, and a
|
|
73
|
+
// reload brings back the same refused session. Errors that last this long,
|
|
74
|
+
// with nothing succeeding in between, mean the session is gone.
|
|
75
|
+
export const REFUSED_AFTER = 3 * 60 * 1000
|
|
76
|
+
export const REFUSED_SYNC_FAILURES = 10
|
|
77
|
+
export const REFUSED_SEND_FAILURES = 5
|
|
78
|
+
// 1205 is the server asking us to send less; the web app logs out on it by
|
|
79
|
+
// itself.
|
|
80
|
+
const NOT_REFUSAL = ['1205']
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Whether an API failure looks like the server refusing the session (numeric
|
|
84
|
+
* BaseResponse.Ret other than 1205 rate limiting), rather than a transient
|
|
85
|
+
* network error.
|
|
86
|
+
*/
|
|
87
|
+
export function isRefusalCandidate (answer: null | ApiAnswer): boolean {
|
|
88
|
+
if (!answer || !answer.failingSince || answer.failures <= 0) {
|
|
89
|
+
return false
|
|
90
|
+
}
|
|
91
|
+
return /^-?\d+$/.test(answer.ret) && !NOT_REFUSAL.includes(answer.ret)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Why the session counts as refused by the server, or undefined while it
|
|
96
|
+
* does not. Only answers from the server count: a request that failed on the
|
|
97
|
+
* way (`request failed: ...`) says nothing about the session.
|
|
98
|
+
*/
|
|
99
|
+
export function refusedSession (health: SessionHealth): undefined | string {
|
|
100
|
+
const checks: Array<[null | ApiAnswer, number]> = [
|
|
101
|
+
[health.lastSync, REFUSED_SYNC_FAILURES],
|
|
102
|
+
[health.lastSend, REFUSED_SEND_FAILURES],
|
|
103
|
+
]
|
|
104
|
+
for (const [answer, minFailures] of checks) {
|
|
105
|
+
if (!answer || !isRefusalCandidate(answer) || answer.failures < minFailures) {
|
|
106
|
+
continue
|
|
107
|
+
}
|
|
108
|
+
const failingSince = answer.failingSince as number
|
|
109
|
+
const minutes = (health.now - failingSince) / 60000
|
|
110
|
+
if (health.now - failingSince >= REFUSED_AFTER) {
|
|
111
|
+
return `${answer.api} answered Ret ${answer.ret} ${answer.failures} times in a row for ${Math.round(minutes)} minutes`
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return undefined
|
|
115
|
+
}
|
|
116
|
+
|
|
67
117
|
export class SessionMonitor {
|
|
68
118
|
|
|
69
119
|
private since = Date.now()
|
|
@@ -113,8 +163,12 @@ export class SessionMonitor {
|
|
|
113
163
|
): ApiAnswer {
|
|
114
164
|
const isSync = api === 'webwxsync'
|
|
115
165
|
const previous = isSync ? this.lastSync : this.lastSend
|
|
166
|
+
const now = Date.now()
|
|
116
167
|
const failures = ret === '0' ? 0 : ((previous && previous.failures) || 0) + 1
|
|
117
|
-
const
|
|
168
|
+
const failingSince = ret === '0'
|
|
169
|
+
? null
|
|
170
|
+
: (previous && previous.failures && previous.failingSince) || now
|
|
171
|
+
const answer = { api, failingSince, failures, ret, time: now }
|
|
118
172
|
|
|
119
173
|
if (isSync) {
|
|
120
174
|
this.lastSync = answer
|