/
main.js
1713 lines (1493 loc) · 45.1 KB
/
main.js
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//Queue-Fair Akamai Adapter v2.1.1 Copyright Matt King 2024 see LICENCE in this distribution for more details.
import { TextDecoder, TextEncoder, base64 } from 'encoding'
import { httpRequest } from 'http-request'
import { crypto } from 'crypto'
import { logger } from 'log'
const encoder = new TextEncoder()
const compiledSecrets = []
const waiting = []
const config = {
// PMUSER_QF_ACCOUNT_SECRET
// Your Account Secret is shown on the Your Account page of
// the Queue-Fair Portal.If you change it there, you must
// change it here too. MUST NOT be the secret of any queue.
accountSecret : 'ACCOUNT_SECRET_FROM_YOUR_ACCOUNT_PAGE_IN_PORTAL',
// PMUSER_QF_ACCOUNT_SYSTEM_NAME
// The System Name of your account from the Your Account page
// of the Queue-Fair Portal. MUST NOT be the system name of any queue.
account : 'ACCOUNT_SYSTEM_NAME_FROM_YOUR_ACCOUNT_PAGE_IN_PORTAL',
// PMUSER_QF_QUERY_VALIDITY_SECONDS
// Time limit for Passed Strings to be considered valid,
// before and after the current time
queryTimeLimitSeconds : 30,
// PMUSER_QF_DEBUG
// set to true to enable debug logging output.
debug : false,
// PMUSER_QF_TIMEOUT_SECONDSS
// How long to wait in seconds for network reads of config
// or Adapter Server (safe mode only)
readTimeout : 10,
// PMUSER_QF_SETTINGS_CACHE_MINUTES
// How long a cached copy of your Queue-Fair settings will be kept before
// downloading a fresh copy. Set this to 0 if you are updating your settings in
// the Queue-Fair Portal and want to test your changes quickly, but remember
// to set it back to at least 5 again when you are finished to reduce CloudFlare costs.
// NOTE: If you set this to one minute or less in a production environment, you will
// exceed the CloudFlare free plan KV limit of 1000 writes per day!
settingsCacheLifetimeMinutes : 5,
// PMUSER_QF_STRIP_PASSED
// Whether or not to strip the Passed String from the URL
// that the Visitor sees on return from the Queue or Adapter servers
// (simple mode) - when set to true causes one additinal HTTP request
// to CloudFlare but only on the first matching visit from a particular
// visitor. The recommended value is true.
stripPassedString : true,
// PMUSER_QF_MODE
// Whether to send the visitor to the Adapter server for counting (simple mode),
// or consult the Adapter server (safe mode).The recommended value is 'safe'.
// If you change this to 'simple', consider setting stripPassedString above to
// false to make it easier for Google to crawl your pages.
adapterMode : 'safe',
// PMUSER_QF_ALWAYS_HTTPS
// When the queue is turned on and showing queue pages, always send a visitor
// from the front of the queue to a URL on your site starting 'https://'
// even if Akamai has told us that they wanted a URL starting 'http://',
// which can happen with some Akamai set-ups involving multiple
// reverse proxies. Setting is only active if Dynamic Targeting is in use.
// Leave this set to true if your whole site is protected by https.
alwaysHTTPS : false,
// PMUSER_QF_SEND_URL
// When enabled the URL of any visitor request that results in an Adapter call to
// the Queue Server cluster is sent to the cluster for logging, which is occasionally
// useful for investigations. Only applies to SAFE mode.
// May be set to false for production systems once we have verified the IP address
// has been successfully received.
sendURL : true,
// PMUSER_QF_EXCLUDE_FILE_TYPES (comma separated list)
// An array of commonly used file extensions on which the Adapter will automatically
// NOT Match. Equivalent to AND Path Does Not Contain .xxx in the
// Portal Activation Rules. Preferably, set these as Does Not Match paths in your
// Adapter Rule Criteria in Control Centre. Set to null or an empty array to disable.
excludeFileTypes : [ 'json', 'xml', 'css', 'js', 'webmanifest', 'txt', //static file types
'jpeg', 'jpg', 'gif', 'png', 'webp', 'svg', 'bmp', 'ico', //Image types
'mpeg','mpg','mp4','wav','mp3','pdf', //media types
'woff','woff2','ttf','eot' //font types
],
// Append this port number to target URLs used with Dynamic Targeting.
// Set to -1 to disable in production systems. Set to 9550 if running Adapter in Sandbox.
targetPort : -1,
}
function setUpConfigVariable(req,key,prop,type = 'string',sep=',') {
logger.log('PMUSER_QF_'+key+" "+req.getVariable('PMUSER_QF_'+key));
if(typeof req.getVariable('PMUSER_QF_'+key) === 'undefined')
return
let i = req.getVariable('PMUSER_QF_'+key)
let o = 'unset'
switch(type) {
case 'list':
o = i.split(sep).trim()
break
case 'bool':
o = (i == 'true')
break
case 'int':
o = parseInt(i)
break
default:
case 'string':
o = i
break
}
config[prop] = o
}
function setUpConfig(req) {
setUpConfigVariable(req,'ACCOUNT_SYSTEM_NAME','account')
setUpConfigVariable(req,'ACCOUNT_SECRET','accountSecret')
setUpConfigVariable(req,'DEBUG','debug','bool')
setUpConfigVariable(req,'QUERY_VALIDITY_SECONDS','queryTimeLimitSeconds','int')
setUpConfigVariable(req,'TIMEOUT_SECONDS','readTimeout','int')
setUpConfigVariable(req,'SETTINGS_CACHE_MINUTES','settingsCacheLifetimeMinutes','int')
setUpConfigVariable(req,'STRIP_PASSED_STRING','stripPassedString','bool')
setUpConfigVariable(req,'ADAPTER_MODE','adapterMode')
setUpConfigVariable(req,'ALWAYS_HTTPS','alwaysHTTPS','bool')
setUpConfigVariable(req,'SEND_URL','sendURL','bool')
setUpConfigVariable(req,'EXCLUDE_FILE_TYPES','excludeFileTypes','list',',')
}
export async function onClientRequest (req) {
//Set up config.
setUpConfig(req)
let d = config.debug
let protocol = req.scheme
if(config.targetPort == 9550) {
//Always use http for sandbox.
protocol = 'http'
}
const service = new QueueFairService(req,logger)
service.isSecure = (protocol == 'https')
const adapter = new QueueFairAdapter(service)
adapter.url = protocol + '://' + req.host
if(config.targetPort != -1) {
adapter.url += ':'+config.targetPort
}
adapter.url += req.url
adapter.userAgent = req.getHeader('user-agent')[0]
if (!await adapter.go()) {
// Adapter says No - do not generate page.
if(service.redirectLoc == null) {
if(d) logger.log('QF WARNING: Queue-Fair returned stop but no redirect!');
return req
}
const resp = {
status: 302,
headers: {
location : service.redirectLoc,
'x-qf-test' : 'test2',
'set-cookie' : 'mycookie=myval'
},
body: '',
addHeader : (name,value) => {
resp.headers[name] = value
},
setHeader : (name,value) => {
resp.headers[name] = value
}
}
req.setVariable('PMUSER_QF_REDIRECT','true')
service.addCookiesTo(req,true,true)
service.setNoCache(resp,false)
if(d) logger.log(resp);
req.respondWith(resp.status, resp.headers,resp.body)
return
}
// Page should continue.
req.setVariable('PMUSER_QF_REDIRECT','false')
service.addCookiesTo(req,true)
service.setNoCache(req,true)
}
export async function onClientResponse (req, resp) {
let d = config.debug
logger.log('Responding')
if(d) {
logger.log('RESP',JSON.stringify(resp))
logger.log('RESPH',JSON.stringify(resp.headers))
}
if(req.getVariable('PMUSER_QF_REDIRECT') == 'true') {
//Queue-Fair generated response.
let varVal = req.getVariable('PMUSER_QF_REDVAR')
if(varVal) {
let bits = varVal.split('|||')
for(let i in bits) {
logger.log('+C',bits[i])
resp.addHeader('set-cookie',bits[i])
}
}
} else {
//Not Queue-Fair generated response. Headers will be available.
if(req.getHeader('x-qf-cookie')) {
//Adds cookies.
let headers = req.getHeader('x-qf-cookie')
logger.log(JSON.stringify(headers))
for(var c in headers) {
resp.addHeader('set-cookie',headers[c])
}
}
}
if(req.getHeader('x-qf-cache') || req.getVariable('PMUSER_QF_REDIRECT') == 'true') {
//Overrides cache-control if set by Queue-Fair.
resp.setHeader('cache-control','no-store,no-cache,max-age=0')
}
if(d) {
logger.log('QF2 RET '+JSON.stringify(resp))
}
return resp
}
class QueueFairService {
req
cookies = null
addedCookies = null
doneNoCache = false
redirectLoc = null
isSecure = false
logger = null
/**
* @param {Object} req a CloudFront request
*/
constructor(req, logger) {
this.req= req
this.logger = logger
}
log(what) {
this.logger.log(what)
}
parseCookies() {
this.cookies = []
let reqCookies = this.req.getHeader('cookie')
if(!reqCookies || reqCookies.length < 1) {
return
}
reqCookies = reqCookies[0]
reqCookies.split(';').forEach((c) => {
if (c) {
let i = c.indexOf('=')
try {
let key = c.substring(0,i).trim()
let value = c.substring(i+1).trim()
this.cookies[key] = value
} catch (error) {
//Do nothing.
}
}
})
}
/**
* @param {string} cname the name of the cookie.
* @return {string} the cookie value, or null if not found.
*/
getCookie(cname) {
if(this.cookies == null) {
this.parseCookies()
}
if(typeof this.cookies[cname] !== 'undefined') {
return this.cookies[cname]
}
return null
}
/**
* @param {string} cname the full name of the cookie.
* @param {string} value the value to store.
* @param {string} lifetimeSeconds how long the cookie persists
* @param {string} path the cookie path
* @param {string} cookieDomain optional cookie domain.
*/
setCookie(cname, value, lifetimeSeconds, path, cookieDomain) {
this.noCache()
if(this.addedCookies == null) {
this.addedCookies = []
}
var v = value+';Max-Age='+lifetimeSeconds
let date=new Date()
date.setTime(date.getTime()+lifetimeSeconds*1000)
v += ';Expires='+date.toUTCString()
if(cookieDomain != null && cookieDomain != '') {
v+=';Domain='+cookieDomain
}
v+=';Path='+path
this.addedCookies[cname] = v
}
/**
* Sets no-cache headers if needed.
*/
noCache() {
if (this.doneNoCache) {
return
}
this.doneNoCache=true
}
/**
* @param {string} loc where to send the visitor. 302 redirect.
*/
redirect(loc) {
this.noCache()
this.redirectLoc = loc
}
/**
* @return {string} the IP address of the visitor
*/
remoteAddr() {
return this.req.getVariable('PMUSER_QF_VISITOR_IP')
}
/**
* @param {Object} obj the JSON object to which to add the cookies.
* @param {boolean} save whether to save the values to be added later, or set them directly with set-cookie header.
*/
addCookiesTo(obj, save, isRedirect = false) {
if(this.addedCookies == null) {
logger.log('NoC')
return
}
let arr = []
let headerName = save ? 'x-qf-cookie' : 'set-cookie'
let varVal = ''
for(var key in this.addedCookies) {
var val = this.addedCookies[key]
var headerVal = key+'='+val+(this.isSecure ? ';Secure;SameSite=None' : '')
logger.log('+C '+headerName+':'+headerVal)
if(isRedirect) {
if(varVal) {
varVal+='|||'
}
varVal+=headerVal
} else {
obj.addHeader(headerName,headerVal)
}
}
if(isRedirect) {
obj.setVariable('PMUSER_QF_REDVAR',varVal)
}
}
/**
* @param {Object} obj the JSON object on which to set the cache-control.
* @param {boolean} save whether to save the value to be set later, or set directly with cache-control header.
*/
setNoCache(obj,save) {
if(!this.doneNoCache) {
return
}
if(this.d) logger.log('NC')
let headerName = save ? 'x-qf-cache' : 'cache-control'
obj.setHeader(headerName, 'no-store,no-cache,max-age=0')
if(!save) {
obj.setHeader('expires','Thu, 1 Jan 1970 00:00:00 GMT')
}
}
}
/** The QueueFairAdapter class */
class QueueFairAdapter {
// Passed in constructor
service
// You must set this to the full URL of the page before running the adapter.
url = null
// You must set this to the visitor's User Agent before running the adapter.
userAgent = null
// Optional extra data for your Queue Page.
extra = null
// If you have multiple custom domains for your queues use this.
queueDomain = null
// -------------------- Internal use only -----------------
static cookieNameBase='QueueFair-Pass-'
d = false
uid = null
continuePage = true
settings = null
redirectLoc=null
adapterResult=null
adapterQueue=null
consultingAdapter=false
passed = []
protocol = 'https'
passedString = null
// For managing the getting and caching of settings.
static memSettings = null
static lastMemSettingsRead = -1
static gettingSettings = false
settingsCounter = 0
thisIsGettingSettings = false
// For returning from promise or timing out.
res=null
waitingRes = null
finished = false
/** Convenience method
* @param {Object} config configuration for the adapter.
* @param {Object} service a service encapsulating low level functions.
*/
constructor(service) {
this.service = service
if (config.debug === false) {
// defaults to false.
} else if (config.debug === true ||
config.debug === service.remoteAddr()) {
this.d = true
}
}
/** Convenience method
* @param {string} haystack
* @param {string} needle
* @return {boolean} does haystack contain needle.
*/
includes(haystack, needle) {
return (haystack.indexOf(needle)!=-1)
}
/** Convenience method
* @param {string} haystack
* @param {string} needle
* @return {boolean} does haystack start with needle.
*/
startsWith(haystack, needle) {
return (haystack.indexOf(needle)===0)
}
/** Convenience method
* @param {string} haystack
* @param {string} needle
* @return {boolean} does haystack end with needle.
*/
endsWith(haystack, needle) {
return (haystack.indexOf(needle) != -1 &&
haystack.indexOf(needle) == haystack.length-needle.length)
}
/** Is this request a match for the queue?
* @param {Object} queue json
* @return {boolean} whether this request matches the
* queue's Activation Rules.
*/
isMatch(queue) {
if (!queue || !queue.activation || !queue.activation.rules) {
return false
}
return this.isMatchArray(queue.activation.rules)
}
/** Runs through an array of rules.
* @param {Array} arr an array of rule objects.
* @return {boolean} whether the rules match.
*/
isMatchArray(arr) {
if (arr == null) {
return false
}
let firstOp = true
let state = false
for (let i = 0; i < arr.length; i++) {
const rule = arr[i]
if (!firstOp && rule.operator != null) {
if (rule.operator == 'And' && !state) {
return false
} else if (rule.operator == 'Or' && state) {
return true
}
}
const ruleMatch = this.isRuleMatch(rule)
if (firstOp) {
state = ruleMatch
firstOp = false
if (this.d) this.log('R1:' + ((ruleMatch) ? 'true' : 'false'))
} else {
if (this.d) {
this.log('R' + (i+1) +
': ' + ((ruleMatch) ? 'true' : 'false'))
}
if (rule.operator == 'And') {
state = (state && ruleMatch)
if (!state) {
break
}
} else if (rule.operator == 'Or') {
state = (state || ruleMatch)
if (state) {
break
}
}
}
}
if (this.d) this.log('Result' + ((state) ? 'true' : 'false'))
return state
}
/** Extract the right component for a rule.
* @param {Object} rule the rule.
* @param {string} url the requested URL.
* @return {string} the component.
*/
extractComponent(rule, url) {
let comp = url
if (rule.component == 'Domain') {
comp=comp.replace('http://', '').replace('https://', '').split(/[/?#]/)[0]
} else if (rule.component == 'Path') {
const domain=comp.replace('http://', '').replace('https://', '').split(/[/?#]/)[0]
comp=comp.substring(comp.indexOf(domain)+domain.length)
let i=0
if (this.startsWith(comp, ':')) {
// We have a port
i=comp.indexOf('/')
if (i !=-1 ) {
comp=comp.substring(i)
} else {
comp=''
}
}
i=comp.indexOf('#')
if (i!=-1) {
comp=comp.substring(0, i)
}
i=comp.indexOf('?')
if (i!=-1) {
comp=comp.substring(0, i)
}
if (comp=='') {
comp='/'
}
} else if (rule.component == 'Query') {
const i = comp.indexOf('?')
if (i == -1) {
comp = ''
} else if (comp == '?') {
comp=''
} else {
comp = comp.substring(i+1)
}
} else if (rule.component == 'Cookie') {
comp=this.getCookie(rule.name)
}
return comp
}
/** Tests URL and cookies against a rule.
* @param {Object} rule the rule.
* @return {boolean} true if matched.
*/
isRuleMatch(rule) {
const comp = this.extractComponent(rule, this.url)
return this.isRuleMatchWithValue(rule, comp)
}
/** Test a component against a rule.
* @param {Object} rule the rule.
* @param {string} comp the component.
* @return {boolean} true if matched.
*/
isRuleMatchWithValue(rule, comp) {
let test=rule.value
if (rule.caseSensitive == false) {
comp=comp.toLowerCase()
test=test.toLowerCase()
}
if (this.d) this.log('T'+rule.component+' '+test+' vs '+comp)
let ret=false
if (rule.match=='Equal' && comp == test) {
ret=true
} else if (rule.match=='Contain' && comp!==null &&
this.includes(comp, test)) {
ret=true
} else if (rule.match=='Exist') {
if (typeof comp == 'undefined' || comp===null || ''===comp) {
ret=false
} else {
ret=true
}
} else if (rule.match == 'RegExp') {
if(typeof comp == 'undefined' || comp === null) {
comp = ''
}
var r = new RegExp(test)
ret = r.test(comp)
}
if (rule.negate) {
ret=!ret
}
return ret
}
/** What to do if a queue match is found.
* @param {Object} queue json.
* @return {boolean} whether further queues should be checked now.
*/
async onMatch(queue) {
if (await this.isPassed(queue)) {
if (this.d) this.log('Passed '+queue.name);
if (this.extra == 'CLEAR') {
const val=this.getCookie(QueueFairAdapter.cookieNameBase+queue.name)
if (this.d) this.log('Clear '+val);
if (''!==val) {
this.setCookie(queue.name, val, 20, queue.cookieDomain)
} else {
return true
}
} else {
return true
}
}
if (this.d) this.log('A '+queue.displayName);
this.consultAdapter(queue)
return false
}
/** Checks if a queue has been passed already.
* @param {Object} queue json
* @return {boolean} true if passed.
*/
async isPassed(queue) {
if (this.passed[queue.name]) {
if (this.d) this.log('Q '+queue.name+' passed');
return true
}
const queueCookie=this.getCookie(QueueFairAdapter.cookieNameBase +
queue.name)
if (!queueCookie || queueCookie==='') {
if (this.d) this.log('NC '+queue.name);
return false
}
if (!this.includes(queueCookie, queue.name)) {
if (this.d) this.log('InvC '+queueCookie+' '+queue.name);
return false
}
if (!await this.validateCookieWithQueue(queue, queueCookie)) {
if (this.d) this.log('FailC ' + queueCookie);
this.setCookie(queue.name, '', 0, queue.cookieDomain)
return false
}
if (this.d) this.log('OKC '+queue.name+' '+queueCookie);
return true
}
/** Creates a SHA256 HMAC hash. MODIFIED from node.js adapter.
* @param {string} secret the secret to use.
* @param {string} message the message to sign.
* @return {string} a hash.
*/
async createHash(secret, message) {
var key
if(compiledSecrets[secret]) {
key = compiledSecrets[secret]
} else {
const secretKeyData = encoder.encode(secret)
key = await crypto.subtle.importKey('raw',secretKeyData,
{ name: 'HMAC', hash: 'SHA-256' },
false,['sign'])
compiledSecrets[secret] = key
}
var mac = await crypto.subtle.sign('HMAC', key, encoder.encode(message))
mac = [...new Uint8Array(mac)]
.map(x => x.toString(16).padStart(2, '0'))
.join('')
return mac
}
/** Processes a User-Agent for use with signature.
* @param {string} parameter the string to process.
* @return {string} a processed string.
*/
processIdentifier(parameter) {
if (parameter == null) {
return null
}
const i = parameter.indexOf('[')
if (i == -1) {
return parameter
}
if (i < 20) {
return parameter
}
return parameter.substring(0, i)
}
/** Called to validate a cookie. May be called externally
* (Hybrid Security Model). MODIFIED async.
* @param {Object} queue json
* @param {string} cookie the cookie value to validate
* @return {boolean} whether it's valid
*/
async validateCookieWithQueue(queue, cookie) {
return await this.validateCookie(queue.secret,
queue.passedLifetimeMinutes, cookie)
}
/** Called to validate a cookie. May be called externally
* (Hybrid Security Model). MODIFIED async
* @param {string} secret the queue secret.
* @param {number} passedLifetimeMinutes the maximum allowed
* lifetime in minutes.
* @param {string} cookie the cookie value to validate
* @return {boolean} whether it's valid
*/
async validateCookie(secret, passedLifetimeMinutes, cookie) {
if (this.d) this.log('Validating cookie ' + cookie);
if (cookie == null || ''==cookie) {
return false
}
try {
const parsed = this.strToPairs(cookie)
if (parsed['qfh'] == null) {
return false
}
const hash = parsed['qfh']
const hpos = cookie.lastIndexOf('qfh=')
const check = cookie.substring(0, hpos)
const checkHash = await this.createHash(secret,
this.processIdentifier(this.userAgent)+check)
if (hash != checkHash) {
if (this.d) this.log('BadHash ' + hash + ' ' + checkHash);
return false
}
let tspos = parsed['qfts']
tspos = parseInt(tspos)
if (!Number.isInteger(tspos)) {
if (this.d) this.log('BadTS ' + tspos);
return false
}
if (tspos < this.time() - (passedLifetimeMinutes * 60)) {
if (this.d) {
this.log('OldTS ' +
(this.time() - tspos))
}
return false
}
if (this.d) this.log('OKC');
return true
} catch (err) {
if (this.d) this.log('FailC Err '+err);
}
return false
}
/** Parses a query string into an array of key-value pairs.
* @param {string} str the query string.
* @return {Array} the array of pairs.
*/
strToPairs(str) {
const q = []
const vars = str.split('&')
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split('=')
if (pair.length > 1) {
q[pair[0]] = decodeURIComponent(pair[1])
}
}
return q
}
/** Convenience method
* @return {number} epoch time in seconds.
*/
time() {
return Date.now()/1000
}
/** Checks if a Passed String is valid. MODIFIED async
* @param {Object} queue json
* @return {boolean} whether it's valid or not.
*/
async validateQuery(queue) {
try {
const i = this.url.indexOf('?')
if (i == -1) {
return false
}
let str = this.url.substring(i)
if ('?' == str) {
return false
}
str = str.substring(1)
const hpos = str.lastIndexOf('qfh=')
if (hpos == -1) {
if (this.d) this.log('NoHash');
return false
}
if (this.d) this.log('QV ' + str);
const qpos = str.lastIndexOf('qfqid=')
if (qpos === -1) {
if (this.d) this.log('NoQID');
return false
}
const q = this.strToPairs(str)
const queryHash = q['qfh']
if (!queryHash) {
if (this.d) this.log('MalHash');
return false
}
// const queryQID = q['qfqid']
let queryTS = q['qfts']
// const queryAccount = q['qfa']
// const queryQueue = q['qfq']
// const queryPassType = q['qfpt']
if (queryTS == null) {
if (this.d) this.log('NoTS');
return false
}
queryTS = parseInt(queryTS)
if (!Number.isInteger(queryTS)) {
if (this.d) this.log('Non#TS '+queryTS);
return false
}
if (queryTS > this.time() + config.queryTimeLimitSeconds) {
if (this.d) this.log('LateTS ' + queryTS + ' ' + this.time());
return false
}
if (queryTS < this.time() - config.queryTimeLimitSeconds) {
if (this.d) this.log('EarlyTS ' + queryTS + ' ' + this.time());
return false
}
const check = str.substring(qpos, hpos)
const checkHash = await this.createHash(queue.secret,
this.processIdentifier(this.userAgent) + check)
if (checkHash != queryHash) {
if (this.d) this.log('FailHash '+checkHash);
return false
}
return true
} catch (err) {
if (this.d) this.log('QV Err '+err);
return false
}
}
/** Called to set the UID from a cookie if present. */
setUIDFromCookie() {
const cookieBase = 'QueueFair-Store-' + config.account
const uidCookie = this.getCookie(cookieBase)
if (uidCookie == '') {
return
}
let i = uidCookie.indexOf(':')
if (i == -1) {
i = uidCookie.indexOf('=')
}
if (i == -1) {
if (this.d) this.log('UIDNoSep ' + uidCookie);
this.uid = uidCookie
return
}
this.uid = uidCookie.substring(i + 1)
if (this.d) this.log('SetUID ' + this.uid);
}
/** Gets a cookie
* @param {string} cname the name of the cookie
* @return {string} the cookie value, or '' if not found.
*/
getCookie(cname) {
if (cname==='' || cname===null) {
return ''
}
const val = this.service.getCookie(cname)
if (val === null) {
return ''
}
return val
}
/** Called when settings as a string have been found
* MODIFIED async
* @param {string} data the settings as a json object
*/
async gotSettingsStr(data) {
try {
const json = JSON.parse(data)
QueueFairAdapter.memSettings = json
QueueFairAdapter.lastMemSettingsRead = Date.now()
json.stamp = QueueFairAdapter.lastMemSettingsRead
await this.gotSettings(QueueFairAdapter.memSettings)
} catch (err) {
this.releaseGetting()
this.errorHandler(err)
}
}
/** Called when settings have been found. MODIFIED async
* @param {Object} json the settings as a json object
*/
async gotSettings(json) {
this.releaseGetting()
this.settings=json
try {
await this.checkQueryString()
if (!this.continuePage) {
return
}
await this.parseSettings()
} catch (err) {
this.errorHandler(err)
}
}