-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathZitiFirstStrategy.ts
1829 lines (1477 loc) · 69.5 KB
/
ZitiFirstStrategy.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
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
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import {StrategyHandler} from 'workbox-strategies/StrategyHandler.js';
import {CacheFirst} from 'workbox-strategies/CacheFirst.js';
import {StrategyOptions} from 'workbox-strategies/Strategy.js';
import {Mutex, withTimeout, Semaphore} from 'async-mutex';
import { isUndefined, isEqual } from 'lodash-es';
import * as cheerio from 'cheerio';
import {
ZitiBrowzerCore,
ZITI_CONSTANTS
} from '@openziti/ziti-browzer-core';
import pjson from '../package.json';
export interface ZitiFirstOptions extends StrategyOptions {
zitiBrowzerServiceWorkerGlobalScope?: any;
logLevel?: string;
eruda?: boolean;
controllerApi?: string;
zitiNetworkTimeoutSeconds?: number;
uuid?: string;
}
type ZitiShouldRouteResult = {
routeOverZiti?: boolean | false;
serviceName?: string | '';
serviceScheme?: string | '';
serviceConnectAppData?: object | undefined;
url?: string | '';
}
var regexZBR = new RegExp( /ziti-browzer-runtime-\w{8}\.js/, 'g' );
var regexZBRnaked = new RegExp( /ziti-browzer-runtime\.js/, 'gi' );
var regexZBRLogo = new RegExp( /ziti-browzer-logo/, 'g' );
var regexZBRcss = new RegExp( /ziti-browzer-css-\w{8}\.css/, 'g' );
var regexZBRCORS = new RegExp( /ziti-cors-proxy/, 'g' );
var regexEdgeClt = new RegExp( /\/edge\/client\/v1/, 'g' );
var regexZBWASM = new RegExp( /libcrypto.*.wasm/, 'g' );
var regexPolipop = new RegExp( /polipop/, 'g' );
var regexCannySetup = new RegExp( /canny-setup/, 'g' );
var regexOAUTHTOKEN = new RegExp( /\/oauth\/token/, 'g' );
var regexFavicon = new RegExp( /\/favicon\.ico/, 'g' );
var regexJSDelivr = new RegExp( /jsdelivr.net/, 'g' );
var regexAtImport = new RegExp( /\@import/, 'gi' );
var regexSlash = new RegExp( /^\/$/, 'g' );
var regexDotSlash = new RegExp( /^\.\//, 'g' );
var regexTextHtml = new RegExp( /text\/html/, 'i' );
var regexTextXml = new RegExp( /text\/xml/, 'i' );
var regexAppJS = new RegExp( /application\/javascript/, 'i' );
var regexAppJSON = new RegExp( /application\/json/, 'i' );
var regexVideo = new RegExp( /video/, 'i' );
var regexMpeg = new RegExp( /mpeg/, 'i' );
var regexImage = new RegExp( /image\//, 'i' );
var regexCSS = new RegExp( /^.*\.css$/, 'i' );
var regexJS = new RegExp( /^.*\.js$/, 'i' );
var regexPNG = new RegExp( /^.*\.png$/, 'i' );
var regexJPG = new RegExp( /^.*\.jpg$/, 'i' );
var regexSVG = new RegExp( /^.*\.svg$/, 'i' );
var regexControllerAPI: any;
const keycloakJs = `https://cdn.jsdelivr.net/npm/[email protected]/dist/keycloak.min.js`;
const erudaJs = `https://cdn.jsdelivr.net/npm/[email protected]/eruda.min.js`;
interface PolicyResult {
[key: string]: string[];
}
interface PolicyBuilderOptions {
directives: Readonly<Record<string, string[] | string | boolean>>;
}
/**
* An implementation of a Ziti network request strategy.
*
* If the network request fails, and there is no cache match, this will throw
* a `WorkboxError` exception.
*
*/
class ZitiFirstStrategy extends CacheFirst /* NetworkFirst */ {
_zitiBrowzerServiceWorkerGlobalScope: any;
private readonly _zitiNetworkTimeoutSeconds: number;
private readonly _logLevel: string;
private readonly _controllerApi: string;
private _core: any;
private logger: any;
private _zitiContext: any;
private _initialized: boolean;
private _initializationMutex: any;
private _uuid: any;
private _rootPaths: any;
private _targetServiceHost: string;
/**
* @param {Object} [options]
* @param {string} [options._zitiBrowzerServiceWorkerGlobalScope] config dsts
* @param {string} [options._logLevel] Which level to log at
* @param {string} [options._controllerApi] Location of Ziti Controller
* @param {number} [options.zitiNetworkTimeoutSeconds] If set, any network requests
* that fail to respond within the timeout will fallback to the cache.
*
*/
constructor(options: ZitiFirstOptions = {}) {
super(options);
this._zitiBrowzerServiceWorkerGlobalScope = options.zitiBrowzerServiceWorkerGlobalScope || 0;
this._zitiNetworkTimeoutSeconds = options.zitiNetworkTimeoutSeconds || 0;
this._logLevel = options.logLevel || 'Silent';
this._controllerApi = options.controllerApi || '<controllerApi-not-configured>';
this._initialized = false;
this._targetServiceHost = '';
var controllerAPIURL = new URL( this._controllerApi );
regexControllerAPI = new RegExp( controllerAPIURL.host, 'g' );
this._initializationMutex = new Mutex();
this._uuid = options.uuid;
this._rootPaths = [];
this._core = new ZitiBrowzerCore({});
this.logger = this._core.createZitiLogger({
logLevel: this._logLevel,
suffix: 'ZBSW',
useSWPostMessage: options.eruda,
zitiBrowzerServiceWorkerGlobalScope: this._zitiBrowzerServiceWorkerGlobalScope,
});
this.logger.trace(`ZitiFirstStrategy ctor completed`);
}
parseCSP(policy: any): PolicyResult {
const result: PolicyResult = {};
policy.split(";").forEach((directive: any) => {
const [directiveKey, ...directiveValue] = directive.trim().split(/\s+/g);
if (
directiveKey &&
!Object.prototype.hasOwnProperty.call(result, directiveKey)
) {
result[directiveKey] = directiveValue;
}
});
return result;
};
buildCSP({ directives }: Readonly<PolicyBuilderOptions>): string {
const namesSeen = new Set<string>();
const result: string[] = [];
Object.keys(directives).forEach((originalName) => {
const name = originalName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
if (namesSeen.has(name)) {
throw new Error(`${originalName} is specified more than once`);
}
namesSeen.add(name);
let value = directives[originalName];
if (Array.isArray(value)) {
value = value.join(" ");
} else if (value === true) {
value = "";
}
if (value) {
result.push(`${name} ${value}`);
} else if (value !== false) {
result.push(name);
}
});
return result.join("; ");
};
generateNewCSP(val:string|undefined) {
let origCSP = this.parseCSP(val);
this.logger.trace( `generateNewCSP() origCSP: `, origCSP);
let idpURL = new URL(this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.idp.host);
let idpHost = idpURL.host;
let controllerURL = new URL(this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.controller.api);
let controllerHost = controllerURL.host;
if (origCSP['default-src']) {
origCSP['default-src'].push(`https://*.netfoundry.io:*`);
origCSP['default-src'].push(`https://*.cloudziti.io`);
origCSP['default-src'].push(`wss://*.netfoundry.io:*`);
origCSP['default-src'].push("data:");
origCSP['default-src'].push("https://opencollective.com");
}
if (origCSP['script-src']) {
origCSP['script-src'].push(`${this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.idp.host}`.replace('https://',''));
origCSP['script-src'].push(`canny.io`);
if (!origCSP['script-src'].includes("'unsafe-eval'")) {
origCSP['script-src'].push("'unsafe-eval'");
}
}
if (origCSP['connect-src']) {
origCSP['connect-src'].push(`${idpHost}`);
origCSP['connect-src'].push(`${this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host}`);
origCSP['connect-src'].push(`${controllerHost}`);
origCSP['connect-src'].push(`https://*.netfoundry.io:*`);
origCSP['connect-src'].push(`https://*.cloudziti.io`);
origCSP['connect-src'].push(`wss://*.netfoundry.io:*`);
origCSP['connect-src'].push(`wss://localhost:*`);
if (!origCSP['connect-src'].includes("data:")) {
origCSP['connect-src'].push("data:");
}
}
if (origCSP['img-src']) {
origCSP['img-src'].push(`data:`);
origCSP['img-src'].push(`${this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host}`);
origCSP['img-src'].push(`*`);
}
if (origCSP['font-src']) {
if (!origCSP['font-src'].includes("data:")) {
origCSP['font-src'].push("data:");
}
}
let directives:any = {}
if (!isUndefined(origCSP['child-src'])) { directives.childSrc = origCSP['child-src'];}
if (!isUndefined(origCSP['connect-src'])) { directives.connectSrc = origCSP['connect-src'];}
if (!isUndefined(origCSP['default-src'])) { directives.defaultSrc = origCSP['default-src'];}
if (!isUndefined(origCSP['font-src'])) { directives.fontSrc = origCSP['font-src'];}
if (!isUndefined(origCSP['frame-ancestors'])) { directives.frameAncestors = origCSP['frame-ancestors'];}
if (!isUndefined(origCSP['frame-src'])) { directives.frameSrc = origCSP['frame-src'];}
if (!isUndefined(origCSP['img-src'])) { directives.imgSrc = origCSP['img-src'];}
if (!isUndefined(origCSP['media-src'])) { directives.mediaSrc = origCSP['media-src'];}
if (!isUndefined(origCSP['object-src'])) { directives.objectSrc = origCSP['object-src'];}
if (!isUndefined(origCSP['script-src'])) { directives.scriptSrc = origCSP['script-src'];}
if (!isUndefined(origCSP['style-src'])) { directives.styleSrc = origCSP['style-src'];}
if (!isUndefined(origCSP['worker-src'])) { directives.workerSrc = origCSP['worker-src'];}
let newCSP = this.buildCSP({ directives });
let newCSParray = this.parseCSP(newCSP);
this.logger.trace( `generateNewCSP() newCSP: `, newCSParray);
return newCSP;
}
/**
* Remain in lazy-sleepy loop until z-b-runtime sends us the _zitiConfig
*
*/
async await_zitiConfig(requestUrl: string, _handler: StrategyHandler) {
let self = this;
let ctr = 0;
let waitTime = 100;
return new Promise((resolve: any, _reject: any) => {
(async function waitFor_zitiConfig() {
if (isUndefined(self._zitiBrowzerServiceWorkerGlobalScope._zitiConfig) || isUndefined(self._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.access_token)) {
ctr++;
self.logger.trace(`await_zitiConfig: ...waiting [${ctr}] for [${requestUrl}]`);
if (ctr == 5) { // kick the ZBR, and ask for the config
self.logger.trace( 'await_zitiConfig: sending ZITI_CONFIG_NEEDED msg to ZBR');
self._zitiBrowzerServiceWorkerGlobalScope._sendMessageToClients( { type: 'ZITI_CONFIG_NEEDED'} );
setTimeout(waitFor_zitiConfig, waitTime);
}
else if (ctr == 10) { // only do the unregister once
self.logger.trace(`await_zitiConfig: initiating unregister`);
// Let's try and 'reboot' the ZBR/SW pair
await self._zitiBrowzerServiceWorkerGlobalScope._unregister();
return resolve( -1 );
}
else {
setTimeout(waitFor_zitiConfig, waitTime);
}
} else {
self.logger.trace(`await_zitiConfig: config acquired for [${requestUrl}]`);
return resolve( 0 );
}
})();
});
}
/**
* Remain in lazy-sleepy loop until z-b-runtime notifies us that it has completed initialization
*
*/
async await_zbrInitialized(request: Request) {
let self = this;
let ctr = 0;
return new Promise((resolve: any, reject: any) => {
(function waitFor_zbrInitialized() {
if (self._zitiBrowzerServiceWorkerGlobalScope._zbrReloadPending) { // this gets reset when ZBR sends the SW the
self.logger.trace(`await_zbrInitialized: ...waiting for [${request.url}]`);
ctr++;
if (ctr > 40) {return reject();}
setTimeout(waitFor_zbrInitialized, 250);
} else {
self.logger.trace(`await_zbrInitialized: ...acquired for [${request.url}]`);
self.logger.trace(`await_zbrInitialized: ...setting logLevel to [${self._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.sw.logLevel}]`);
self.logger.logLevel = self._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.sw.logLevel;
return resolve();
}
})();
});
}
idpAuthHealthEventHandler(idpAuthHealthEvent: any) {
this.logger.trace(`idpAuthHealthEventHandler() ${idpAuthHealthEvent}`);
if (idpAuthHealthEvent.expired) {
this.logger.trace( `idpAuthHealthEventHandler: authToken has expired and will be torn down`);
setTimeout(function(_zitiBrowzerServiceWorkerGlobalScope: any) {
_zitiBrowzerServiceWorkerGlobalScope._accessTokenExpired(); // This will cause a logout with the IdP
}, 10, this._zitiBrowzerServiceWorkerGlobalScope);
setTimeout(function(_zitiBrowzerServiceWorkerGlobalScope: any) {
_zitiBrowzerServiceWorkerGlobalScope._unregister(); // Let's try and 'reboot' the ZBR/SW pair
}, 500, this._zitiBrowzerServiceWorkerGlobalScope);
}
}
async noConfigForServiceEventHandler(noConfigForServiceEvent: any) {
this.logger.trace(`noConfigForServiceEventHandler() `, noConfigForServiceEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._noConfigForService(noConfigForServiceEvent);
}
async noConfigProtocolForServiceEventHandler(noConfigProtocolForServiceEvent: any) {
this.logger.trace(`noConfigProtocolForServiceEventHandler() `, noConfigProtocolForServiceEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._noConfigProtocolForService(noConfigProtocolForServiceEvent);
}
async WSSEnabledEdgeRouterConnectionErrorEventHandler(wssERConnectionErrorEvent: any) {
this.logger.trace(`WSSEnabledEdgeRouterConnectionErrorEventHandler() `, wssERConnectionErrorEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._wssERConnectionError(wssERConnectionErrorEvent);
}
async ControllerConnectionErrorEventHandler(controllerConnectionErrorEvent: any) {
this.logger.trace(`ControllerConnectionErrorEventHandler() `, controllerConnectionErrorEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._controllerConnectionError(controllerConnectionErrorEvent);
}
async sessionCreationErrorEventHandler(sessionCreationErrorEvent: any) {
this.logger.trace(`sessionCreationErrorEventHandler() `, sessionCreationErrorEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._sessionCreationError(sessionCreationErrorEvent);
this._zitiBrowzerServiceWorkerGlobalScope._unregisterNoReload();
}
async noServiceEventHandler(noServiceEvent: any) {
this.logger.trace(`noServiceEventHandler() `, noServiceEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._noService(noServiceEvent);
this._zitiBrowzerServiceWorkerGlobalScope._unregisterNoReload();
}
async invalidAuthEventHandler(invalidAuthEvent: any) {
this.logger.trace(`invalidAuthEventHandler() `, invalidAuthEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._invalidAuth(invalidAuthEvent);
}
async noWSSRoutersEventHandler(noWSSRoutersEvent: any) {
this.logger.trace(`noWSSRoutersEventHandler() `, noWSSRoutersEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._noWSSRouters(noWSSRoutersEvent);
}
async channelConnectFailEventHandler(channelConnectFailEvent: any) {
this.logger.trace(`channelConnectFailEventHandler() `, channelConnectFailEvent);
await this._zitiBrowzerServiceWorkerGlobalScope._channelConnectFail(channelConnectFailEvent);
}
async xgressEventHandler(xgressEvent: any) {
this._zitiBrowzerServiceWorkerGlobalScope._xgressEvent(xgressEvent);
}
async nestedTLSHandshakeTimeoutEventHandler(nestedTLSHandshakeTimeoutEvent: any) {
this._zitiBrowzerServiceWorkerGlobalScope._nestedTLSHandshakeTimeout(nestedTLSHandshakeTimeoutEvent);
}
/**
* Do all work necessary to initialize the ZitiFirstStrategy instance.
*
*/
async _initialize() {
// Run the init sequence within a critical-section
await this._initializationMutex.runExclusive(async () => {
return new Promise( async (resolve, _) => {
if (!this._initialized) {
this.logger.trace(`_initialize: entered`);
if (isUndefined(this._zitiContext)) {
this._zitiContext = this._core.createZitiContext({
logger: this.logger,
controllerApi: this._controllerApi,
sdkType: pjson.name,
sdkVersion: pjson.version,
sdkBranch: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.sdkBranch,
sdkRevision: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.sdkRevision,
token_type: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.token_type,
id_token: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.id_token,
access_token: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.access_token,
bootstrapperTargetService: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.service,
bootstrapperHost: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host,
});
this.logger.trace(`_initialize: ZitiContext created`);
this._zitiBrowzerServiceWorkerGlobalScope._zitiContext = this._zitiContext;
// Make SW scope available to idpAuthHealthEventHandler
this._zitiContext._zitiBrowzerServiceWorkerGlobalScope = this._zitiBrowzerServiceWorkerGlobalScope;
this._zitiContext.setKeyTypeEC();
await this._zitiContext.initialize({
loadWASM: true, // unlike the ZBR, here in the ZBSW, we always instantiate the internal WebAssembly
jspi: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.jspi,
target: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target,
bootstrapperHost: this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host
});
await this._zitiContext.listControllerVersion();
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_IDP_AUTH_HEALTH, this.idpAuthHealthEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_NO_CONFIG_FOR_SERVICE, this.noConfigForServiceEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_NO_SERVICE, this.noServiceEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_SESSION_CREATION_ERROR, this.sessionCreationErrorEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_INVALID_AUTH, this.invalidAuthEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_CHANNEL_CONNECT_FAIL, this.channelConnectFailEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_NO_WSS_ROUTERS, this.noWSSRoutersEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_XGRESS, this.xgressEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_NESTED_TLS_HANDSHAKE_TIMEOUT, this.nestedTLSHandshakeTimeoutEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_NO_CONFIG_PROTOCOL_FOR_SERVICE, this.noConfigProtocolForServiceEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_WSS_ROUTER_CONNECTION_ERROR, this.WSSEnabledEdgeRouterConnectionErrorEventHandler);
this._zitiContext.on(ZITI_CONSTANTS.ZITI_EVENT_CONTROLLER_CONNECTION_ERROR, this.ControllerConnectionErrorEventHandler);
this.logger.trace(`_initialize: ZitiContext '${this._uuid}' initialized`);
} else {
this.logger.trace(`_initialize: initiating unregister`);
await this._zitiBrowzerServiceWorkerGlobalScope._unregister(); // Let's try and 'reboot' the ZBR/SW pair
this.logger.trace(`_initialize: terminated`);
}
setTimeout(async function(self: any, resolve: any) {
let result = await self._zitiContext.enroll(); // this acquires an ephemeral Cert
if (!result) {
self.logger.trace(`_initialize: ephemeral Cert acquisition failed`);
// If we couldn't acquire a cert, it most likely means that the JWT from the IdP needs a refresh
self.logger.trace(`_initialize: initiating unregister`);
await self._zitiBrowzerServiceWorkerGlobalScope._unregister(); // Let's try and 'reboot' the ZBR/SW pair
self.logger.trace(`_initialize: terminated`);
} else {
self.logger.trace(`_initialize: ephemeral Cert acquisition succeeded`);
self._rootPaths.push(self._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.path);
self._initialized = true;
self.logger.trace(`_initialize: ZitiContext '${self._uuid}' initialize complete`);
}
return resolve(null);
}, 500, this, resolve);
} else {
return resolve(null);
}
});
})
.catch(( err: any ) => {
this.logger.error(err);
return new Promise( async (_, reject) => {
reject( err );
});
});
}
_sendServiceUnavailable(_zitiBrowzerServiceWorkerGlobalScope: any, newUrl: any) {
_zitiBrowzerServiceWorkerGlobalScope._sendMessageToClients(
{
type: 'SERVICE_UNAVAILABLE_TO_IDENTITY',
payload: {
message: `Ziti Service ${newUrl.hostname} is unavailable to your identity; Notify your administrator.`
}
}
)
}
/**
* Determine if this request should be routed over Ziti, or over raw internet.
*
* @private
* @param {Request} request The request from the fetch event.
* @return {ZitiShouldRouteResult} If request should go over Ziti we return a (possibly adjusted) URL
*/
async _shouldRouteOverZiti(request: Request) {
let result: ZitiShouldRouteResult = {}
this.logger.trace(`_shouldRouteOverZiti starting`);
let url = new URL(request.url);
result.url = url.toString();
let targetHost = url.hostname;
let targetPort = url.port;
if (isEqual(targetHost, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host) && isEqual(targetPort,'')) {
targetPort = '443';
}
let targetPath = url.pathname;
this.logger.trace(`_shouldRouteOverZiti targetHost:port path is: ${targetHost}:${targetPort} ${targetPath}`);
try {
// We want to intercept fetch requests that target the Ziti BrowZer Bootstrapper... that is...
// ...we want to intercept any request from the web app that targets the server from
// which the app was loaded.
let targetserviceHost = await this._zitiContext.getConfigHostByServiceName (this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.service);
let connectAppData = await this._zitiContext.getConnectAppDataByServiceName (this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.service, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.scheme);
var targetServiceRegex = new RegExp( targetserviceHost , 'g' );
var browzerLoadBalancerRegex = new RegExp( this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.loadbalancer.host , 'g' );
if (
(isEqual(targetHost, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host) && (isEqual(targetPort, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.port))) // yes, the request is targeting the Ziti BrowZer Bootstrapper
||
(isEqual(targetHost, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host) && (isEqual(targetPort, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.loadbalancer.port))) // yes, the request is targeting the Ziti BrowZer LB
||
(this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.loadbalancer.host && request.url.match( browzerLoadBalancerRegex ))
) { // yes, the request is targeting the Ziti BrowZer LoadBalancer
var newUrl = new URL( request.url );
if ( isEqual(targetPath, '/')) {
result.routeOverZiti = true;
result.serviceName = this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.service;
result.serviceScheme = this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.scheme;
result.serviceConnectAppData = connectAppData;
}
else if ( (request.url.match( regexZBR )) || (request.url.match( regexZBRnaked )) || (request.url.match( regexZBWASM )) || (request.url.match( regexZBRLogo )) || (request.url.match( regexZBRcss )) || (request.url.match( regexZBRCORS ))) { // the request seeks z-b-r/wasm/logo/css/cors-proxy
this.logger.trace(`_shouldRouteOverZiti: z-b-r/css/wasm/logo, bypassing intercept of [${request.url}]`);
result.routeOverZiti = false;
}
else {
// Don't muck with URL only because top-level domain of target matches the top-level domain of the load-balancer.
// Only do that if the entire hostname matches, or else sub-domains represented by different Services will be routed
// to the wrong place.
if (isEqual(newUrl.hostname, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host)) {
newUrl.hostname = this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.service;
newUrl.port = this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.port;
if (
isEqual(newUrl.port, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.port) ||
isEqual(newUrl.port, this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.loadbalancer.port)
) {
newUrl.port = '';
}
}
var pathnameArray = newUrl.pathname.split('/');
var targetpathnameArray = this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.path.split('/');
if (!isEqual(pathnameArray[1], targetpathnameArray[1])) {
newUrl.pathname = this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.path + newUrl.pathname;
newUrl.pathname = newUrl.pathname.replace('//','/');
}
this.logger.trace( '_shouldRouteOverZiti: transformed URL: ', newUrl.toString());
result.serviceName = await this._zitiContext.shouldRouteOverZiti( newUrl );
this.logger.trace(`_shouldRouteOverZiti result.serviceName[${result.serviceName}]`);
if (isUndefined(result.serviceName) || isEqual(result.serviceName, '')) { // If we have no config associated with the hostname:port, do not intercept
this.logger.warn(`_shouldRouteOverZiti: no associated Ziti config, bypassing intercept of [${request.url}]`);
setTimeout(this._sendServiceUnavailable, 250, this._zitiBrowzerServiceWorkerGlobalScope, newUrl);
} else {
result.routeOverZiti = true;
result.url = newUrl.toString();
result.serviceScheme = this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.scheme;
result.serviceConnectAppData = connectAppData;
}
}
}
// If no routing determination has been made yet
if (isUndefined(result.routeOverZiti)) {
result.serviceName = await this._zitiContext.shouldRouteOverZiti( url );
this.logger.trace(`_shouldRouteOverZiti result.serviceName[${result.serviceName}]`);
if (isUndefined(result.serviceName) || isEqual(result.serviceName, '')) { // If we have no config associated with the hostname:port, do not intercept
this.logger.warn(`_shouldRouteOverZiti: no associated Ziti config, bypassing intercept of [${request.url}]`);
result.routeOverZiti = false;
} else {
result.routeOverZiti = true;
result.url = url.toString();
result.serviceScheme = url.protocol;
let connectAppData = await this._zitiContext.getConnectAppDataByServiceName (result.serviceName, url.protocol);
result.serviceConnectAppData = connectAppData;
}
}
} catch (e) {
this.logger.error( e );
}
this.logger.trace(`_shouldRouteOverZiti result[${result.routeOverZiti}]`);
return result;
}
/**
* Determine if this request can used previously cached response, or be routed over Ziti/internet.
*
* @private
* @param {Request} request The request from the fetch event.
* @return {boolean} If request can used previously cached response
*/
_shouldUseCache(request: Request): boolean {
if (request.method !== 'GET') { // Only cache GET responses
this.logger.trace(`_shouldUseCache: handling ${request.method} method; NOT using cache`);
return false;
}
if (request.url.match( regexEdgeClt )) { // Never cache responses from Ziti Controller
this.logger.trace(`_shouldUseCache: handling request to Ziti Controller; NOT using cache`);
return false;
}
if (request.url.match( regexControllerAPI )) { // Never cache responses from Ziti Controller
this.logger.trace(`_shouldUseCache: handling request to Ziti Controller; NOT using cache`);
return false;
}
// We will allow the SW to cache teh ZBR/WASM files ...for the moment
//
// if ( (request.url.match( regexZBR )) || ((request.url.match( regexZBWASM ))) ) { // Do not cache the ZBR/WASM
// this.logger.trace(`_shouldUseCache: handling request for ZBR|WASM; NOT using cache`);
// return false;
// }
if (request.url.match( regexSlash ) ) { // Never cache responses for root path
this.logger.trace(`_shouldUseCache: handling request for '/'; NOT using cache`);
return false;
}
let url = new URL(request.url);
if ( url.pathname === '/' ) { // Do not cache the web app's root path
this.logger.trace(`_shouldUseCache: handling request for ROOT path; NOT using cache`);
return false;
}
let isRootPath = this._rootPaths.find((element: string) => element === `${url.pathname}`);
if ( isRootPath ) { // Do not cache the web app's root path
this.logger.trace(`_shouldUseCache: handling request for ROOT path; NOT using cache`);
return false;
}
if ( url.search !== '' ) { // Do not cache requests with search parms
this.logger.trace(`_shouldUseCache: handling request with search parms; NOT using cache`);
return false;
}
// Cache everything else
this.logger.trace(`_shouldUseCache: we WILL cache response for ${request.url}`);
return true;
}
_isRootPATH(request: Request): boolean {
if (request.url.match( regexSlash ) ) {
return true;
}
let url = new URL(request.url);
if ( url.pathname === '/' ) {
return true;
}
let isRootPath = this._rootPaths.find((element: string) => element === `${url.pathname}`);
if ( isRootPath ) {
return true;
}
return false;
}
/**
* @private
* @param {Request|string} request A request to run this strategy for.
* @param {workbox-strategies.StrategyHandler} handler The event that triggered the request.
* @return {Promise<Response>}
*/
async _handle(request: Request, handler: StrategyHandler): Promise<Response> {
let tryZiti: boolean | false;
this.logger.trace(`_handle entered for: [${request.url}]`);
const requestURL = new URL(request.url);
// If hitting the Controller, or seeking z-b-runtime|WASM, then
// we never go over Ziti, and we let the browser route the request
// to the Controller or browZer Bootstrapper.
if (
(request.url.match( regexControllerAPI )) || // " " "
(request.url.match( regexZBR )) || // seeking Ziti BrowZer Runtime
(request.url.match( regexZBRnaked )) || // seeking Ziti BrowZer Runtime
(request.url.match( regexZBRLogo )) || // seeking Ziti BrowZer Logo
(request.url.match( regexZBRCORS )) || // seeking Ziti BrowZer CORS proxy
(request.url.match( regexZBRcss )) || // seeking Ziti BrowZer CSS
(request.url.match( regexPolipop )) || // seeking Ziti Polipop
(request.url.match( regexCannySetup )) || // seeking Canny setup
(request.url.match( regexOAUTHTOKEN )) || // seeking IdP token
(request.url.match( regexFavicon )) || // seeking favicon
(request.url.match( regexZBWASM )) || // seeking Ziti BrowZer WASM
(request.url.match( regexJSDelivr )) // seeking CDN content
) {
tryZiti = false;
} else {
tryZiti = true;
}
if (this._isRootPATH(request)) {
const url = new URL(request.url)
const urlSearchParams = new URLSearchParams(url.search);
const codeParm = urlSearchParams.get('code');
const stateParm = urlSearchParams.get('state');
if (codeParm && stateParm) { // possible IdP-related URL
if (this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig && requestURL.hostname === this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.self.host) { // ..but if hitting the protected web app itself
tryZiti = true; // ..then let it go over Ziti
} else {
tryZiti = false; // ..otherwise, route over raw internet since it's IdP-related
}
}
}
if (tryZiti && this._zitiBrowzerServiceWorkerGlobalScope._zbrReloadPending) {
if (request.url.match( regexZBWASM )) { // the ZBR loads the WASM during init, so we need to process that request; all others wait
/* NOP */
}
else if (request.url.match( regexControllerAPI )) { // the ZBR hits the Ziti Controller during init, so we need to process that request; all others wait
/* NOP */
}
else {
await this.await_zbrInitialized(request).catch( async ( _err: any ) => {
this.logger.debug(`ZBR init not responding`);
await this._zitiBrowzerServiceWorkerGlobalScope._unregister();
throw new WorkboxError('no-response', {url: request.url});
});
}
}
if (tryZiti && (!this._isRootPATH(request)) && (!request.url.match( regexZBR ))) { // if NOT in the process of bootstrapping from HTTP Agent
if (isUndefined(this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig) ) { // ...and we don't yet have the zitiConfig from ZBR
if (!request.url.match( regexEdgeClt )) { // ...and NOT hitting the controller
let result: any = await this.await_zitiConfig(request.url, handler); // ...then wait for ZBR to send zitiConfig to us
if (result < 0) {
let redirectResponse = new Response('', { // If ZBR is AWOL, initiate top-level page reboot
status: 302,
statusText: 'Found',
headers: {
Location: '/'
}
}
);
return redirectResponse;
};
}
}
}
let self = this;
let skipInject = false;
let useCache = this._shouldUseCache(request);
if (useCache) {
let cachResponse = await handler.cacheMatch(request);
if (cachResponse) {
return cachResponse;
}
}
const promises: Promise<Response | undefined>[] = [];
let timeoutId: number | undefined;
let bootstrappingZBRFromSW: boolean | false;
let bootstrappingZBRFromSWConfigNeeded: boolean | false;
let response: Response | undefined;
let shouldRoute: ZitiShouldRouteResult = {routeOverZiti: false}
if (tryZiti) {
if (this._isRootPATH(request) ) { // seeking root path
bootstrappingZBRFromSW = true;
if (isUndefined(this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig) ) { // ...but we don't yet have the zitiConfig from ZBR
tryZiti = false; // ...then we're bootstrapping, so load ZBR from HTTP Agent
bootstrappingZBRFromSWConfigNeeded = true;
}
}
}
if ( tryZiti ) {
if (isUndefined(this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig)) {
let result: any = await this.await_zitiConfig(request.url, handler);
if (result < 0) {
let redirectResponse = new Response('', { // If ZBR is AWOL, initiate top-level page reboot
status: 302,
statusText: 'Found',
headers: {
Location: '/'
}
}
);
return redirectResponse;
};
}
// If going over Ziti, we must first complete the work to ensure WASM is instantiated, we have a cert, etc
await this.await_zitiConfig('null', handler); // wait for ZBR to send zitiConfig to us
await this._initialize();
this._targetServiceHost = await this._zitiContext.getConfigHostByServiceName (this._zitiBrowzerServiceWorkerGlobalScope._zitiConfig.browzer.bootstrapper.target.service);
// Now determine if we're going over Ziti or not
shouldRoute = await this._shouldRouteOverZiti(request);
}
if (this._zitiNetworkTimeoutSeconds) {
const {id, promise} = this._getZitiTimeoutPromise({request, handler});
timeoutId = id;
promises.push(promise);
}
let networkPromise;
let zitiNetworkPromise;
if (!shouldRoute.routeOverZiti) {
this.logger.trace(`_handle: ------- routing over raw internet ----------`);
networkPromise = this._getNetworkPromise({
timeoutId,
request,
handler,
useCache,
});
promises.push(networkPromise);
} else {
this.logger.trace(`_handle: ------- routing over Ziti ----------`);
zitiNetworkPromise = this._getZitiNetworkPromise({
timeoutId,
shouldRoute,
request,
handler,
useCache,
});
promises.push(zitiNetworkPromise);
}
response = await handler.waitUntil(
(async () => {
let netPromise = networkPromise || zitiNetworkPromise;
// Promise.race() will resolve as soon as the first promise resolves.
return (
(await handler.waitUntil(Promise.race(promises))) ||
// If Promise.race() resolved with null, it might be due to a network
// timeout + a cache miss. If that were to happen, we'd rather wait until
// the netPromise (which is either over Ziti or raw internet) resolves
// instead of returning null.
//
// Note that it's fine to await an already-resolved promise, so we don't
// have to check to see if it's still "in flight".
(await netPromise)
);
})(),
).catch(( err: any ) => {
this.logger.error(err);
return new Promise( async (_, reject) => {
reject( err );
});
});
if (!response) {
this.logger.error(`no-response when trying to reach URL [${request.url}]`);
await this._zitiBrowzerServiceWorkerGlobalScope._requestFailedWithNoResponse({
url: request.url
});
let errResponse = new Response('', {
status: 500,
statusText: 'ServerError',
}
);
return errResponse;
}
const location = response.headers.get('Location');
const contentType = response.headers.get('Content-Type');
if ( location && response.status >= 300 && response.status < 400 ) {
if (!this._rootPaths.find((element: string) => element === `${location}`)) {
this._rootPaths.push(location);
}
skipInject = true;
}
if ( response.status === 403 ) {
skipInject = true;
}
if (!contentType || !contentType.match( regexTextHtml )) {
skipInject = true;
}
if (contentType && contentType.match( regexTextHtml )) {
/**
* Jenkins thing