-
Notifications
You must be signed in to change notification settings - Fork 6k
Expand file tree
/
Copy pathgithubServer.js
More file actions
952 lines (819 loc) · 57.8 KB
/
Copy pathgithubServer.js
File metadata and controls
952 lines (819 loc) · 57.8 KB
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
exports.newGithubServer = function newGithubServer() {
let thisObject = {
getGithubStars: getGithubStars,
getGithubWatchers: getGithubWatchers,
getGithubForks: getGithubForks,
createGithubFork: createGithubFork,
mergePullRequests: mergePullRequests,
initialize: initialize,
finalize: finalize,
run: run
}
const GITHUB_API_WAITING_TIME = 250
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
}
async function getGithubStars(repository, username, token) {
return await getGithubUsernames('activity', 'listStargazersForRepo', repository, username, token)
}
async function getGithubWatchers(repository, username, token) {
return await getGithubUsernames('activity', 'listWatchersForRepo', repository, username, token)
}
async function getGithubForks(repository, username, token) {
return await getGithubUsernames('repos', 'listForks', repository, username, token)
}
async function mergePullRequests(commitMessage, username, token) {
return await mergeGithubPullRequests(commitMessage, username, token)
}
async function getGithubUsernames(endpoint, method, repository, username, token) {
try {
repository = unescape(repository)
username = unescape(username)
token = unescape(token)
let error
let githubListArray = []
return await getRepoInfo()
async function getRepoInfo() {
await doGithub()
if (error !== undefined) {
let docs = {
project: 'Governance',
category: 'Topic',
type: 'Gov Error - Get Repository Information',
anchor: undefined,
placeholder: {}
}
return respondWithDocsObject(docs, error)
}
return {
result: global.DEFAULT_OK_RESPONSE.result,
githubListArray: githubListArray
}
}
async function doGithub() {
const { Octokit } = SA.nodeModules.octokit
const octokit = new Octokit({
auth: token,
userAgent: 'Superalgos ' + SA.version
})
await getList()
async function getList() {
const repo = repository
const owner = 'Superalgos'
const per_page = 100 // Max
let page = 0
let lastPage = false
while (lastPage === false) {
try {
page++
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
let listResponse = await octokit[endpoint][method]({
owner,
repo,
per_page,
page
});
if (listResponse.data.length < 100) {
lastPage = true
}
for (let i = 0; i < listResponse.data.length; i++) {
let listItem = listResponse.data[i]
let githubUsername
switch (endpoint) {
case 'activity':
{
githubUsername = listItem.login
break
}
case 'repos':
{
githubUsername = listItem.owner.login
break
}
}
//SA.logger.info(listItem)
githubListArray.push(githubUsername)
}
// SA.logger.info('Github Server -> getRepoInfo -> doGithub -> getList -> ' + method + ' Page = ' + page)
// SA.logger.info('Github Server -> getRepoInfo -> doGithub -> getList -> ' + method + ' Received = ' + listResponse.data.length)
} catch (err) {
SA.logger.error(err)
if (err.stack.indexOf('last page') >= 0) {
return
} else {
SA.logger.error('Github Server -> getRepoInfo -> doGithub -> getList ->Method call produced an error.')
SA.logger.error('Github Server -> getRepoInfo -> doGithub -> getList ->err.stack = ' + err.stack)
SA.logger.error('Github Server -> getRepoInfo -> doGithub -> getList ->repository = ' + repository)
SA.logger.error('Github Server -> getRepoInfo -> doGithub -> getList ->username = ' + username)
SA.logger.error('Github Server -> getRepoInfo -> doGithub -> getList ->token starts with = ' + token.substring(0, 10) + '...')
SA.logger.error('Github Server -> getRepoInfo -> doGithub -> getList ->token ends with = ' + '...' + token.substring(token.length - 10))
error = err
return
}
}
}
}
}
} catch (err) {
SA.logger.error('Github Server -> getRepoInfo -> Method call produced an error.')
SA.logger.error('Github Server -> getRepoInfo -> err.stack = ' + err.stack)
SA.logger.error('Github Server -> getRepoInfo -> repository = ' + repository)
SA.logger.error('Github Server -> getRepoInfo -> username = ' + username)
SA.logger.error('Github Server -> getRepoInfo -> token starts with = ' + token.substring(0, 10) + '...')
SA.logger.error('Github Server -> getRepoInfo -> token ends with = ' + '...' + token.substring(token.length - 10))
let error = {
result: 'Fail Because',
message: err.message,
stack: err.stack
}
return error
}
}
async function createGithubFork(username, token, repo = 'Superalgos') {
try {
token = unescape(token)
username = unescape(username)
await doGithub()
await Promise.all(Object.values(global.env.PROJECT_PLUGIN_MAP).map(v => {
return doGithub(v.repo)
}))
async function doGithub(repo = 'Superalgos') {
try {
let Octokit
if (SA && SA.nodeModules && SA.nodeModules.octokit) Octokit = SA.nodeModules.octokit.Octokit
else Octokit = require('@octokit/rest').Octokit
const octokit = new Octokit({
auth: token,
userAgent: 'Superalgos ' + SA.version
})
// check if repo already exists
octokit.repos.get({
owner: username,
repo: repo,
}).catch(async err => {
SA.logger.error('Github Server -> createGithubFork -> doGithub -> err.stack = ' + err.stack)
SA.logger.warn('Github Server -> createGithubFork -> doGithub -> forking new submodule: ' + repo)
// fork it since it doesn't seem to exist, but the user has presumably already forked main repo
await octokit.repos.createFork({
owner: 'Superalgos',
repo: repo
})
})
} catch (err) {
if (err === undefined) { return }
SA.logger.error('Github Server -> createGithubFork -> doGithub -> err.stack = ' + err.stack)
}
}
} catch (err) {
SA.logger.error('Github Server -> createGithubFork -> Method call produced an error.')
SA.logger.error('Github Server -> createGithubFork -> err.stack = ' + err.stack)
SA.logger.error('Github Server -> createGithubFork -> repository = ' + repository)
SA.logger.error('Github Server -> createGithubFork -> username = ' + username)
SA.logger.error('Github Server -> createGithubFork -> token starts with = ' + token.substring(0, 10) + '...')
SA.logger.error('Github Server -> createGithubFork -> token ends with = ' + '...' + token.substring(token.length - 10))
let error = {
result: 'Fail Because',
message: err.message,
stack: err.stack
}
return error
}
}
async function mergeGithubPullRequests(commitMessage, username, token) {
try {
commitMessage = unescape(commitMessage)
username = unescape(username)
token = unescape(token)
/* Unsaving # */
for (let i = 0; i < 10; i++) {
commitMessage = commitMessage.replace('_SLASH_', '/')
commitMessage = commitMessage.replace('_HASHTAG_', '#')
}
let error
let githubPrListArray = []
return await processOpenPullRequests()
async function processOpenPullRequests() {
await doGithub('Governance-Plugins')
if (error !== undefined) {
let docs = {
project: 'Governance',
category: 'Topic',
type: 'Gov Error - Pull Requests Not Processed',
anchor: undefined,
placeholder: {}
}
return respondWithDocsObject(docs, error)
}
return {
result: global.DEFAULT_OK_RESPONSE.result
}
}
async function doGithub(repo = 'Governance-Plugins') {
try {
const owner = 'Superalgos'
const { Octokit } = SA.nodeModules.octokit
const octokit = new Octokit({
auth: token,
userAgent: 'Superalgos ' + SA.version
})
await getPrList()
await mergePrs()
await closePrsToMaster()
async function getPrList() {
const per_page = 100 // Max
let page = 0
let lastPage = false
while (lastPage === false) {
try {
page++
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
let listResponse = await octokit.rest.pulls.list({
owner: owner,
repo: repo,
state: 'open',
head: 'develop',
base: 'develop',
sort: undefined,
direction: undefined,
per_page: per_page,
page: page
});
if (listResponse.data.length < 100) {
lastPage = true
}
SA.logger.info('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList -> Receiving Page = ' + page)
for (let i = 0; i < listResponse.data.length; i++) {
let pullRequest = listResponse.data[i]
SA.logger.info('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList -> Pull Request "' + pullRequest.title + '" found and added to the list to validate. ')
githubPrListArray.push(pullRequest)
}
SA.logger.info('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList -> Received = ' + listResponse.data.length)
} catch (err) {
SA.logger.error(err)
if (err.stack.indexOf('last page') >= 0) {
return
} else {
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->Method call produced an error.')
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->err.stack = ' + err.stack)
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->repository = ' + repo)
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->username = ' + username)
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->token starts with = ' + token.substring(0, 10) + '...')
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->token ends with = ' + '...' + token.substring(token.length - 10))
error = err
return
}
}
}
}
async function mergePrs() {
/*
In order to automatically merge a PRs we will run several validations first.
We want to automate specifically the merging of Profile File changes at the
Governance System done by the same Github user name that matches the profile
changed. We will also not do the merge if there are more than one file at the
PR.
We will go through the list of open PRs and run the validations at each one of them.
*/
SA.logger.info('Github Server -> mergeGithubPullRequests -> Ready to Validate ' + githubPrListArray.length + ' pull requests. ')
for (let i = 0; i < githubPrListArray.length; i++) {
let pullRequest = githubPrListArray[i]
/*
Lets get the files changed at this Pull Request.
*/
let filesChanged = []
const per_page = 100 // Max
let page = 0
let lastPage = false
while (lastPage === false) {
page++
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
let listResponse = await octokit.rest.pulls.listFiles({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
per_page: per_page,
page: page
});
if (listResponse.data.length < 100) {
lastPage = true
}
for (let i = 0; i < listResponse.data.length; i++) {
let listItem = listResponse.data[i]
filesChanged.push(listItem)
}
}
let fileContentUrl // URL to the only file at the PR
let fileContent // File content of the only file at the PR
let userProfile // User Profile Object
let githubUsername // The Github user name of who is submitting the Pull Request
let mergeResponse // The response received from the call to Github to merge the Pull Request
if (await validatePrHasMoreThanOneFile() === false) { continue }
if (await validateFileNameEqualsGithubUsername() === false) { continue }
if (await validateFileChangedIsUserProfile() === false) { continue }
if (await validateMessageSignedIsGithubUsername() === false) { continue }
if (await validateMessageSignedHashIsSignatureHash() === false) { continue }
if (await validateUserProfileNodeNameEqualsGithubUsername() === false) { continue }
if (await validateUserProfileIdDoesNotBelongtoAnotherUserProfile() === false) { continue }
if (await validateUserProfileBlockchainAccountDoesNotBelongtoAnotherUserProfile() === false) { continue }
if (await validateUserProfileSigningAccountsDoesNotBelongtoAnotherUserProfile() === false) { continue }
/*
TODO: We need to check before merging a User Profile that none of id of the node of the profile hierarchy exists at any other
User Profile already at the repository, to avoid attacks of users hijacking references of other user profiles.
*/
if (await mergePullRequest() === false) {
SA.logger.warn('Github Server -> mergeGithubPullRequests -> Merge Failed -> Pull Request "' + pullRequest.title + '" not merged because Github could not merge it. -> mergeResponse.message = ' + mergeResponse.data.message)
} else {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Merge Succeed -> Pull Request "' + pullRequest.title + '" successfully merged. -> mergeResponse.message = ' + mergeResponse.data.message)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request was automatically merged by the Superalgos Governance System because it was detected that the Github User " ' + githubUsername + '" who submitted it, modified its own User Profile Plugin File and nothing else but that file. All validations were successful.'
});
}
async function validatePrHasMoreThanOneFile() {
/*
Validation #1: If the PR has more than one file, then we will not automatically
merge it.
*/
if (filesChanged.length !== 1) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #1 Failed -> Pull Request "' + pullRequest.title + '" not merged because it contains more than 1 file. -> fileCount = ' + filesChanged.length)
/*
We will close PRs that contains any User Profile file together with other files in the same Pull Request.
This will avoid manual merges to include User Profile files.
*/
for (let j = 0; j < filesChanged.length; j++) {
let pullRequestFile = filesChanged[j]
let fileContentUrl = pullRequestFile.raw_url
if (fileContentUrl.indexOf('Plugins/Governance/User-Profiles') >= 0) {
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because it was detected that a User Profile file... \n\n' + fileContentUrl + '\n\n...was submitted together with ' + (filesChanged.length - 1) + ' other file/s. User Profiles files as per the Governance System rules, must be the only file present at a Pull Request in order to pass all the validations and be automatically merged. \n\n If you intentionally submitted the extra files, the way to get your work merged is by first removing your User Profile file from the Plugins folder at your local installation and executing an app.contribute again. Then wait until the PR is merged (manually reviewed) and after that you put your User Profile file again and create a new PR only with that file with an app.contribute. That last PR should be merged automatically.'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
break
}
}
return false
}
}
async function validateFileNameEqualsGithubUsername() {
/*
Validation #2: File Name must be the same to the Github Username of the PR owner.
*/
let pullRequestFile = filesChanged[0]
fileContentUrl = unescape(pullRequestFile.raw_url)
if (fileContentUrl.indexOf('User-Profiles') < 0) {
/*
If it is not a user profile then there is no need to auto merge.
*/
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #2 Failed -> Pull Request "' + pullRequest.title + '" not merged because the file modified at the Pull Request is not a User Profile file. -> fileContentUrl = ' + fileContentUrl)
return false
}
let splittedURL = fileContentUrl.split('/')
let fileName = splittedURL[splittedURL.length - 1]
let splittedFileName = fileName.split('.')
fileName = splittedFileName[0]
githubUsername = pullRequest.user.login
if (githubUsername.toLowerCase() !== fileName.toLowerCase()) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #2 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Github Username is not equal to the File Name. -> Github Username = ' + githubUsername + '-> fileName = ' + fileName)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because it was detected that the Github User "' + githubUsername + '" who submitted it, is not equal to the name of the User Profile Plugin File.\n\n File Name = "' + fileName + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateFileChangedIsUserProfile() {
/*
Validation #3: The file changed at the PR is a User Profile.
*/
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
fileContent = await SA.projects.foundations.utilities.webAccess.fetchAPIDataFile(fileContentUrl)
try {
userProfile = JSON.parse(fileContent)
} catch (err) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #3 Failed -> Pull Request "' + pullRequest.title + '" not merged because the file modified it is not in a valid JSON format. -> err = ' + err.message)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because the User Profile is not in a valid JSON format.\n\n err = "' + err.message + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
if (userProfile.type !== 'User Profile') {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #3 Failed -> Pull Request "' + pullRequest.title + '" not merged because the file modified is not a User Profile. -> Type = ' + userProfile.type)
return false
}
}
async function validateMessageSignedIsGithubUsername() {
/*
Validation #4: The message signed at the config is not the Github Username.
*/
let config = JSON.parse(userProfile.config)
if (config.signature === undefined) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #4 Failed -> Pull Request "' + pullRequest.title + '" not merged because the User Profile config does not include a Signature. Maybe the user did not follow the procedure to create his User Profile but commited the User Profile file to the Governance repo anyways.')
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'Github Server -> mergeGithubPullRequests -> Validation #4 Failed -> Pull Request "' + pullRequest.title + '" not merged because the User Profile config does not include a Signature. Maybe the user did not follow the procedure to create his User Profile but commited the User Profile file to the Governance repo anyways.'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
let messageSigned = config.signature.message
if (messageSigned.toLowerCase() !== githubUsername.toLowerCase()) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #4 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Github Username is not equal to the Message Signed at the User Profile. -> Github Username = ' + githubUsername + '-> messageSigned = ' + messageSigned)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because it was detected that the Github User "' + githubUsername + '" who submitted it, is not equal to the Message Signed at the User Profile.\n\n Message Signed = "' + messageSigned + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateMessageSignedHashIsSignatureHash() {
/*
Validation #5: The message signed has is equal to the signature messageHash.
*/
let config = JSON.parse(userProfile.config)
let serverResponse = await PL.servers.WEB3_SERVER.hashData(
config.signature.message
)
let messageSignedHash = serverResponse.hash
let signatureHash = config.signature.messageHash
if (messageSignedHash !== signatureHash) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #5 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Message Signed Hash is not equal to the the Signature Hash. -> messageSignedHash = ' + messageSignedHash + '-> signatureHash = ' + signatureHash)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because the Message Signed Hash is not equal to the the Signature Hash.\n\n messageSignedHash = "' + messageSignedHash + '"\n\n signatureHash = "' + signatureHash + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateUserProfileNodeNameEqualsGithubUsername() {
/*
Validation #6: The name of the User Profile node is not the Github Username.
*/
if (userProfile.name.toLowerCase() !== githubUsername.toLowerCase()) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #6 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Github Username is not equal to the User Profile node\'s name. -> Github Username = ' + githubUsername + '-> userProfile.name = ' + userProfile.name)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because it was detected that the Github User "' + githubUsername + '" who submitted it, is not equal to the User Profile node\'s name.\n\n User Profile Name = "' + userProfile.name + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateUserProfileIdDoesNotBelongtoAnotherUserProfile() {
/*
Validation #7: The id of the User Profile can not be the id of an already existing User Profile
unless the existing one belongs to the same Github username.
*/
let userProfileIdMap = new Map()
let pluginFileNames = await SA.projects.communityPlugins.utilities.plugins.getPluginFileNames(
'Governance',
'User-Profiles'
)
for (let i = 0; i < pluginFileNames.length; i++) {
let pluginFileName = pluginFileNames[i]
let pluginFileContent = await SA.projects.communityPlugins.utilities.plugins.getPluginFileContent(
'Governance',
'User-Profiles',
pluginFileName
)
let otherUserProfile = JSON.parse(pluginFileContent)
userProfileIdMap.set(otherUserProfile.id, otherUserProfile.name)
}
let testUserProfile = userProfileIdMap.get(userProfile.id)
if (testUserProfile === undefined) { return true }
if (testUserProfile !== userProfile.name) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #7 Failed -> Pull Request "' + pullRequest.title + '" not merged because the User Profile Id already exists and belongs to another User Profile on record. -> Profile Id = ' + userProfile.id + '-> User Profile with the same Id = ' + testUserProfile)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because the User Profile Id already exists and belongs to another User Profile on record. \n\nUser Profile Id = "' + userProfile.id + '" \n\n User Profile with the same Id = "' + testUserProfile + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateUserProfileBlockchainAccountDoesNotBelongtoAnotherUserProfile() {
try {
/*
Validation #8 The blockchain account of the User Profile can not be the
blockchain account of an already existing User Profile
unless the existing one belongs to the same Github username.
*/
let userProfileIdMap = new Map()
let pluginFileNames = await SA.projects.communityPlugins.utilities.plugins.getPluginFileNames(
'Governance',
'User-Profiles'
)
for (let i = 0; i < pluginFileNames.length; i++) {
let pluginFileName = pluginFileNames[i]
let pluginFileContent = await SA.projects.communityPlugins.utilities.plugins.getPluginFileContent(
'Governance',
'User-Profiles',
pluginFileName
)
let otherUserProfile = JSON.parse(pluginFileContent)
let config = JSON.parse(otherUserProfile.config)
let messageSigned = JSON.stringify(config.signature)
let serverResponse = await PL.servers.WEB3_SERVER.recoverAddress(
messageSigned
)
userProfileIdMap.set(serverResponse.address, otherUserProfile.name)
}
let config = JSON.parse(userProfile.config)
let messageSigned = JSON.stringify(config.signature)
let serverResponse = await PL.servers.WEB3_SERVER.recoverAddress(
messageSigned
)
let testUserProfile = userProfileIdMap.get(serverResponse.address)
if (testUserProfile === undefined) { return true }
if (testUserProfile !== userProfile.name) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #8 Failed -> Pull Request "' + pullRequest.title + '" not merged because the User Profile Blockchain Account already exists and belongs to another User Profile on record. -> Profile Blockchain Account = ' + serverResponse.address + '-> User Profile with the same Blockchain Account = ' + testUserProfile)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because the User Profile Blockchain Account already exists and belongs to another User Profile on record. \n\nUser Profile Blockchain Account = "' + serverResponse.address + '" \n\n User Profile with the same Blockchain Account = "' + testUserProfile + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
} catch (err) {
SA.logger.error(err.stack)
}
}
async function validateUserProfileSigningAccountsDoesNotBelongtoAnotherUserProfile() {
try {
if (userProfile.signingAccounts === undefined) { return true }
for (let i = 0; i < userProfile.signingAccounts.signingAccounts.length; i++) {
let signingAccount = userProfile.signingAccounts.signingAccounts[i]
let config = JSON.parse(signingAccount.config)
/*
Validation #9 Signing accounts of the User Profile
must have a signature of the same Github username of the User Profile.
*/
let messageSigned = config.signature.message
if (messageSigned.toLowerCase() !== githubUsername.toLowerCase()) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #9 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Signing Account ' + signingAccount.name + ' has not signed the current Github User Account, but something else. -> messageSigned = ' + messageSigned + '-> githubUsername = ' + githubUsername)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because the Signing Account "' + signingAccount.name + '" has not signed the current Github User Account, but something else. \n\n messageSigned = "' + messageSigned + '" \n\n githubUsername = "' + githubUsername + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
/*
Validation #10: The message signed has is equal to the signature messageHash.
*/
let serverResponse = await PL.servers.WEB3_SERVER.hashData(
config.signature.message
)
let messageSignedHash = serverResponse.hash
let signatureHash = config.signature.messageHash
if (messageSignedHash !== signatureHash) {
SA.logger.info('Github Server -> mergeGithubPullRequests -> Validation #10 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Message Signed Hash is not equal to the the Signature Hash. -> messageSignedHash = ' + messageSignedHash + '-> signatureHash = ' + signatureHash)
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because the Message Signed Hash is not equal to the the Signature Hash.\n\n messageSignedHash = "' + messageSignedHash + '"\n\n signatureHash = "' + signatureHash + '"'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
return true
} catch (err) {
SA.logger.error(err.stack)
}
}
async function mergePullRequest() {
/*
All validations passed, we will proceed an merge this Pull Request.
*/
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
mergeResponse = await octokit.rest.pulls.merge({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
commit_title: 'Changes in User Profile done by Profile Owner ' + githubUsername + ' automatically merged by Superalgos.'
});
return mergeResponse.data.merged
}
}
}
async function closePrsToMaster() {
let githubPrListMaster = []
const per_page = 100 // Max
let page = 0
try {
page++
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
let listResponse = await octokit.rest.pulls.list({
owner: owner,
repo: repo,
state: 'open',
head: undefined,
base: 'master',
sort: undefined,
direction: undefined,
per_page: per_page,
page: page
});
if (listResponse.data.length < 100) {
lastPage = true
}
SA.logger.info('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster -> Receiving Page = ' + page)
for (let i = 0; i < listResponse.data.length; i++) {
let pullRequest = listResponse.data[i]
SA.logger.info('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster -> Pull Request "' + pullRequest.title + '" found and added to the list to validate. ')
githubPrListMaster.push(pullRequest)
}
SA.logger.info('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster -> Received = ' + listResponse.data.length)
for (let i = 0; i < githubPrListMaster.length; i++) {
let pullRequest = githubPrListMaster[i]
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'Hi, this is the Superalgos Governance System taking notice that you have submitted a pull request directly to the master branch.\n\nThanks for submitting a PR to the Superalgos Project. We value every contribution and everyone is welcome to send PRs. Unfortunately we are not merging pull requests directly into the master branch. Consider resubmitting to the develop branch instead. For your convenience, you can switch branches from within the app, at the footer of the Docs tab. \n\n I will close this pull request now and look forward for your next contribution either to the develop branch or any other branch available for this purpose.'
});
await SA.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
}
} catch (err) {
if (err.stack.indexOf('last page') >= 0) {
return
} else {
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->Method call produced an error.')
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->err.stack = ' + err.stack)
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->repository = ' + repo)
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->username = ' + username)
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->token starts with = ' + token.substring(0, 10) + '...')
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->token ends with = ' + '...' + token.substring(token.length - 10))
error = err
return
}
}
}
} catch (err) {
if (err === undefined) { return }
SA.logger.error('Github Server -> mergeGithubPullRequests -> doGithub -> err.stack = ' + err.stack)
}
}
} catch (err) {
SA.logger.error('Github Server -> mergeGithubPullRequests -> Method call produced an error.')
SA.logger.error('Github Server -> mergeGithubPullRequests -> err.stack = ' + err.stack)
SA.logger.error('Github Server -> mergeGithubPullRequests -> repository = ' + repo)
SA.logger.error('Github Server -> mergeGithubPullRequests -> username = ' + username)
SA.logger.error('Github Server -> mergeGithubPullRequests -> token starts with = ' + token.substring(0, 10) + '...')
SA.logger.error('Github Server -> mergeGithubPullRequests -> token ends with = ' + '...' + token.substring(token.length - 10))
let error = {
result: 'Fail Because',
message: err.message,
stack: err.stack
}
return error
}
}
function respondWithDocsObject(docs, error) {
if (error.message !== undefined) {
docs.placeholder.errorMessage = {
style: 'Error',
text: error.message
}
}
if (error.stack !== undefined) {
docs.placeholder.errorStack = {
style: 'Javascript',
text: error.stack
}
}
if (error.status !== undefined) {
docs.placeholder.errorCode = {
style: 'Json',
text: error.status
}
}
docs.placeholder.errorDetails = {
style: 'Json',
text: JSON.stringify(error, undefined, 4)
}
let customResponse = {
result: global.CUSTOM_FAIL_RESPONSE.result,
docs: docs
}
return customResponse
}
}