-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathindex.ts
632 lines (567 loc) · 19.1 KB
/
index.ts
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
import { captureError } from '../errors'
import { createLieDetector, documentLie } from '../lies'
import { getWebGLRendererConfidence, compressWebGLRenderer } from '../trash'
import { createTimer, queueEvent, getOS, getUserAgentPlatform, decryptUserAgent, computeWindowsRelease, JS_ENGINE, logTestResult, isUAPostReduction, performanceLogger, hashSlice, IS_WORKER_SCOPE, IS_BLINK, getReportedPlatform } from '../utils/helpers'
import { HTMLNote } from '../utils/html'
export const enum Scope {
WORKER = 0,
WINDOW,
}
export let WORKER_TYPE = ''
export let WORKER_NAME = ''
export async function spawnWorker() {
const ask = (fn) => {
try {
return fn()
} catch (e) {
return
}
}
function getWorkerPrototypeLies(scope: Window & typeof globalThis) {
const lieDetector = createLieDetector(scope)
const {
searchLies,
} = lieDetector
searchLies(() => Function, {
target: [
'toString',
],
ignore: [
'caller',
'arguments',
],
})
// @ts-expect-error
searchLies(() => WorkerNavigator, {
target: [
'deviceMemory',
'hardwareConcurrency',
'language',
'languages',
'platform',
'userAgent',
],
})
// return lies list and detail
const props = lieDetector.getProps()
const propsSearched = lieDetector.getPropsSearched()
return {
lieDetector,
lieList: Object.keys(props).sort(),
lieDetail: props,
lieCount: Object.keys(props).reduce((acc, key) => acc + props[key].length, 0),
propsSearched,
}
}
const getUserAgentData = async (navigator) => {
if (!('userAgentData' in navigator)) {
return
}
const data = await navigator.userAgentData.getHighEntropyValues(
['platform', 'platformVersion', 'architecture', 'bitness', 'model', 'uaFullVersion'],
)
const { brands, mobile } = navigator.userAgentData || {}
const compressedBrands = (brands, captureVersion = false) => brands
.filter((obj) => !/Not/.test(obj.brand)).map((obj) => `${obj.brand}${captureVersion ? ` ${obj.version}` : ''}`)
const removeChromium = (brands) => (
brands.length > 1 ? brands.filter((brand) => !/Chromium/.test(brand)) : brands
)
// compress brands
if (!data.brands) {
data.brands = brands
}
data.brandsVersion = compressedBrands(data.brands, true)
data.brands = compressedBrands(data.brands)
data.brandsVersion = removeChromium(data.brandsVersion)
data.brands = removeChromium(data.brands)
if (!data.mobile) {
data.mobile = mobile
}
const dataSorted = Object.keys(data).sort().reduce((acc, key) => {
acc[key] = data[key]
return acc
}, {})
return dataSorted
}
const getWebglData = () => ask(() => {
// @ts-ignore
const canvasOffscreenWebgl = new OffscreenCanvas(256, 256)
const contextWebgl = canvasOffscreenWebgl.getContext('webgl')
const rendererInfo = contextWebgl.getExtension('WEBGL_debug_renderer_info')
return {
webglVendor: contextWebgl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL),
webglRenderer: contextWebgl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL),
}
})
const computeTimezoneOffset = () => {
const date = new Date().getDate()
const month = new Date().getMonth()
// @ts-ignore
const year = Date().split` `[3] // current year
const format = (n) => (''+n).length == 1 ? `0${n}` : n
const dateString = `${month+1}/${format(date)}/${year}`
const dateStringUTC = `${year}-${format(month+1)}-${format(date)}`
// @ts-ignore
const utc = Date.parse(new Date(dateString))
const now = +new Date(dateStringUTC)
return +(((utc - now)/60000).toFixed(0))
}
const getLocale = () => {
const constructors = [
'Collator',
'DateTimeFormat',
'DisplayNames',
'ListFormat',
'NumberFormat',
'PluralRules',
'RelativeTimeFormat',
]
// @ts-ignore
const locale = constructors.reduce((acc, name) => {
try {
const obj = new Intl[name]
if (!obj) {
return acc
}
const { locale } = obj.resolvedOptions() || {}
return [...acc, locale]
} catch (error) {
return acc
}
}, [])
return [...new Set(locale)]
}
const getWorkerData = async () => {
const timer = createTimer()
await queueEvent(timer)
const userAgentData = await getUserAgentData(navigator).catch((error) => console.error(error))
// webgl
const { webglVendor, webglRenderer } = getWebglData() || {}
// timezone & locale
const timezoneOffset = computeTimezoneOffset()
// eslint-disable-next-line new-cap
const timezoneLocation = Intl.DateTimeFormat().resolvedOptions().timeZone
const locale = getLocale()
// navigator
const {
hardwareConcurrency,
language,
languages,
platform,
userAgent,
// @ts-expect-error
deviceMemory,
} = navigator || {}
// prototype lies
await queueEvent(timer)
const {
// lieDetector: lieProps,
lieList,
lieDetail,
// lieCount,
// propsSearched,
} = getWorkerPrototypeLies(self) // execute and destructure the list and detail
// const prototypeLies = JSON.parse(JSON.stringify(lieDetail))
const protoLieLen = lieList.length
// match engine locale to system locale to determine if locale entropy is trusty
let systemCurrencyLocale
const lang = (''+language).split(',')[0]
try {
systemCurrencyLocale = (1).toLocaleString((lang || undefined), {
style: 'currency',
currency: 'USD',
currencyDisplay: 'name',
minimumFractionDigits: 0,
maximumFractionDigits: 0,
})
} catch (e) {}
const engineCurrencyLocale = (1).toLocaleString(undefined, {
style: 'currency',
currency: 'USD',
currencyDisplay: 'name',
minimumFractionDigits: 0,
maximumFractionDigits: 0,
})
const localeEntropyIsTrusty = engineCurrencyLocale == systemCurrencyLocale
const localeIntlEntropyIsTrusty = new Set((''+language).split(',')).has(''+locale)
const { href, pathname } = self.location || {}
const locationPathNameLie = (
!href ||
!pathname ||
!/^\/(docs|creepjs|public)|\/creep.js$/.test(pathname) ||
!new RegExp(`${pathname}$`).test(href)
)
return {
lied: protoLieLen || +locationPathNameLie,
lies: {
proto: protoLieLen ? lieDetail : false,
},
locale: ''+locale,
systemCurrencyLocale,
engineCurrencyLocale,
localeEntropyIsTrusty,
localeIntlEntropyIsTrusty,
timezoneOffset,
timezoneLocation,
deviceMemory,
hardwareConcurrency,
language,
languages: ''+languages,
platform,
userAgent,
webglRenderer,
webglVendor,
userAgentData,
}
}
// Compute and communicate from worker scope
const onEvent = (eventType, fn) => addEventListener(eventType, fn)
const send = (source) => {
return getWorkerData().then((data) => source.postMessage(data))
}
if (IS_WORKER_SCOPE) {
globalThis.ServiceWorkerGlobalScope ? onEvent('message', (e) => send(e.source)) :
globalThis.SharedWorkerGlobalScope ? onEvent('connect', (e) => send(e.ports[0])) :
send(self) // DedicatedWorkerGlobalScope
}
return IS_WORKER_SCOPE ? Scope.WORKER : Scope.WINDOW
}
export default async function getBestWorkerScope() {
try {
const timer = createTimer()
await queueEvent(timer)
const ask = (fn) => {
try {
return fn()
} catch (e) {
return
}
}
const hasConstructor = (x, name) => x && x.__proto__.constructor.name == name
const getDedicatedWorker = ({ scriptSource }) => new Promise((resolve) => {
const giveUpOnWorker = setTimeout(() => {
return resolve(null)
}, 3000)
const dedicatedWorker = ask(() => new Worker(scriptSource))
if (!hasConstructor(dedicatedWorker, 'Worker')) return resolve(null)
dedicatedWorker.onmessage = (event) => {
dedicatedWorker.terminate()
clearTimeout(giveUpOnWorker)
return resolve(event.data)
}
})
const getSharedWorker = ({ scriptSource }) => new Promise((resolve) => {
const giveUpOnWorker = setTimeout(() => {
return resolve(null)
}, 3000)
const sharedWorker = ask(() => new SharedWorker(scriptSource))
if (!hasConstructor(sharedWorker, 'SharedWorker')) return resolve(null)
sharedWorker.port.start()
sharedWorker.port.onmessage = (event) => {
sharedWorker.port.close()
clearTimeout(giveUpOnWorker)
return resolve(event.data)
}
})
const getServiceWorker = ({ scriptSource }) => new Promise((resolve) => {
const giveUpOnWorker = setTimeout(() => {
return resolve(null)
}, 4000)
if (!ask(() => navigator.serviceWorker.register)) return resolve(null)
return navigator.serviceWorker.register(scriptSource).then((registration) => {
if (!hasConstructor(registration, 'ServiceWorkerRegistration')) return resolve(null)
return navigator.serviceWorker.ready.then((registration) => {
// @ts-ignore
registration.active.postMessage(undefined)
navigator.serviceWorker.onmessage = (event) => {
registration.unregister()
clearTimeout(giveUpOnWorker)
return resolve(event.data)
}
})
}).catch((error) => {
console.error(error)
clearTimeout(giveUpOnWorker)
return resolve(null)
})
})
const scriptSource = './creep.js'
WORKER_NAME = 'ServiceWorkerGlobalScope'
WORKER_TYPE = 'service' // loads fast but is not available in frames
let workerScope = await getServiceWorker({ scriptSource }).catch((error) => {
captureError(error)
console.error(error.message)
return
})
if (!(workerScope || {}).userAgent) {
WORKER_NAME = 'SharedWorkerGlobalScope'
WORKER_TYPE = 'shared' // no support in Safari, iOS, and Chrome Android
workerScope = await getSharedWorker({ scriptSource }).catch((error) => {
captureError(error)
console.error(error.message)
return
})
}
if (!(workerScope || {}).userAgent) {
WORKER_NAME = 'DedicatedWorkerGlobalScope'
WORKER_TYPE = 'dedicated' // device emulators can easily spoof dedicated scope
workerScope = await getDedicatedWorker({ scriptSource }).catch((error) => {
captureError(error)
console.error(error.message)
return
})
}
if (!(workerScope || {}).userAgent) {
return
}
workerScope.system = getOS(workerScope.userAgent)
workerScope.device = getUserAgentPlatform({ userAgent: workerScope.userAgent })
// detect lies
const {
system,
userAgent,
userAgentData,
platform,
deviceMemory,
hardwareConcurrency,
} = workerScope || {}
// navigator lies
// skip language and languages to respect valid engine language switching bug in Chrome
// these are more likely navigator lies, so don't trigger lied worker scope
const workerScopeMatchLie = 'does not match worker scope'
if (platform != navigator.platform) {
documentLie('Navigator.platform', workerScopeMatchLie)
}
if (userAgent != navigator.userAgent) {
documentLie('Navigator.userAgent', workerScopeMatchLie)
}
if (hardwareConcurrency && (hardwareConcurrency != navigator.hardwareConcurrency)) {
documentLie('Navigator.hardwareConcurrency', workerScopeMatchLie)
}
// @ts-ignore
if (deviceMemory && (deviceMemory != navigator.deviceMemory)) {
documentLie('Navigator.deviceMemory', workerScopeMatchLie)
}
// prototype lies
if (workerScope.lies.proto) {
const { proto } = workerScope.lies
const keys = Object.keys(proto)
keys.forEach((key) => {
const api = `WorkerGlobalScope.${key}`
const lies = proto[key]
lies.forEach((lie) => documentLie(api, lie))
})
}
// user agent os lie
const [userAgentOS, platformOS] = getReportedPlatform(userAgent, platform)
if (userAgentOS != platformOS) {
workerScope.lied = true
workerScope.lies.os = `${platformOS} platform and ${userAgentOS} user agent do not match`
documentLie('WorkerGlobalScope', workerScope.lies.os)
}
// user agent engine lie
const decryptedName = decryptUserAgent({
ua: userAgent,
os: system,
isBrave: false, // default false since we are only looking for JS runtime and version
})
const userAgentEngine = (
(/safari/i.test(decryptedName) || /iphone|ipad/i.test(userAgent)) ? 'JavaScriptCore' :
/firefox/i.test(userAgent) ? 'SpiderMonkey' :
/chrome/i.test(userAgent) ? 'V8' :
undefined
)
if (userAgentEngine != JS_ENGINE) {
workerScope.lied = true
workerScope.lies.engine = `${JS_ENGINE} JS runtime and ${userAgentEngine} user agent do not match`
documentLie('WorkerGlobalScope', workerScope.lies.engine)
}
// user agent version lie
const getVersion = (x) => (/\d+/.exec(x) || [])[0]
const userAgentVersion = getVersion(decryptedName)
const userAgentDataVersion = getVersion(userAgentData ? userAgentData.uaFullVersion : '')
const versionSupported = userAgentDataVersion && userAgentVersion
const versionMatch = userAgentDataVersion == userAgentVersion
if (versionSupported && !versionMatch) {
workerScope.lied = true
workerScope.lies.version = `userAgentData version ${userAgentDataVersion} and user agent version ${userAgentVersion} do not match`
documentLie('WorkerGlobalScope', workerScope.lies.version)
}
// platformVersion lie
const FEATURE_CASE = IS_BLINK && CSS.supports('accent-color: initial')
const getPlatformVersionLie = (device, userAgentData) => {
if (!/windows|mac/i.test(device) || !userAgentData?.platformVersion) {
return false
}
if (userAgentData.platform == 'macOS') {
return FEATURE_CASE ? /_/.test(userAgentData.platformVersion) : false
}
const reportedVersionNumber = (/windows ([\d|\.]+)/i.exec(device)||[])[1]
const windows10OrHigherReport = +reportedVersionNumber == 10
const { platformVersion } = userAgentData
const versionMap: Record<string, string> = {
'6.1': '7',
'6.2': '8',
'6.3': '8.1',
'10.0': '10',
}
const version = versionMap[platformVersion]
if (!FEATURE_CASE && version) {
return version != reportedVersionNumber
}
const parts = platformVersion.split('.')
if (parts.length != 3) return true
const windows10OrHigherPlatform = +parts[0] > 0
return (
(windows10OrHigherPlatform && !windows10OrHigherReport) ||
(!windows10OrHigherPlatform && windows10OrHigherReport)
)
}
const windowsVersionLie = getPlatformVersionLie(workerScope.device, userAgentData)
if (windowsVersionLie) {
workerScope.lied = true
workerScope.lies.platformVersion = `platform version is fake`
documentLie('WorkerGlobalScope', workerScope.lies.platformVersion)
}
// capture userAgent version
workerScope.userAgentVersion = userAgentVersion
workerScope.userAgentDataVersion = userAgentDataVersion
workerScope.userAgentEngine = userAgentEngine
const gpu = {
...(getWebGLRendererConfidence(workerScope.webglRenderer) || {}),
compressedGPU: compressWebGLRenderer(workerScope.webglRenderer),
}
logTestResult({ time: timer.stop(), test: `${WORKER_TYPE} worker`, passed: true })
return {
...workerScope,
gpu,
uaPostReduction: isUAPostReduction(workerScope.userAgent),
}
} catch (error) {
logTestResult({ test: 'worker', passed: false })
captureError(error, 'workers failed or blocked by client')
return
}
}
export function workerScopeHTML(fp) {
if (!fp.workerScope) {
return `
<div class="col-six undefined">
<strong>Worker</strong>
<div>lang/timezone:</div>
<div class="block-text">${HTMLNote.BLOCKED}</div>
<div>gpu:</div>
<div class="block-text">${HTMLNote.BLOCKED}</div>
</div>
<div class="col-six undefined">
<div>userAgent:</div>
<div class="block-text">${HTMLNote.BLOCKED}</div>
<div>device:</div>
<div class="block-text">${HTMLNote.BLOCKED}</div>
<div>userAgentData:</div>
<div class="block-text">${HTMLNote.BLOCKED}</div>
</div>`
}
const { workerScope: data } = fp
const {
lied,
locale,
systemCurrencyLocale,
engineCurrencyLocale,
localeEntropyIsTrusty,
localeIntlEntropyIsTrusty,
timezoneOffset,
timezoneLocation,
deviceMemory,
hardwareConcurrency,
language,
// languages,
platform,
userAgent,
uaPostReduction,
webglRenderer,
webglVendor,
gpu,
userAgentData,
system,
device,
$hash,
} = data || {}
const {
parts,
warnings,
gibbers,
confidence,
grade: confidenceGrade,
compressedGPU,
} = gpu || {}
return `
<span class="time">${performanceLogger.getLog()[`${WORKER_TYPE} worker`]}</span>
<span class="aside-note-bottom">${WORKER_NAME || ''}</span>
<div class="relative col-six${lied ? ' rejected' : ''}">
<strong>Worker</strong><span class="hash">${hashSlice($hash)}</span>
<div class="help">lang/timezone:</div>
<div class="block-text help" title="WorkerNavigator.language\nWorkerNavigator.languages\nIntl.Collator.resolvedOptions()\nIntl.DateTimeFormat.resolvedOptions()\nIntl.DisplayNames.resolvedOptions()\nIntl.ListFormat.resolvedOptions()\nIntl.NumberFormat.resolvedOptions()\nIntl.PluralRules.resolvedOptions()\nIntl.RelativeTimeFormat.resolvedOptions()\nNumber.toLocaleString()\nIntl.DateTimeFormat().resolvedOptions().timeZone\nDate.getDate()\nDate.getMonth()\nDate.parse()">
${
localeEntropyIsTrusty ? `${language} (${systemCurrencyLocale})` :
`${language} (<span class="bold-fail">${engineCurrencyLocale}</span>)`
}
${
locale === language ? '' : localeIntlEntropyIsTrusty ? ` ${locale}` :
` <span class="bold-fail">${locale}</span>`
}
<br>${timezoneLocation} (${''+timezoneOffset})
</div>
<div class="relative">${
confidence ? `<span class="confidence-note">confidence: <span class="scale-up grade-${confidenceGrade}">${confidence}</span></span>` : ''
}gpu:</div>
<div class="block-text help" title="${
confidence ? `\nWebGLRenderingContext.getParameter()\ngpu compressed: ${compressedGPU}\nknown parts: ${parts || 'none'}\ngibberish: ${gibbers || 'none'}\nwarnings: ${warnings.join(', ') || 'none'}` : 'WebGLRenderingContext.getParameter()'
}">
${webglVendor ? webglVendor : ''}
${webglRenderer ? `<br>${webglRenderer}` : HTMLNote.UNSUPPORTED}
</div>
</div>
<div class="col-six${lied ? ' rejected' : ''}">
<div class="relative">userAgent:${!uaPostReduction ? '' : `<span class="confidence-note">ua reduction</span>`}</div>
<div class="block-text help" title="WorkerNavigator.userAgent">
<div>${userAgent || HTMLNote.UNSUPPORTED}</div>
</div>
<div>device:</div>
<div class="block-text help" title="WorkerNavigator.deviceMemory\nWorkerNavigator.hardwareConcurrency\nWorkerNavigator.platform\nWorkerNavigator.userAgent">
${`${system}${platform ? ` (${platform})` : ''}`}
${device ? `<br>${device}` : HTMLNote.BLOCKED}
${
hardwareConcurrency && deviceMemory ? `<br>cores: ${hardwareConcurrency}, ram: ${deviceMemory}` :
hardwareConcurrency && !deviceMemory ? `<br>cores: ${hardwareConcurrency}` :
!hardwareConcurrency && deviceMemory ? `<br>ram: ${deviceMemory}` : ''
}
</div>
<div>userAgentData:</div>
<div class="block-text help" title="WorkerNavigator.userAgentData\nNavigatorUAData.getHighEntropyValues()">
<div>
${((userAgentData) => {
const {
architecture,
bitness,
brandsVersion,
uaFullVersion,
mobile,
model,
platformVersion,
platform,
} = userAgentData || {}
// @ts-ignore
const windowsRelease = computeWindowsRelease({ platform, platformVersion })
return !userAgentData ? HTMLNote.UNSUPPORTED : `
${(brandsVersion || []).join(',')}${uaFullVersion ? ` (${uaFullVersion})` : ''}
<br>${windowsRelease || `${platform} ${platformVersion}`} ${architecture ? `${architecture}${bitness ? `_${bitness}` : ''}` : ''}
${model ? `<br>${model}` : ''}
${mobile ? '<br>mobile' : ''}
`
})(userAgentData)}
</div>
</div>
</div>
`
}