-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
1723 lines (1501 loc) · 73 KB
/
popup.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
// const {mockAccount} = import('./engine.js');
import {RULE_ENGINE} from './engine.js';
import {Sentry} from './sentry.js';
import {EXPLAINERS,ORG_EXPLAINERS} from './data-explainers.js';
let debug = false;
const api = "https://sentry.io/api/0/organizations/"
let url;
Sentry.init({
dsn: 'https://[email protected]/4505150139006976',
release: "[email protected]",
integrations: [
new Sentry.BrowserTracing({
// Set `tracePropagationTargets` to control for which URLs distributed tracing should be enabled
tracePropagationTargets: ["localhost", "api"],
})
],
autoSessionTracking: true,
tracesSampleRate: 1.0,
sendDefaultPii: true,
beforeSend(event, hint) {
event.request.url = event.tags['org slug']
return event;
}
});
function currentOrg(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
url = activeTab.url;
let org = ''
if (window.location.hash.includes('#window')) {
// org = window.location.hash.split('#window')[1];
org = document.getElementById('orgSlugName').value;
} else {
org = url.split('.sentry.io')[0].substring(8);
}
Sentry.setTag('org slug',org);
Sentry.setUser({ username: org });
start(org);
});
}
function openNewTab(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
url = activeTab.url;
const org = url.split('.sentry.io')[0].substring(8);
chrome.tabs.create({url: 'popup.html#window'+org});
});
}
function createDropRateTable(dataObject){
var tableDiv = document.createElement('div');
Sentry.addBreadcrumb({
category: "dataObject",
message: String(dataObject),
level: "info",
});
console.log(dataObject);
tableDiv.style.overflow = 'scroll';
var tbl = document.createElement('table');
tbl.setAttribute('id','dropRateRows');
tbl.style.border = '1px solid black';
const row = tbl.insertRow();
dataObject[0].forEach((cellValue) => {
const cell = row.insertCell();
var text = document.createTextNode(cellValue);
cell.appendChild(text);
cell.style.border = '1px solid black';
})
if(dataObject[1].length>0){
if(dataObject[1].length>1 || dataObject[1][0].constructor === Array){
dataObject[1].forEach((array) => {
const row = tbl.insertRow();
array.forEach((cellValue) =>{
const cell = row.insertCell();
var text = document.createTextNode(cellValue);
cell.appendChild(text);
cell.style.border = '1px solid black';
})
})
} else {
for (let index = 1; index < dataObject.length; index++) {
const element = dataObject[index];
const row = tbl.insertRow();
element.forEach((cellValue) =>{
const cell = row.insertCell();
var text = document.createTextNode(cellValue);
cell.appendChild(text);
cell.style.border = '1px solid black';
})
}
}
}
tableDiv.appendChild(tbl);
document.body.appendChild(tableDiv);
}
function createTable(dataObject,outboundArray,csvOutput){
console.log("table creation")
console.log(dataObject)
Sentry.addBreadcrumb({
category: "dataObject",
message: String(dataObject),
level: "info",
});
var tableDiv = document.createElement('div');
tableDiv.style.overflow = 'scroll';
// tableDiv.style.overflow = 'auto';
// 'overflow:scroll;height:80px;width:100%;overflow:auto'
var tbl = document.createElement('table');
tbl.setAttribute('id','auditResults');
tbl.style.border = '1px solid black';
outputRows[3].forEach( (cellValue) => {
const row = tbl.insertRow();
const firstCell = row.insertCell();
// var text = document.createTextNode(cellValue);
var text = document.createElement('abbr');
text.title = EXPLAINERS[cellValue];
text.textContent = cellValue;
firstCell.appendChild(text);
firstCell.style.border = '1px solid black';
dataObject['org']['projects'].forEach((project)=>{
let cell = row.insertCell()
text = document.createTextNode(project)
})
})
let i = 0;
dataObject['org']['projects'].forEach( (project) => {
console.log(project)
for(let key in project){
console.log(key)
let cell = tbl.rows[i].insertCell();
var text = document.createTextNode(project[key]);
cell.appendChild(text);
cell.style.border = '1px solid black';
switch(project[key]) {
case goodThresholds[i]:
cell.style.backgroundColor = 'green';break;
default:
if (key == 'sdkUpdates') { cell.style.backgroundColor = 'red';break; }
if (goodThresholds[i] == 'Any' || goodThresholds[i] == 0) {
cell.style.backgroundColor = 'green';break;
} else if (goodThresholds[i].constructor != null && goodThresholds[i].constructor === Array) {
if(project[key] > goodThresholds[i][1]) {
cell.style.backgroundColor = 'green';break;
} else if (project[key] > goodThresholds[i][0]) {
cell.style.backgroundColor = 'yellow';break;
}
}
cell.style.backgroundColor = 'red';break;
}
i += 1;
}
i = 0;
})
// let row = tbl.insertRow();
// let firstCell = row.insertCell();
// var text = document.createTextNode('Outcomes');
// firstCell.appendChild(text);
// firstCell.style.border = '1px solid black';
// console.log(outboundArray);
// outboundArray.forEach( (project) => {
// project[1].sort((first, second) => { return first['priority'] - second['priority'] });
// let outcomeCell = row.insertCell();
// let aggProjOutcomes = ''
// project[1].forEach( (outbound) => {
// aggProjOutcomes.concat(" ",outbound['body']," Priority: ",outbound['priority'],".")
// })
// text = document.createTextNode(aggProjOutcomes);
// outcomeCell.appendChild(text);
// })
// let cell = tbl.rows[i].insertCell();
// var text = document.createTextNode(project[key]);
// cell.appendChild(text);
// cell.style.border = '1px solid black';
// i += 1;
i = 0;
tableDiv.appendChild(tbl);
document.body.appendChild(tableDiv);
var orgStatsDiv = document.createElement('div');
orgStatsDiv.style.overflow = 'scroll';
// tableDiv.style.overflow = 'auto';
// 'overflow:scroll;height:80px;width:100%;overflow:auto'
var orgStatsTable = document.createElement('table');
orgStatsTable.setAttribute('id','auditResults');
orgStatsTable.style.border = '1px solid black';
const orgStats = csvOutput.slice(0,2);
orgStats.forEach((array) => {
var row = orgStatsTable.insertRow();
array.forEach((cellValue)=> {
const cell = row.insertCell();
if(cellValue in ORG_EXPLAINERS){
var text = document.createElement('abbr');
text.title = ORG_EXPLAINERS[cellValue];
text.textContent = cellValue;
}
else {
var text = document.createTextNode(cellValue);
}
cell.appendChild(text);
if(cellValue == 'false' || cellValue == '0'){
cell.style.backgroundColor = 'red';
}
cell.style.border = '1px solid black';
})
})
orgStatsDiv.appendChild(orgStatsTable);
document.body.appendChild(orgStatsDiv);
}
// .NET / Flutter additions
const mobileSdks = ['sentry.java.android','sentry.cocoa','sentry.javascript.react-native','android','ios'];
const frontEndSdks = ['sentry.javascript','javascript','react','sentry.javascript.react'];
const backEndSdks = ['sentry.java','java','node','sentry.javascript.nodejs','nodejs','rails','ruby','express','sentry.javascript.express'];
const ingestionCategoryDict = ['sessions','profile','transaction_indexed','attachment','replay','error','transaction'];
let orgSubscriptionApi = `https://sentry.io/api/0/subscriptions/{org}/`
let orgSubscriptionHistoryApi = 'https://{org}.sentry.io/api/0/customers/{org}/history/'
let orgStatsApi = 'https://sentry.io/api/0/organizations/{org}/stats_v2/?field=sum%28quantity%29&groupBy=category&groupBy=outcome&interval=1h&project=-1&statsPeriod=14d'
let projectStatsApi = 'https://sentry.io/api/0/organizations/{org}/stats_v2/?field=sum%28quantity%29&groupBy=outcome&groupBy=project&groupBy=category&interval=1h&project=-1&statsPeriod=14d'
let projectsApi = 'https://sentry.io/api/0/organizations/{org}/projects/'
let projectSdkApi = 'https://sentry.io/api/0/organizations/{org}/events/?field=project&field=sdk.name&field=sdk.version&field=count%28%29&per_page=100&project=-1&sort=-count&statsPeriod=14d'
let teamDict = {};
let projects = [];
let projectObjects = [];
let orgObject;
let aggregateProjects = {};
let orgStats = [];
let projectSdkStats = [];
let projectStats = [];
let mobileUseCase = false;
let topProjects = [];
let mobileProjects = [];
let orgWideStats = [];
let frontendUseCase = false;
let backendUseCase = false;
let nativeUseCase = false;
let allProjectAudits = [];
// Indexes - 0:Blank 1:Org Stats, 2:Blank, 3:Org Stats Headers, 4:Org Stats populated, 5:Blank, 6:Blank 7:Project Stats Headers
// Org Stats to be populated (outputRows[1][index]) Index:
// 0:Org Name, 1:SCIM, 2:SSO, Integrations 3:Messaging 4:SCM 5:Issue Tracking, 6:Projects created recently, 7:Members added, 8:Teams used recently,
// 9:Project Settings edited
class Organization {
constructor(name,scimUsage=false,ssoUsage=false,messagingIntegration=false,scmIntegration=false,issueIntegration=false,
projectCreated=false,memberInvited=false,teamUsed=false,projSettings=false)
{
this.name = name;
this.scimUsage = scimUsage;
this.ssoUsage = ssoUsage;
this.messagingIntegration = messagingIntegration;
this.scmIntegration = scmIntegration;
this.issueIntegration = issueIntegration;
this.projectCreated = projectCreated;
this.memberInvited = memberInvited;
this.teamUsed = teamUsed;
this.projSettings = projSettings;
}
get usesScim(){
return this.scimUsage;
}
set usesScim(scim){
this.scimUsage = scim;
}
get usesSso(){
return this.ssoUsage;
}
set usesSso(sso){
this.ssoUsage = sso;
}
get messageIntegration(){
return this.messagingIntegration;
}
set messageIntegration(integration){
this.messagingIntegration = integration;
}
get usesScm(){
return this.scmIntegration;
}
set usesScm(scm){
this.scmIntegration = scm;
}
get usesIssueInt(){
return this.issueIntegration;
}
set usesIssueInt(issue){
this.issueIntegration = issue;
}
get createdProjects(){
return this.projectCreated;
}
set createdProjects(projects){
this.projectCreated = projects;
}
get invitedMembers(){
return this.memberInvited;
}
set invitedMembers(invited){
this.memberInvited = invited;
}
get useTeams(){
return this.teamUsed;
}
set useTeams(team){
this.teamUsed = team;
}
get editProjects(){
return this.projSettings;
}
set editProjects(project){
this.projSettings = project;
}
}
class Project {
constructor(name,id,usesEnvironments,platforms,hasMinifiedStackTrace,sdkUpdates,useResolveWorkflow,assignmentPercentage,ownershipRules,usingSessions,
usingReleases,usingAttachments,usingProfiling,messagingIntegration,usingPerformance,alertsSet,metricAlerts,crashFreeAlerts,linksIssues,usesAllErrorTypes,isMobile=false,httpIsInstrumented=true,
dbIsInstrumented=true,uiIsInstrumented=true,routerIsInstrumented = true,usingSessionReplay=true){
this.name = name;
this.id = id;
this.usesEnvironments = usesEnvironments;
this.platforms = platforms;
this.hasMinifiedStackTrace = hasMinifiedStackTrace;
this.sdkUpdates = sdkUpdates;
this.useResolveWorkflow = useResolveWorkflow;
this.assignmentPercentage = assignmentPercentage;
this.ownershipRules = ownershipRules
this.usingSessions = usingSessions;
this.usingReleases = usingReleases;
this.usingPerformance = usingPerformance;
this.usingAttachments = usingAttachments;
this.usingProfiling = usingProfiling;
this.alertsSet = alertsSet;
this.metricAlerts = metricAlerts;
this.crashFreeAlerts = crashFreeAlerts;
this.messagingIntegration = messagingIntegration;
this.isMobile = isMobile;
this.linksIssues = linksIssues;
this.usesAllErrorTypes = usesAllErrorTypes;
this.httpIsInstrumented = httpIsInstrumented;
this.dbIsInstrumented = dbIsInstrumented;
this.uiIsInstrumented = uiIsInstrumented;
this.routerIsInstrumented = routerIsInstrumented;
this.usingSessionReplay = usingSessionReplay;
// this.isMobile = false;
}
get projectName(){
return this.name;
}
get projectId(){
return this.id;
}
get projectEnvironments(){
return this.usesEnvironments;
}
set projectEnvironments(x){
this.usesEnvironments = x;
}
get projectStackTraces(){
return this.hasMinifiedStackTrace
}
get messageIntegration(){
return this.messagingIntegration;
}
set messageIntegration(integration){
this.messagingIntegration = integration;
}
set projectStackTraces(x){
this.hasMinifiedStackTrace = x;
}
get projectUpdates(){
return this.sdkUpdates;
}
set projectUpdates(x){
this.sdkUpdates = x;
}
get projectWorkflow(){
return this.useResolveWorkflow;
}
set projectWorkflow(x){
this.useResolveWorkflow = x;
}
get projectAssignment(){
return this.assignmentPercentage;
}
set projectAssignment(x){
this.assignmentPercentage = x;
}
get projectOwnership(){
return this.ownershipRules;
}
set projectOwnership(x){
this.ownershipRules = x;
}
get projectSessions(){
return this.usingSessions;
}
set projectSessions(x){
this.usingSessions = x;
}
get projectReleases(){
return this.usingReleases;
}
set projectReleases(x){
this.usingReleases = x;
}
get projectPerformance(){
return this.usingPerformance
}
set projectPerformance(x){
this.usingPerformance = x;
}
get projectAttachments(){
return this.usingAttachments;
}
set projectAttachments(x){
this.usingAttachments = x;
}
get projectProfiling(){
return this.usingProfiling;
}
set projectProfiling(x){
this.usingProfiling = x;
}
get projectUsesAllErrorTypes(){
return this.usesAllErrorTypes;
}
set projectUsesAllErrorTypes(x){
return this.usesAllErrorTypes;
}
get projectAlerts(){
return this.alertsSet;
}
set projectAlerts(x){
this.alertsSet = x;
}
get projectMetricAlerts(){
return this.metricAlerts;
}
set projectMetricAlerts(x){
this.metricAlerts = x;
}
get projectCrashFreeAlerts(){
return this.crashFreeAlerts;
}
set projectCrashFreeAlerts(x){
this.crashFreeAlerts = x;
}
get projectPlatforms(){
return this.platforms;
}
set projectPlatforms(x){
this.platforms = x;
}
get projectIsMobile(){
return this.isMobile;
}
set projectIsMobile(x){
this.isMobile = x;
}
get projectInstrumentedHTTP(){
this.httpIsInstrumented;
}
set projectInstrumentedHTTP(x){
this.httpIsInstrumented = x;
}
get projectInstrumentedUI(){
this.uiIsInstrumented;
}
set projectInstrumentedUI(x){
this.uiIsInstrumented = x;
}
get projectInstrumentedDB(){
this.dbIsInstrumented;
}
set projectInstrumentedDB(x){
this.dbIsInstrumented = x;
}
// this.usesAllErrorTypes = usesAllErrorTypes;
// this.httpIsInstrumented = httpIsInstrumented;
// this.dbIsInstrumented = dbIsInstrumented;
// this.uiIsInstrumented = uiIsInstrumented;
}
// let projectData = {
// 'projectName':projectName,'projectId':projectId,'environments':projEnvironmentCount>1,'hasDesymFiles':hasDesymbolicationFiles,
// 'upgradeSdk':sdktoUpgrade,'useAllErrorTypes':iosMechanismsUsed || androidMechanismsUsed,'useResolveWorkflow':useResolveWorkflow,'assignments':assignmentPercentage,'ownershipRules':ownershipRulesSet,
// 'sessions':usingSessions,'releases':usingReleases,'attachments':usingAttachments,'profiles':usingProfiling,'performance':usingPerformance,
// 'alerts':projectAlerts.length>0,'metricAlerts':metricAlerts.length>0,"Crash Free Alerts":crashFreeAlerts
// };
// // this.name = name;
// this.id = id;
// this.usesEnvironments = usesEnvironments;
// this.hasMinifiedStackTrace = hasMinifiedStackTrace;
// this.sdkUpdates = sdkUpdates;
// this.useResolveWorkflow = useResolveWorkflow;
// this.assignmentPercentage = assignmentPercentage;
// this.ownershipRules = ownershipRules
// this.usingSessions = usingSessions;
// this.usingReleases = usingReleases;
// this.usingPerformance = usingPerformance;
// this.usingAttachments = usingAttachments;
// this.usingProfiling = usingProfiling;
// this.alertsSet = alertsSet;
// this.metricAlerts = metricAlerts;
// this.crashFreeAlerts = crashFreeAlerts;
// this.messagingIntegration = messagingIntegration;
// this.isMobile = isMobile;
// this.linksIssues = linksIssues;
// this.platforms = platforms;
// this.usesAllErrorTypes = usesAllErrorTypes;
// this.httpIsInstrumented = httpIsInstrumented;
// this.dbIsInstrumented = dbIsInstrumented;
// this.uiIsInstrumented = uiIsInstrumented;
let outputRowToProperty = ['name','id','usesEnvironments','hasMinifiedStackTrace','sdkUpdates','usesAllErrorTypes','useResolveWorkflow','assignmentPercentage','ownershipRules','usingSessions',
'usingReleases','usingAttachments','usingProfiling','usingPerformance','alertsSet','metricAlerts','crashFreeAlerts','platforms','messagingIntegration','dbIsInstrumented','uiIsInstrumented','httpIsInstrumented']
let outputRows = [
[
'Organization Name', 'Using SCIM', 'Using SSO', 'Using Messaging Integration', 'Using SCM Integration', 'Using Issue Tracking Integration',
'Projects Created Recently', 'Members Invited Recently', 'Teams have been used recently (Either created or joined)', 'Project Settings edited recently', 'Renewal in next 6 months',
'Average Error Quota Usage over the past 6 months', 'Average Txn Quota Usage over the past 6 months', 'Average Attachment Quota Usage over the past 6 months'
],[],[],[
'Project Name','Project Id','Project Uses Environments?','Project Platform', 'Project has minified Stacktraces?', 'Sdk version to upgrade', 'Issue Workflow is used? (Issues get Resolved)',
'% Of issues that are assigned', 'Ownership Rules are set', 'Sessions are being sent?', 'Releases are being created?', 'Performance is used in this project?', 'Attachments are being sent?',
'Profiles are being used?', 'Project has alerts set up?', 'Project has metric alerts set up?', 'Project has a CFSR Alert?','Project has an alert which utilises a messaging integration', 'Project is Mobile',
'Project links issues', 'Uses all Error Types', 'HTTP Spans Instrumented','DB Spans Instrumented (perf issues)', 'UI Spans Instrumented', 'Router Instrumented?', 'Using Session Replay?'
]
]
let goodThresholds = [
0, // Name
0, // id
true, // usesEnvironments
'Any', // platforms
false, // hasMinifiedStackTrace
null, // sdkUpdates
true, // useResolveWorkflow
[5,45], // assignmentPercentage
true, // ownershipRules
true, // usingSessions
true, // usingReleases
true, // usingPerformance
true, // usingAttachments
true, // usingProfiling
true, // alertsSet
true, // metricAlerts
true, // crashFreeAlerts
true, // messagingIntegration
'Any', // isMobile
true, // linksIssues
true, // usesAllErrorTypes
true, // httpIsInstrumented
true, // dbIsInstrumented
true, // uiIsInstrumented
true, // routerIsInstrumented
true, // usingSessionReplay
]
let dropRateDataRows = [
['Project Name/Org', 'Event Type', 'Percentage Dropped', 'Dropped Events', 'Filtered Events %', 'Accepted Events']
]
let sourceControlDict = ['github','bitbucket','gitlab'];
let messagingDict = ['slack','ms-teams','teams'];
let issueTrackingDict = ['JIRA','jira','azure'];
let checkNonMobile = true;
// UI Creation
let displayAsTab = false;
if (window.location.hash.includes('#window')) {
displayAsTab = true;
// Create a textbox to enter Org Slug
document.getElementById('enterOrgSlug').hidden = false;
document.getElementById('orgSlugName').value = window.location.hash.split('#window')[1];
}
let startingDiv = document.createElement('div')
startingDiv.id = 'startingDiv';
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "MobileProjectCheck";
checkbox.value = false;
checkbox.id = "MobileProjectCheck";
var label = document.createElement('label');
label.htmlFor = "MobileProjectCheck";
label.appendChild(document.createTextNode('Tick for mobile only audit.'));
let newTabButton = document.createElement("BUTTON");
let newTabLabel = document.createTextNode("Click to open in new tab.");
let startButton = document.createElement("BUTTON");
let startLabel = document.createTextNode("Click me to run audit.");
startButton.appendChild(startLabel);
newTabButton.appendChild(newTabLabel);
startButton.onclick = currentOrg;
newTabButton.onclick = openNewTab;
startingDiv.appendChild(checkbox);
startingDiv.appendChild(label);
startingDiv.appendChild(startButton);
if(!displayAsTab) {
startingDiv.appendChild(newTabButton);
}
document.body.appendChild(startingDiv);
async function start(org){
// wb.SheetNames.push(`${org} Stats`)
outputRows[1][0] = org;
orgObject = new Organization(org);
if(document.getElementById("MobileProjectCheck").checked) {
checkNonMobile = false;
}
document.getElementById('startingDiv').remove()
try { // Using an ugly catch-all try-catch statement here because window.onerror appears to be faulty in chrome extensions
// See https://bugs.chromium.org/p/chromium/issues/detail?id=457785
var transaction = Sentry.startTransaction({ name: "checkIntegrations" });
checkIntegrations(org);
transaction.finish();
transaction = Sentry.startTransaction({ name: "checkAuth" });
checkAuth(org);
transaction.finish();
transaction = Sentry.startTransaction({ name: "checkAudit" });
checkAudit(org);
transaction.finish();
orgSubscriptionApi = orgSubscriptionApi.replace('{org}',org);
transaction = Sentry.startTransaction({ name: "checkOrgStats" });
await checkOrgStats(org);
transaction.finish();
console.log(orgObject);
let orgIsTeamsPlan = await fetch(orgSubscriptionApi).then((r)=> r.json()).then((result => {return result}));
console.log(orgIsTeamsPlan);
orgIsTeamsPlan = orgIsTeamsPlan['plan'].includes('team');
transaction = Sentry.startTransaction({ name: "checkProjectStats" });
await checkProjectStats(org,orgIsTeamsPlan);
transaction.finish();
transaction = Sentry.startTransaction({ name: "checkMobileUseCase" });
await checkMobileUseCase(org);
transaction.finish();
dropRateDataRows.forEach( element => {
if(Array.isArray(element[0])) {
element.forEach( el => {
outputRows.push(el)
})
} else {
outputRows.push(element)
}
})
// org:{ project [{},{}]
console.log(allProjectAudits)
let projectsArray = []
allProjectAudits.forEach( project => {
let projObject = new Project(project['projectName']);
projObject.id = project['projectId'];
projObject.alertsSet = project['alerts'];
projObject.assignmentPercentage = project['assignments'];
projObject.crashFreeAlerts = project['Crash Free Alerts'];
projObject.hasMinifiedStackTrace = project['hasDesymFiles'];
projObject.metricAlerts = project['metricAlerts'];
projObject.ownershipRules = project['ownershipRules'];
projObject.sdkUpdates = project['upgradeSdk'];
projObject.useResolveWorkflow = project['useResolveWorkflow'];
projObject.usesEnvironments = project['environments'];
projObject.usingPerformance = project['performance'];
projObject.usingProfiling = project['profiles'];
projObject.usingReleases = project['releases'];
projObject.usesAllErrorTypes = project['useAllErrorTypes'];
projObject.usingSessions = project['sessions'];
projObject.platforms = project['Platform'];
projObject.usingSessionReplay = project['usingSessionReplay'];
projObject.messagingIntegration = project['slackAlert']
if (project['useAllErrorTypes'] != 'null') {
projObject.projectIsMobile = true;
projObject.httpIsInstrumented = project['httpSpansInstrumented']
projObject.dbIsInstrumented = project['dbSpansInstrumented']
projObject.uiIsInstrumented = project['uiSpansInstrumented']
}
// projObject.httpClientErrors = project['httpErrors'];
projObject.routerIsInstrumented = project['routerInstrumentation'];
projObject.linksIssues = project['linksIssues']
if(projectsArray.filter( function (element) { return element.name == projObject.name }).length<1){
projectsArray.push(projObject);
}
})
orgObject.projects = projectsArray;
console.log(orgObject);
let objForEval = {org: orgObject}
console.log(objForEval);
let o = await RULE_ENGINE.generateOutboundForAccount(objForEval);
console.log(o)
outputRows.push([])
outputRows.push(['Project Name','Outbound Message','Priority'])
var outboundArray = Object.keys(o).map(
(key) => { return [key, o[key]] });
var transaction = Sentry.startTransaction({ name: "createTable" });
createTable(objForEval,outboundArray,outputRows);
transaction.finish()
await checkKeyMembers(org);
outboundArray.forEach( (project) => {
project[1].sort((first, second) => { return first['priority'] - second['priority'] });
project[1] = Array.from(new Set(project[1]))
project[1].forEach( (outbound) => {
outputRows.push([project[0],'"'+outbound['body']+'"',outbound['priority']*1])
})
})
console.log(outputRows)
console.log(outboundArray)
if( dropRateDataRows.length > 1) {
var transaction = Sentry.startTransaction({ name: "createDropRateTable" });
createDropRateTable(dropRateDataRows);
transaction.finish();
}
let csvContent = "data:text/csv;charset=utf-8," + outputRows.map(e => e.join(",")).join("\n");
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", `${org}_audit.csv`);
link.innerText = "Download as CSV";
document.body.appendChild(link);
} catch (error) {
console.log(error)
Sentry.captureException(error);
alert('Audit failed due to an inability to query the API. Please refresh the Sentry page for '+org+ ', authenticate as super user, and try again.');
alert('Please also send a message to #proj-se-audit-automation with the org you were attempting to audit if this does not work.');
if(!debug){
location.reload();
}
}
// console.log('projects without Crash Free Alerts')
// console.log(allProjectAudits.filter(function (element) { return element['Crash Free Alerts'] == false }))
// console.log('projects not using assignments')
// console.log(allProjectAudits.filter(function (element) { return element['assignments'] == 0 }))
// console.log('projects with minified stack traces')
// console.log(allProjectAudits.filter(function (element) { return element['hasDesymFiles'] == false }))
// console.log('projects using performance')
// console.log(allProjectAudits.filter(function (element) { return element['performance'] == true }))
// console.log('projects using profiling')
// console.log(allProjectAudits.filter(function (element) { return element['profiles'] == true }))
// var wbout = XLSX.write(wb, {bookType:'xlsx', type: 'binary'});
// var buf = new ArrayBuffer(wbout.length); //convert s to arrayBuffer
// var view = new Uint8Array(buf); //create uint8array as viewer
// for (var i=0; i<wbout.length; i++) view[i] = wbout.charCodeAt(i) & 0xFF; //convert to octet
// var encodedUri = encodeURI(wbout);
// var link = document.createElement("a");
}
async function checkAuth(org){
let authApi = `https://sentry.io/api/0/organizations/${org}/auth-provider/`;
let authUsage = await fetch(authApi).then((r)=> {if (r.status != '204') {return r.json()} else { return r.status}}).then((result => {return result}));
// console.log(authUsage)
if (authUsage == '204') {
// console.log("no SSO enabled altogether (no SCIM no SSO)");
outputRows[1][1] = 'No.'
outputRows[1][2] = 'No.'
}
else {
outputRows[1][2] = authUsage['require_link'];
orgObject.usesSso = authUsage['require_link'];
outputRows[1][1] = authUsage['scim_enabled'];
orgObject.usesScim = authUsage['scim_enabled'];
// console.log("SSO enabled: "+authUsage['require_link']);
// console.log("SCIM enabled: "+authUsage['scim_enabled']);
}
}
async function checkAudit(org){
let auditApi = `https://sentry.io/api/0/organizations/${org}/audit-logs/`
let auditLog = await fetch(auditApi).then((r)=> r.json()).then((result => {return result}));
let oneMonthAgo = new Date( (new Date().getTime() - (1000 * 60 * 60 * 24 * 30)) )
let recentAudit = auditLog['rows'].filter( function(element) { return new Date(element['dateCreated']).getTime() > oneMonthAgo } )
let projectsCreatedRecently = recentAudit.filter( function(element) { return element['event'] == 'project.create' })
let memberInvitedrecently = recentAudit.filter( function(element) { return element['event'] == 'member.invite' })
let memberTeamActivity = recentAudit.filter( function(element) { return element['event'] == 'member.join-team' || element['event'] == 'team.create' || element['event'] == 'member.accept-invite' })
let projectActivity = recentAudit.filter( function(element) { return element['event'] == 'project.edit' || element['event'] == 'projectkey.create' })
let auditUsage = {'projectsCreatedRecently':projectsCreatedRecently.length,'membersInvitedRecently':memberInvitedrecently.length,'memberTeamActivity':memberTeamActivity.length,'projectActivity':projectActivity.length}
outputRows[1][6] = auditUsage['projectsCreatedRecently'];
outputRows[1][7] = auditUsage['membersInvitedRecently'];
outputRows[1][8] = auditUsage['memberTeamActivity'];
outputRows[1][9] = auditUsage['projectActivity'];
orgObject.createdProjects = auditUsage['projectsCreatedRecently'];
orgObject.invitedMembers = auditUsage['membersInvitedRecently'];
orgObject.useTeams = auditUsage['memberTeamActivity'];
orgObject.editProjects = auditUsage['projectActivity'];
}
function aggregateStats(apiResult) {
// Not including 'rejected' outcome here since it's not immediately actionable by customer, usually it's a negligble amount caused due to network error or intermittent problems.
// let ingestionRejectionDict = ['client_discard','rate_limited']
let ingestionRejectionDict = ['rate_limited']
let ingestionFilteredDict = ['filtered']
let ingestionAcceptedDict = ['accepted']
let acceptedStats = {}
let acceptedEvents = []
let rejectedEvents = []
let filteredEvents = []
let rejectedStats = {}
let filteredStats = {}
let alarmingDropRate = []
// Org stats is passed in with 'groups'
if ('groups' in apiResult) {
rejectedEvents = apiResult.groups.filter( function (element) {
return ingestionRejectionDict.includes(element['by']['outcome'])
});
filteredEvents = apiResult.groups.filter( function (element) {
return ingestionFilteredDict.includes(element['by']['outcome'])
});
acceptedEvents = apiResult.groups.filter( function (element) {
return ingestionAcceptedDict.includes(element['by']['outcome'])
});
} else {
rejectedEvents = apiResult.filter( function (element) {
return ingestionRejectionDict.includes(element['by']['outcome'])
});
filteredEvents = apiResult.filter( function (element) {
return ingestionFilteredDict.includes(element['by']['outcome'])
})
acceptedEvents = apiResult.filter( function (element) {
return ingestionAcceptedDict.includes(element['by']['outcome'])
});
}
// Aggregate total rejection and acceptance stats by type of event
ingestionCategoryDict.forEach(element => {
let rejectsForCategory = rejectedEvents.filter( function (el) {
return element == el['by']['category'];
})
rejectsForCategory.forEach(el => {
rejectedStats[element] = el['totals']['sum(quantity)']
})
let acceptsForCategory = acceptedEvents.filter( function (el) {
return element == el['by']['category'];
})
acceptsForCategory.forEach(el => {
acceptedStats[element] = el['totals']['sum(quantity)']
})
let filtersForCategory = filteredEvents.filter( function (el) {
return element == el['by']['category'];
})
filtersForCategory.forEach(el => {
filteredStats[element] = el['totals']['sum(quantity)']
})
if ((element in rejectedStats && element in acceptedStats) || (element in filteredStats)){
if ((acceptedStats[element] / 3 < rejectedStats[element]) || (acceptedStats[element] / 3 < filteredStats[element])) {
alarmingDropRate.push(element);
}
}
// else if (element in rejectedStats && !(element in acceptedStats)) {
// alarmingDropRate.push(element);
// }
})
return [alarmingDropRate,acceptedStats,rejectedStats,filteredStats]
}
async function checkOrgStats(org){
orgSubscriptionApi = orgSubscriptionApi.replace('{org}',org);
orgSubscriptionHistoryApi = orgSubscriptionHistoryApi.replace('{org}',org);
orgStatsApi = orgStatsApi.replace('{org}',org);
let orgSubscription = await fetch(orgSubscriptionApi).then((r)=> r.json()).then((result => {return result}));
let orgHistory = await fetch(orgSubscriptionHistoryApi).then((r)=>r.json()).then((result=>{return result}));
let renewalDate = new Date(orgSubscription['renewalDate']).getTime()
let renewalSoon = ( ( renewalDate - new Date().getTime() ) / (1000*60*60*24) ) < 180 // Check if renewal is within 6 months
outputRows[1][10] = renewalSoon;
let errorQuotaUsage = 0;
let txnsQuotaUsage = 0;
let attachmentQuotaUsage = 0;
for(var i=0; i < 6; i++) {
if (orgHistory[i]){
errorQuotaUsage += orgHistory[i]['categories']['errors']['usage'] / orgHistory[i]['categories']['errors']['reserved']
if (orgHistory[i]['categories']['transactions']){
txnsQuotaUsage += orgHistory[i]['categories']['transactions']['usage'] / orgHistory[i]['categories']['transactions']['reserved']
}
if (orgHistory[i]['categories']['attachments']){
attachmentQuotaUsage += orgHistory[i]['categories']['attachments']['usage'] / orgHistory[i]['categories']['attachments']['reserved']
}
}
}