-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequest.js
1585 lines (1357 loc) · 34.8 KB
/
Request.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
/* eslint-disable class-methods-use-this, max-lines */
const {UAParser} = require('ua-parser-js');
const bodyParser = require('koa-body');
const IPRange = require('./IPRange');
const GeoIP = require('./GeoIP');
const enableRateLimit = require('./rateLimit');
const enableBasicAuth = require('./basicAuth');
const enableStaticPaths = require('./staticPaths');
const enableBotBanning = require('./botBanning');
const {setLogger, logError} = require('./logger');
const uaParser = new UAParser();
const ONE_HOUR = 3600 * 1000;
const ONE_DAY = 24 * ONE_HOUR;
const ONE_MONTH = 30 * ONE_DAY;
const ONE_YEAR = 365 * ONE_DAY;
const TEN_YEARS = 10 * ONE_YEAR;
const PLATFORM_PARAM = 'platform';
const PLATFORM_COOKIE = 'platform';
const APPINFO_PARAM = 'sm_app';
const APPINFO_COOKIE = 'sm_app';
const APPINFO_HEADER = 'sm-app';
const TRACKING_HEADER = 'sm-tracking';
const UTM_COOKIE = 'sm_utm';
const AFFID_PARAM = 'affid';
const SUBAFFID_PARAM = 'subaffid';
const COUNTRY_COOKIE = 'country';
const AFFID_COOKIE = 'sm_aff';
const AFFID_COOKIE_DURATION = ONE_DAY;
const REF_PARAM = 'ref';
const SESSIONID_COOKIE = 'sid';
const COOKIEID_COOKIE = 'id';
const COOKIE_PARAM_PREFIX = '_ck_';
const USER_TOKEN_COOKIE = 'utok';
const FLASH_COOKIE = 'flash';
const VIEWPORT_WIDTH_COOKIE = 'vw';
// these cookies are httpOnly, should not be readable from js
const SENSITIVE_COOKIES = [USER_TOKEN_COOKIE, COOKIEID_COOKIE, SESSIONID_COOKIE];
const APP_PLATFORMS = new Map([
['android', {}],
['ios', {}],
['wp', {}],
['tizen', {}],
['jio', {}],
]);
// sometimes request parameters can be an array (like &q=s&q=b)
// since we expect a string, this will convert array to a string
function handleArray(value, defaultValue = '') {
if (Array.isArray(value)) {
return value[value.length - 1] || value[0] || defaultValue;
}
return value || defaultValue;
}
function sanitizeCookiePart(value, defaultValue = '') {
if (!value) return defaultValue;
return handleArray(value).replace(/\|/g, '!~!').substring(0, 255);
}
function joinCookieParts(parts, defaultValue = '') {
return parts.map(part => sanitizeCookiePart(part, defaultValue)).join('|');
}
function splitCookieParts(cookie) {
return cookie.split('|').map(part => part.replace(/!~!/g, '|'));
}
/**
* return [subDomain, baseDomain, canHaveSubdomain]
*/
function getDomainParts(domain) {
const parts = domain.split('.');
if (parts.length <= 1) {
// domain is localhost
return ['', domain, false];
}
if (/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test(domain)) {
// domain is an ip
return ['', domain, false];
}
if (parts.length <= 2) {
// a simple domain like example.com
return ['', domain, true];
}
const secondTld = parts[parts.length - 2];
if (/co|nic|gov/i.test(secondTld)) {
// a domain with second level tld, like example.co.uk
if (parts.length <= 3) {
return ['', domain, true];
}
}
return [parts[0], parts.slice(1).join('.'), true];
}
function randomId(length) {
let id = '';
while (id.length < length) {
id += Math.random().toString(36).substring(2);
}
return id.substring(0, length);
}
function getIntegerKey(key) {
if (typeof key === 'number') return key;
if (typeof key === 'string') {
let value = 0;
for (let i = 0; i < key.length; ++i) {
value = ((value << 5) - value) + key.charCodeAt(i); // value * 31 + c
value |= 0; // to 32bit integer
}
return value;
}
return key;
}
function addQuery(url, query = {}) {
try {
const uri = new URL(url, 'http://localhost');
if (typeof query === 'string') {
query = new URLSearchParams(query);
for (const [key, val] of query) {
uri.searchParams.set(key, val);
}
}
else {
for (const [key, val] of Object.entries(query)) {
uri.searchParams.set(key, val);
}
}
return `${uri.pathname}${uri.search}`;
}
catch (e) {
logError(e);
return url;
}
}
const isProduction = (process.env.NODE_ENV === 'production');
class Request {
/**
* @param {import('koa').Context} ctx
*/
constructor(ctx, options = {}) {
this.ctx = ctx;
this.options = options;
}
/** @type {Routes.installer} */
static install(app, options = {}) {
enableStaticPaths(app, options.staticPaths);
app.use(bodyParser({
multipart: true,
}));
if (options.middleware) {
app.use(this.middleware(options));
}
enableBasicAuth(app, options.basicAuth);
enableBotBanning(app, options.banBots);
enableRateLimit(app, options.rateLimit);
}
/** @returns {Routes.middleware} */
static middleware(options) {
return async (ctx, next) => {
ctx.$req = await this.from(ctx, options);
await next();
};
}
/**
* @param {import('koa').Context} ctx
*/
static async from(ctx, options) {
const req = new this(ctx, options);
await req.init();
return req;
}
appPlatforms() {
return APP_PLATFORMS;
}
/**
* get or set request header value
* @param {string} name name of the header
* @param {string} value value to set, if not given header value is return
* @returns {string}
* get: header value, or empty string if header not found
* set: empty string
* @example
* // get header value
* ctx.$req.header('user-agent')
* // set header value
* ctx.$req.header('ETag', '1234')
*/
header(name, value) {
// get header value
if (value === undefined) {
return this.ctx.headers[name.toLowerCase()] || '';
}
// set header value
this.ctx.set(name, value);
return '';
}
/**
* Get value from either from request body or query params
* @param {string} key
* @param {string} defaultValue
* @return {any}
*/
param(key, defaultValue = '') {
const ctx = this.ctx;
let paramValue;
if (ctx.request.body &&
ctx.request.body.fields &&
(key in ctx.request.body.fields)
) {
paramValue = ctx.request.body.fields[key];
}
if (ctx.request.body &&
(key in ctx.request.body)
) {
paramValue = ctx.request.body[key];
}
else {
paramValue = ctx.query[key];
}
paramValue = paramValue || defaultValue;
if (typeof paramValue === 'string') return paramValue.trim();
if (Array.isArray(paramValue)) return paramValue.map(v => v.trim());
return paramValue;
}
/**
* Get parameter as a string (from query or body)
* @param {string} key
* @param {number} defaultValue
* @returns {number}
*/
paramStr(key, defaultValue = '') {
const value = this.param(key, null);
if (value === null) return defaultValue;
return String(value);
}
/**
* Get parameter as an integer (from query or body)
* @param {string} key
* @param {number} defaultValue
* @returns {number}
*/
paramInt(key, defaultValue = 0) {
const value = this.param(key, null);
if (value === null) return defaultValue;
const intVal = Number(value);
if (Number.isNaN(intVal)) {
return defaultValue;
}
return intVal;
}
/**
* Get parameter as a boolean
* Only '0', 'false', 'no', 'off' are considered falsy
* empty string is truthy, so url?param would be truthy
* but url?param=0 or url?param=false would be falsy
* @param {string} key
* @param {boolean} defaultValue
* @returns {boolean}
*/
paramBool(key, defaultValue = false) {
const value = this.param(key, null);
if (value === null) return defaultValue;
if (
value === false ||
value === 0 ||
value === '0' ||
value === 'false' ||
value === 'no' ||
value === 'off'
) return false;
return true;
}
/**
* Get the parameter as an id.
* id any is a max 20 character long alphanumeric string
* @param {string} key
* @param {string} defaultValue
* @returns {string}
*/
paramId(key, defaultValue = '') {
const value = this.param(key, null);
if (value === null) return defaultValue;
if (/^[A-Za-z0-9]{1,20}$/.test(value)) return value;
return defaultValue;
}
/**
* get a string parameter and escape it for xss attacks
* @param {string} key
* @param {string} defaultValue
* @returns {string} value of the param
*/
paramXSS(key, defaultValue = '') {
const param = this.param(key, null);
if (param === null) return defaultValue;
return param.replace(/([<>"'])/g, (match, g1) => {
switch (g1) {
case '<': return '<';
case '>': return '>';
case '"': return '"';
case '\'': return ''';
default: return g1;
}
});
}
/**
* Get the file with this param name
* @param {string} key
* @returns
*/
file(key) {
return this.files(key)[0] || null;
}
/**
* Get all the files with this param name
* @param {string} key
* @returns {array}
*/
files(key) {
if (this.ctx.request.files && this.ctx.request.files[key]) {
const result = this.ctx.request.files[key];
if (!Array.isArray(result)) return [result];
return result.filter(Boolean);
}
return [];
}
/**
* Get the bearer token of the request.
* Authorization: Bearer abc would give abc as bearer token
* @returns {string}
*/
bearerToken() {
const authorization = this.ctx.headers.authorization;
if (!authorization) return '';
const parts = authorization.split(' ');
if (parts.length !== 2) return '';
if (parts[0] !== 'Bearer') return '';
return parts[1];
}
/**
* Get the api token of the request.
* API token can be sent as a header x-api-token
* @returns {string}
*/
apiToken() {
return this.header('x-api-token');
}
/**
* initialize a request
* set important cookies and all
*/
async init() {
// don't allow other domains to embed our iframe
if (isProduction) {
const domain = this.baseDomain();
this.ctx.set('Content-Security-Policy', `frame-ancestors https://*.${domain}`);
}
if (!this.isAjax()) {
this.setUTMCookie();
this.setAffidCookie();
this.handleFlashMessage();
// in case of visit out from app we need to set cookies from params
if (this.ctx.query.installId) {
await this.setCookiesFromParams();
}
}
}
/**
* check whether the request is http or https
* isHttp returns false if the request is https, true otherwise
* @returns {boolean}
*/
isHttp() {
if (this._isHttp === undefined) {
const ctx = this.ctx;
this._isHttp = (ctx.headers.origin || '').startsWith('http:') || (ctx.headers.host || '').includes(':');
if (!this._isHttp && this.ctx.protocol !== 'https') {
this.ctx.cookies.secure = true;
}
}
return this._isHttp;
}
/**
* @typedef {Object} CustomCookieOpts
* @property {boolean} [onlyCache]
* @property {boolean} [onlyCacheIfExists]
* @property {number} [days]
* @property {number} [years]
*/
/**
* Get or set a cookie
* @template {string | number | boolean | undefined} V
* @param {string} name
* @param {V} value
* @param {CustomCookieOpts & import('cookies').SetOption} [options]
* @returns {V extends undefined ? string : null}
*/
cookie(name, value, options = {}) {
const cookies = this._cookies || (this._cookies = {});
if (value === undefined) {
if (name in cookies) {
return cookies[name];
}
const existing = this.ctx.cookies.get(name) || '';
return decodeURIComponent(existing);
}
cookies[name] = value;
// only set the cookie in cache
// don't set it in real
if (options.onlyCache) {
return null;
}
// set the cookie only if does not exist
// but always set it in cache
if (options.onlyCacheIfExists) {
if (this.ctx.cookies.get(name)) return null;
}
// clone options
options = Object.assign({}, options);
if (options.domain === '*') {
options.domain = this.baseDomain();
}
if (!('path' in options)) {
options.path = '/';
}
if ('days' in options) {
options.maxAge = options.days * ONE_DAY;
}
if ('years' in options) {
options.maxAge = options.years * ONE_YEAR;
}
if (!('httpOnly' in options)) {
if (!SENSITIVE_COOKIES.includes(name)) {
options.httpOnly = false;
}
}
const isHttp = this.isHttp();
if (!('secure' in options) && !isHttp) {
options.secure = true;
}
if (!('sameSite' in options)) {
// sameSite = none means intentionally send the cookie in 3rd party contexts
options.sameSite = isHttp ? false : 'none';
}
if (value) {
value = encodeURIComponent(value);
}
this.ctx.cookies.set(name, value, options);
return null;
}
/**
* Used for sending tracking info from other servers/sites
* @template {string | undefined} T
* @param {T} key
* @returns {T extends string ? string : Object.<string, string>}
*/
trackingHeader(key) {
if (!this._trackingHeader) {
const header = this.header(TRACKING_HEADER);
if (!header) {
this._trackingHeader = {};
}
else {
try {
this._trackingHeader = JSON.parse(header) || {};
}
catch (e) {
this._trackingHeader = {};
}
}
}
return key ? this._trackingHeader[key] : this._trackingHeader;
}
/**
* Get the user agent of the request.
* @returns {string}
*/
userAgent() {
return this.trackingHeader('user-agent') || this.header('user-agent');
}
/**
* Get the referer of the request.
* @returns {string}
*/
referer() {
return this.trackingHeader('referer') || this.header('referer');
}
/**
* Get the referer name of the request.
* @returns {string}
*/
refererName() {
return this._refererName;
}
/**
* Parse the user agent with ua-parser-js and return the result
* Returns {ua: '', browser: {}, cpu: {}, device: {}, engine: {}, os: {} }
* @returns {object}
*/
parseUserAgent() {
if (!this._ua) {
this._ua = uaParser.setUA(this.userAgent()).getResult() || {};
}
return this._ua;
}
/**
* Get the browser name
* @returns {string}
*/
browser() {
const ua = this.parseUserAgent();
const deviceType = (ua && ua.device && ua.device.type) || '';
const browserName = (ua && ua.browser && ua.browser.name) || '';
if (deviceType === 'mobile') {
switch (browserName) {
case 'Chrome': return 'Chrome Mobile';
case 'Firefox': return 'Firefox Mobile';
case 'Safari': return 'Safari Mobile';
case 'Mobile Safari': return 'Safari Mobile';
default: return browserName;
}
}
return browserName;
}
/**
* Get the browser name + version (eg. Chrome 96.1.0.110)
* @returns {string}
*/
browserVersion() {
const ua = this.parseUserAgent();
let browerVersion = (ua.browser && ua.browser.version) || '';
if (browerVersion) browerVersion = ' ' + browerVersion;
return this.browser() + browerVersion;
}
/**
* Get the browser version only (eg. 96.1.0.110)
* @returns {string}
*/
browserVersionRaw() {
const ua = this.parseUserAgent();
const version = (ua.browser && ua.browser.version) || '';
return String(version);
}
/**
* Get the os name (eg. Windows)
* @returns {string}
*/
os() {
const ua = this.parseUserAgent();
return (ua.os && ua.os.name) || '';
}
/**
* Get the os name + version (eg. Windows 11)
* @returns {string}
*/
osVersion() {
const ua = this.parseUserAgent();
let osVersion = (ua.os && ua.os.version) || '';
if (osVersion) osVersion = ' ' + osVersion;
return this.os() + osVersion;
}
/**
* Get the header sm-user-agent
* @returns {string}
*/
smUserAgent() {
return this.header('sm-user-agent');
}
appUserAgent() {
return this.smUserAgent() || this.userAgent();
}
getAppInfoFromUserAgent() {
return null;
}
_getAppInfoFromString(infoStr, separator = '#') {
if (!infoStr) return null;
// eslint-disable-next-line prefer-const
let [os, appVersion, installId] = infoStr.split(separator);
os = os.toLowerCase();
const appInfo = {};
if (os) {
appInfo.os = os;
}
if (appVersion) {
appInfo.appVersion = appVersion;
}
if (installId) {
appInfo.installId = installId;
}
if (this.appPlatforms().has(os)) {
appInfo.appType = 'app';
}
return appInfo;
}
getAppInfoFromParam() {
const appInfoParam = this.ctx.query[APPINFO_PARAM];
if (appInfoParam) {
this.cookie(APPINFO_COOKIE, appInfoParam, {
path: '/',
maxAge: TEN_YEARS,
domain: '*',
});
return this._getAppInfoFromString(appInfoParam, ':');
}
const appInfoCookie = this.cookie(APPINFO_COOKIE);
if (appInfoCookie) {
return this._getAppInfoFromString(appInfoParam, ':');
}
return null;
}
getAppInfoFromHeader() {
return this._getAppInfoFromString(this.ctx.headers[APPINFO_HEADER]);
}
getAppInfoCustom() {
return null;
}
_getDeviceTypeFromUA() {
const ua = this.parseUserAgent();
const deviceType = ua.device?.type;
if (deviceType === 'mobile') return 'mobile';
if (deviceType === 'tablet') return 'tablet';
return 'desktop';
}
_getDeviceType() {
const secHeader = this.ctx.headers['sec-ch-ua-mobile'];
if (secHeader) {
if (secHeader === '?1') return 'mobile';
return this._getDeviceTypeFromUA();
}
const vwCookie = this.cookie(VIEWPORT_WIDTH_COOKIE);
if (vwCookie) {
if (Number(vwCookie) <= 750) return 'mobile';
return this._getDeviceTypeFromUA();
}
return this._getDeviceTypeFromUA();
}
computeAppInfo() {
const ctx = this.ctx;
const appInfo1 = this.getAppInfoFromHeader() || {};
const appInfo2 = this.getAppInfoFromParam() || {};
const appInfo3 = this.getAppInfoFromUserAgent() || {};
const appInfo4 = this.getAppInfoCustom() || {};
const appInfo = {
installId: ctx.query.installId,
appVersion: ctx.query.appVersion,
...appInfo4,
...appInfo3,
...appInfo2,
...appInfo1,
};
let xPlatform = (
ctx.query[PLATFORM_PARAM] ||
this.cookie(PLATFORM_COOKIE) ||
ctx.headers['x-sm-platform']
);
if (xPlatform) {
xPlatform = xPlatform.toLowerCase();
if (xPlatform === 'mobile_app') {
if (!appInfo.deviceType) appInfo.deviceType = 'mobile';
if (!appInfo.appType) appInfo.appType = 'app';
}
else {
const os = xPlatform.match(/android|ios|wp|tizen|jio/i)?.[0];
if (os) {
if (!appInfo.deviceType) appInfo.deviceType = 'mobile';
if (!appInfo.appType) appInfo.appType = 'app';
if (!appInfo.os) appInfo.os = os.toLowerCase();
}
else if (!appInfo.deviceType) {
appInfo.deviceType = xPlatform.includes('mobile') ? 'mobile' : 'desktop';
}
}
}
else if (!appInfo.deviceType) {
appInfo.deviceType = this._getDeviceType();
}
return appInfo;
}
/*
* get the app related info using a header / query parameter / user agent
* this means that you can have the url as sm_app=android
* and it'll automatically identify it as an android app
*/
appInfo() {
if (!this._appInfo) {
this._appInfo = this.computeAppInfo() || {};
}
return this._appInfo;
}
installId() {
return this.appInfo().installId || '';
}
appVersion() {
return this.appInfo().appVersion || '';
}
isApp() {
return this.appInfo().appType === 'app';
}
isAndroidApp() {
return this.isApp() && this.appInfo().os === 'android';
}
isIOSApp() {
return this.isApp() && this.appInfo().os === 'ios';
}
isWPApp() {
return this.isApp() && this.appInfo().os === 'wp';
}
isTizenApp() {
return this.isApp() && this.appInfo().os === 'tizen';
}
isJIOApp() {
return this.isApp() && this.appInfo().os === 'jio';
}
isMobileApp() {
return this.isApp() && this.isMobile();
}
isMobileWeb() {
return this.isMobile() && !this.isApp();
}
deviceType() {
return this.appInfo().deviceType || 'desktop';
}
isMobile() {
return this.appInfo().deviceType === 'mobile';
}
isTablet() {
return this.appInfo().deviceType === 'tablet';
}
isDesktop() {
return !this.isMobile();
}
isAPI() {
return false;
}
platform() {
if (this.isApp()) return 'mobile_app';
if (this.isMobile()) return 'mobile_web';
if (this.isAPI()) return 'api';
return 'desktop';
}
/**
* @typedef {Object} UTMObject
* @property {string} source
* @property {string} medium
* @property {string} campaign
* @property {string} term
* @property {string} content
* @property {string} sourceMedium
*/
/**
* @template {string | null} P
* @param {P} [param]
* @returns {P extends null ? UTMObject : P extends string ? string : UTMObject}
*/
utm(param = null) {
if (!this._utm) {
const utmCookie = this.cookie(UTM_COOKIE);
if (!utmCookie) {
this._utm = {};
}
else {
const [source, medium, campaign, term, content] = splitCookieParts(utmCookie);
this._utm = {
source,
medium,
campaign,
term,
content,
sourceMedium: `${source}/${medium}`,
};
}
}
return param ? this._utm[param] : this._utm;
}
/**
* @returns {string}
*/
ref() {
return this.param(REF_PARAM).replace(/[^a-zA-Z0-9_.:~-]+/g, '-');
}
_affidSubaffid() {
const affidCookie = this.cookie(AFFID_COOKIE);
if (!affidCookie) return ['', ''];
const [affid, subaffid] = affidCookie.split('|');
return [affid || '', subaffid || ''];
}
affid() {
return this._affidSubaffid()[0];
}
subaffid() {
return this._affidSubaffid()[1];
}
subAffid() {
return this.subaffid();
}
cookieId() {
let cookieId = this.cookie(COOKIEID_COOKIE);
if (!cookieId) {
const version = '1';
cookieId = version + randomId(15);
this.cookie(COOKIEID_COOKIE, cookieId, {
maxAge: TEN_YEARS,
domain: '*',
});
}
return cookieId;
}
// cookie id that's existing (not set in this request)
existingCookieId() {
return this.ctx.cookies.get(COOKIEID_COOKIE);
}
sessionId() {
let sessionId = this.cookie(SESSIONID_COOKIE);
if (!sessionId) {
const version = '1';
sessionId = version + randomId(15);
this.cookie(SESSIONID_COOKIE, sessionId, {
domain: '*',
});
}
return sessionId;
}
// session id that's existing (not set in this request)
existingSessionId() {
return this.ctx.cookies.get(SESSIONID_COOKIE);
}
isOriginRequest() {
if (!isProduction) return true;
const baseDomain = this.options.baseDomain;
if (!baseDomain) return true;
const origin = this.ctx.headers.origin;
// this is needed because firefox currently does not
// send origin with form submit requests (sends with xhr)
// so this might cause csrf on firefox
if (!origin) return true;
const matches = origin.match(/^((http|https):\/\/)?([^/:]+)[/]?/i);
if (!matches) return false;
if (('.' + matches[3]).endsWith('.' + baseDomain)) return true;
return false;
}
/**
* Get the ip of the request
* @returns {string}
*/
ip() {
if (!this._ip) {
if (this.trackingHeader('ip')) {
this._ip = this.trackingHeader('ip');
}
// nginx proxy sets x-real-ip header as real ip address
else if (this.ctx.headers['x-real-ip']) {
this._ip = this.ctx.headers['x-real-ip'];
}
else {
// ip is of format ::ffff:127.1.0.1, strip ::ffff: from it
this._ip = this.ctx.ip.replace(/^.*:/, '');
}
}
return this._ip;
}
/**
* Get the real ip of the request (after considering x-forwarded-for)
* @returns {string}
*/
realIP() {
if (this._realIP) return this._realIP;
const forwardedFor = this.header('x-forwarded-for');