-
Notifications
You must be signed in to change notification settings - Fork 769
/
ppp.js
801 lines (641 loc) · 19.2 KB
/
ppp.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
/** @decorator */
import {
observable,
html,
Observable,
css
} from './vendor/fast-element.min.js';
import { DesignToken } from './design/design-token.js';
import {
bufferToString,
generateIV,
stringToBuffer
} from './lib/ppp-crypto.js';
import { PPPElement } from './lib/ppp-element.js';
import { APIS } from './lib/const.js';
import { TAG } from './lib/tag.js';
export const keySet = [
'github-login',
'github-token',
'master-password',
'mongo-api-key',
'mongo-app-client-id',
'mongo-app-client-id',
'mongo-app-id',
'mongo-group-id',
'mongo-private-key',
'mongo-public-key',
'global-proxy-url'
];
class KeyVault {
#keys = {};
ok() {
if (this.getKey('tag') !== TAG) return false;
return keySet.map((k) => this.getKey(k)).every((i) => !!i);
}
setKey(key, value) {
if (key) {
this.#keys[key] = value;
localStorage.setItem(`ppp-${key}`, (value ?? '').trim());
}
}
decacheKey(key) {
this.#keys[key] = void 0;
}
getKey(key) {
if (!this.#keys[key])
this.#keys[key] = (localStorage.getItem(`ppp-${key}`) ?? '').trim();
return this.#keys[key];
}
removeKey(key) {
this.#keys[key] = void 0;
localStorage.removeItem(`ppp-${key}`);
}
}
class PPPCrypto {
#key;
resetKey() {
this.#key = void 0;
}
async #generateKey(password = ppp.keyVault.getKey('master-password')) {
if (!this.#key) {
const rawKey = new TextEncoder().encode(
password.slice(0, 32).padEnd(32, '.')
);
this.#key = await window.crypto.subtle.importKey(
'raw',
rawKey,
'AES-GCM',
true,
['encrypt', 'decrypt']
);
}
return this.#key;
}
async encrypt(iv, plaintext, password) {
if (typeof iv === 'string') iv = stringToBuffer(iv);
const encoded = new TextEncoder().encode(plaintext);
const key = await this.#generateKey(password);
const ciphertext = await window.crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv
},
key,
encoded
);
return bufferToString(ciphertext);
}
async decrypt(iv, ciphertext, password) {
if (typeof iv === 'string') iv = stringToBuffer(iv);
const key = await this.#generateKey(password);
const decrypted = await window.crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv
},
key,
stringToBuffer(ciphertext)
);
return new TextDecoder().decode(decrypted);
}
}
(class DesignSystemCanvas extends PPPElement {
connectedCallback() {
super.connectedCallback();
DesignToken.registerDefaultStyleTarget(this);
}
})
.compose({
template: html` <slot></slot> `,
styles: css`
:host {
position: relative;
height: 100%;
}
`
})
.define();
class SettingsMap extends Map {
#observable;
constructor(observable) {
super();
this.#observable = observable;
}
load(key, value) {
return super.set(key, value);
}
set(key, value) {
super.set(key, value);
Observable.notify(this.#observable, 'settings');
if (ppp.keyVault?.ok()) {
return ppp.user.functions.updateOne(
{
collection: 'app'
},
{
_id: '@settings'
},
{
$set: {
[key]: value
}
},
{
upsert: true
}
);
}
}
}
class PPP {
@observable
workspaces;
@observable
extensions;
@observable
settings;
@observable
darkMode;
locales = ['ru', 'en'];
locale =
localStorage.getItem('ppp-locale') ??
this.locales.find((l) => {
return new RegExp(`^${l}\\b`, 'i').test(navigator.language);
}) ??
this.locales[0];
get i18nLocale() {
return {
en: 'en-US',
ru: 'ru-RU'
}[this.locale];
}
crypto = new PPPCrypto();
pusherConnections = new Map();
keyVault = new KeyVault();
constructor(appType) {
this.workspaces = [];
this.extensions = [];
this.settings = new SettingsMap(this);
this.designSystemCanvas = document.querySelector(
'ppp-design-system-canvas'
);
this.darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
const savedDarkMode = localStorage.getItem('ppp-dark-mode');
if (typeof savedDarkMode === 'string') {
if (savedDarkMode === '0') this.darkMode = false;
else if (savedDarkMode === '1') this.darkMode = true;
else localStorage.setItem('ppp-dark-mode', '2');
} else {
localStorage.setItem('ppp-dark-mode', '2');
}
this.appType = appType;
this.rootUrl = window.location.origin;
if (this.rootUrl.endsWith('.github.io')) this.rootUrl += '/ppp';
if (!this.keyVault.ok()) {
this.#createApplication({ emergency: true });
} else {
this.#createApplication({});
}
}
structuredClone(value) {
if (typeof structuredClone === 'function') {
return structuredClone(value);
} else {
return Object.assign({}, value);
}
}
#showLoadingError({
errorText,
shouldShowGlobalProxyUrlInput,
shouldShowSwitchToCloudDBButton
}) {
document.querySelector('.splashscreen-loader').classList.add('error');
document.querySelector('.loading-text').classList.add('error');
document.querySelector('.loading-text').textContent = errorText;
if (shouldShowGlobalProxyUrlInput) {
document.querySelector('.global-proxy-url').removeAttribute('hidden');
}
if (shouldShowSwitchToCloudDBButton) {
document.querySelector('.switch-to-cloud-db').removeAttribute('hidden');
}
}
async #rebuildDictionary() {
let savedPhrases = {};
if (this.dict) {
savedPhrases = ppp.structuredClone(this.dict.phrases);
}
this.dict = new Polyglot({
locale: this.locale
});
(await import(`./i18n/${this.locale}/lib/ppp-errors.i18n.js`)).default(
this.dict
);
this.dict.extend(savedPhrases);
}
async #createApplication({ emergency }) {
await this.#rebuildDictionary();
if (!emergency) {
const { getApp, Credentials } = await import(
`${this.rootUrl}/lib/realm.js`
);
const { Traders } = await import(
`${this.rootUrl}/lib/traders/runtime.js`
);
try {
this.traders = new Traders();
this.realm = getApp(this.keyVault.getKey('mongo-app-client-id'));
this.credentials = Credentials.apiKey(
this.keyVault.getKey('mongo-api-key')
);
this.user = await this.realm.logIn(this.credentials, false);
} catch (e) {
console.error(e);
if (e.statusCode === 401 || e.statusCode === 404) {
this.keyVault.removeKey('mongo-api-key');
return this.#createApplication({ emergency: true });
} else {
if (/Failed to fetch/i.test(e?.message)) {
if (localStorage.getItem('ppp-use-alternative-mongo') === '1') {
this.#showLoadingError({
errorText: this.t('$pppErrors.E_NO_MONGODB_CONNECTION'),
shouldShowSwitchToCloudDBButton: true
});
const listener = function () {
localStorage.removeItem('ppp-use-alternative-mongo');
window.location.reload();
const button = document.querySelector('.switch-to-cloud-db');
button.setAttribute('hidden', '');
button.removeEventListener('click', listener);
};
document
.querySelector('.switch-to-cloud-db')
.addEventListener('click', listener);
} else {
this.#showLoadingError({
errorText: this.t('$pppErrors.E_NO_PROXY_CONNECTION'),
shouldShowGlobalProxyUrlInput: true
});
}
} else {
this.#showLoadingError({
errorText: this.t('$pppErrors.E_UNKNOWN')
});
}
return;
}
}
} else {
const params = Object.fromEntries(
new URLSearchParams(window.location.search).entries()
);
if (params.page !== 'cloud-services') {
window.history.replaceState(
'',
'',
`${window.location.origin}${window.location.pathname}?page=cloud-services`
);
}
}
if (!emergency) {
try {
const lines = ((context) => {
const db = context.services.get('mongodb-atlas').db('ppp');
const workspaces = db
.collection('workspaces')
.find(
{ removed: { $not: { $eq: true } } },
{ _id: 1, name: 1, order: 1 }
);
const settings = db.collection('app').findOne({ _id: '@settings' });
const extensions = db
.collection('extensions')
.find({ removed: { $not: { $eq: true } } });
return { workspaces, settings, extensions };
})
.toString()
.split(/\r?\n/);
lines.pop();
lines.shift();
const evalRequest = await this.user.functions.eval(lines.join('\n'));
this.workspaces = evalRequest.workspaces ?? [];
this.extensions = evalRequest.extensions ?? [];
for (const key in evalRequest.settings ?? {}) {
if (key !== '_id') {
this.settings.load(key, evalRequest.settings?.[key]);
}
}
await import(`${this.rootUrl}/lib/debug.js`);
const storedDarkMode = this.settings.get('darkMode');
if (storedDarkMode === '1') {
this.darkMode = true;
localStorage.setItem('ppp-dark-mode', '1');
} else if (storedDarkMode === '0') {
this.darkMode = false;
localStorage.setItem('ppp-dark-mode', '0');
} else if (storedDarkMode === '2') {
this.darkMode = window.matchMedia(
'(prefers-color-scheme: dark)'
).matches;
localStorage.setItem('ppp-dark-mode', '2');
}
const locale = this.settings.get('language');
if (this.locales.includes(locale)) {
this.locale = locale;
}
await this.#rebuildDictionary();
localStorage.setItem('ppp-locale', this.locale);
} catch (e) {
console.error(e);
if (/Failed to fetch/i.test(e?.message)) {
if (localStorage.getItem('ppp-use-alternative-mongo') === '1') {
this.#showLoadingError({
errorText: this.t('$pppErrors.E_NO_MONGODB_CONNECTION'),
shouldShowSwitchToCloudDBButton: true
});
const listener = function () {
localStorage.removeItem('ppp-use-alternative-mongo');
window.location.reload();
const button = document.querySelector('.switch-to-cloud-db');
button.setAttribute('hidden', '');
button.removeEventListener('click', listener);
};
document
.querySelector('.switch-to-cloud-db')
.addEventListener('click', listener);
} else {
this.#showLoadingError({
errorText: this.t('$pppErrors.E_NO_PROXY_CONNECTION'),
shouldShowGlobalProxyUrlInput: true
});
}
} else if (/failed to find refresh token/i.test(e?.message)) {
sessionStorage.removeItem('realmLogin');
window.location.reload();
} else if (/Cannot access member 'db' of undefined/i.test(e?.message)) {
this.#showLoadingError({
errorText: this.t('$pppErrors.E_BROKEN_ATLAS_REALM_LINK')
});
} else if (
/error resolving cluster hostname/i.test(e?.message) ||
/error connecting to MongoDB cluster/i.test(e?.message) ||
/server selection error/i.test(e?.message)
) {
this.#showLoadingError({
errorText: this.t('$pppErrors.E_OFFLINE_MONGODB_APP')
});
} else if (/function not found/i.test(e?.message)) {
this.#showLoadingError({
errorText: this.t(
'$pppErrors.E_CLOUD_SERVICES_MISCONFIGURATION_PLEASE_WAIT'
)
});
setTimeout(() => {
localStorage.removeItem('ppp-mongo-app-id');
localStorage.removeItem('ppp-tag');
window.location.reload();
}, 5000);
} else {
this.#showLoadingError({
errorText: this.t('$pppErrors.E_UNKNOWN')
});
}
return;
}
}
try {
await import(`./elements/app.js`);
const appElement = document.createElement('ppp-app');
this.app = this.designSystemCanvas.appendChild(appElement);
document
.querySelector('.splashscreen-loader')
.setAttribute('hidden', true);
} catch (e) {
console.error(e);
this.#showLoadingError({
errorText: this.t('$pppErrors.E_UNKNOWN')
});
}
}
async i18n(url) {
let { origin } = new URL(url);
const rootUrl = window.location.origin;
if (rootUrl.endsWith('.github.io')) {
origin += '/ppp';
}
(
await import(
`./i18n/${this.locale}${url
.split(origin)[1]
.replace('.js', '.i18n.js')}`
)
).default(this.dict);
}
t(key, options) {
return this.dict.t(key, options);
}
async encrypt(document = {}) {
const clone = this.structuredClone(document);
let iv;
for (const key in clone) {
if (
/(token|key|secret|password)$/i.test(key) &&
!(key === 'key' && clone?.type === APIS.PUSHER)
) {
if (!iv) {
iv = generateIV();
}
clone[key] = await this.crypto.encrypt(iv, clone[key]);
clone.iv = bufferToString(iv);
}
}
return clone;
}
async decrypt(document = {}) {
const clone = this.structuredClone(document);
for (const key in clone) {
if (
/(token|key|secret|password)$/i.test(key) &&
!(key === 'key' && clone?.type === APIS.PUSHER)
) {
try {
clone[key] = await this.crypto.decrypt(document.iv, clone[key]);
} catch (e) {
if (!(key === 'key' && clone?.type === APIS.PUSHER)) {
throw e;
}
}
} else if (
clone[key] !== null &&
typeof clone[key] === 'object' &&
clone[key].iv
) {
clone[key] = await this.decrypt(clone[key]);
}
}
return clone;
}
decryptDocumentsTransformation() {
return async (d) => {
if (Array.isArray(d)) {
const mapped = [];
for (const document of d) {
mapped.push(await this.decrypt(document));
}
return mapped;
}
return d;
};
}
brandSvg(svg) {
return `static/brand/${ppp.darkMode ? 'dark' : 'light'}/${svg}.svg`;
}
async getOrCreateTrader(document, options) {
return this.traders.getOrCreateTrader(document, options);
}
async getOrCreatePusherConnection(document) {
if (document) {
await import(`${ppp.rootUrl}/vendor/pusher.min.js`);
Pusher.logToConsole = false;
if (!this.pusherConnections.has(document._id)) {
this.pusherConnections.set(
document._id,
new Pusher(document.key, {
cluster: document.cluster,
enabledTransports: ['ws', 'wss'],
disabledTransports: ['xhr_streaming', 'xhr_polling', 'sockjs']
})
);
this.pusherConnections.get(document._id).subscribe('telegram');
this.pusherConnections.get(document._id).subscribe('ppp');
this.pusherConnections.get(document._id).subscribe('psina');
}
return this.pusherConnections.get(document._id);
}
}
async nextInstrumentCacheVersion({ exchange, broker }) {
const cacheFieldName = `instrumentCache:${exchange}:${broker}`;
await this.user.functions.updateOne(
{
collection: 'app'
},
{
_id: '@settings'
},
{
$inc: {
[cacheFieldName]: 1
}
},
{
upsert: true
}
);
const response = await this.user.functions.findOne(
{
collection: 'app'
},
{
_id: '@settings'
}
);
const result = +response[cacheFieldName];
this.settings.load(cacheFieldName, result);
return result;
}
async openInstrumentCache({ exchange, broker }) {
let version = 1;
// Check for Firefox garbage browser.
if (typeof indexedDB.databases === 'function') {
const databases = await indexedDB.databases();
const database = databases.find((db) => db.name === 'ppp');
if (database) {
version = database.version;
}
}
const checkStoreRequest = indexedDB.open('ppp');
let storeNames;
try {
storeNames = Array.from(
await new Promise((resolve, reject) => {
checkStoreRequest.onsuccess = () => {
if (typeof indexedDB.databases !== 'function') {
version = checkStoreRequest.result.version;
}
resolve(checkStoreRequest.result.objectStoreNames);
};
checkStoreRequest.onerror = (event) => {
reject(event.target.error);
};
})
);
} finally {
checkStoreRequest.result.close();
}
const storeName = `${exchange}:${broker}`;
if (!storeNames.includes(storeName)) {
version++;
}
const openRequest = indexedDB.open('ppp', version);
return new Promise((resolve, reject) => {
openRequest.onupgradeneeded = () => {
const db = openRequest.result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: 'symbol' });
}
db.onerror = (event) => {
console.error(event.target.error);
reject(event.target.error);
};
};
openRequest.onsuccess = () => {
const db = openRequest.result;
db.onversionchange = () => {
db.close();
};
resolve(openRequest.result);
};
});
}
getWorkerTemplateFullUrl(relativeOrAbsoluteUrl) {
let url;
if (relativeOrAbsoluteUrl.startsWith('/')) {
const rootUrl = window.location.origin;
if (rootUrl.endsWith('.github.io'))
url = new URL('/ppp' + relativeOrAbsoluteUrl, rootUrl);
else url = new URL(relativeOrAbsoluteUrl, rootUrl);
} else {
url = new URL(relativeOrAbsoluteUrl);
}
return url;
}
async fetch(url, options = {}, allowedHeaders = []) {
const globalProxy = this.keyVault.getKey('global-proxy-url');
if (globalProxy) {
const urlObject = new URL(url);
options.headers ??= {};
options.headers['X-Host'] = urlObject.hostname;
options.headers['X-Port'] = urlObject.port;
for (const h of Object.keys(options.headers)) {
const lower = h.toLowerCase();
if (lower === 'x-host' || lower === 'x-port') {
continue;
}
if (!allowedHeaders.includes(lower)) {
allowedHeaders.push(h);
}
}
options.headers['X-Allowed-Headers'] = allowedHeaders.join(',');
urlObject.hostname = new URL(globalProxy).hostname;
urlObject.port = 443;
return fetch(urlObject.toString(), options);
} else {
return fetch(url, options);
}
}
}
/** @global */
globalThis.ppp ??= new PPP(
document.documentElement.getAttribute('ppp-app-type')
);
export default globalThis.ppp;