-
Notifications
You must be signed in to change notification settings - Fork 316
/
Copy pathscriptStorage.js
1992 lines (1668 loc) · 58.3 KB
/
scriptStorage.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
'use strict';
// Define some pseudo module globals
var isPro = require('../libs/debug').isPro;
var isDev = require('../libs/debug').isDev;
var isDbg = require('../libs/debug').isDbg;
var statusError = require('../libs/debug').statusError;
//
//--- Dependency inclusions
var fs = require('fs');
var util = require('util');
var _ = require('underscore');
var URL = require('url');
var http = require('http');
var https = require('https');
var crypto = require('crypto');
var stream = require('stream');
var peg = require('pegjs');
var AWS = require('aws-sdk');
var UglifyJS = require("uglify-es");
var rfc2047 = require('rfc2047');
var mediaType = require('media-type');
var mediaDB = require('mime-db');
var async = require('async');
var moment = require('moment');
var Base62 = require('base62');
var SPDXOSI = require('spdx-osi'); // NOTE: Sub-dep of `spdx-is-osi`
var SPDX = require('spdx-license-ids');
var sizeOf = require('image-size');
var MongoClient = require('mongodb').MongoClient;
var ExpressBrute = require('express-brute');
var MongoStore = require('express-brute-mongo');
//--- Model inclusions
var Script = require('../models/script').Script;
var User = require('../models/user').User;
var Discussion = require('../models/discussion').Discussion;
//--- Controller inclusions
//--- Library inclusions
// var scriptStorageLib = require('../libs/scriptStorage');
var ensureIntegerOrNull = require('../libs/helpers').ensureIntegerOrNull;
var RepoManager = require('../libs/repoManager');
var cleanFilename = require('../libs/helpers').cleanFilename;
var findDeadorAlive = require('../libs/remove').findDeadorAlive;
var encode = require('../libs/helpers').encode;
var isFQUrl = require('../libs/helpers').isFQUrl;
var countTask = require('../libs/tasks').countTask;
var modelParser = require('../libs/modelParser');
//--- Configuration inclusions
var userRoles = require('../models/userRoles.json');
var blockSPDX = require('./blockSPDX');
// Add greasemonkey support for Media Type
if (!mediaDB['text/x-userscript-meta']) {
mediaDB = _.extend(mediaDB, {
'text/x-userscript-meta' : {
source: 'greasemonkey',
compressible: true,
extensions: ['meta.js']
}
});
}
if (!mediaDB['text/x-userscript']) {
mediaDB = _.extend(mediaDB, {
'text/x-userscript' : {
source: 'greasemonkey_peer',
compressible: true,
extensions: ['user.js']
}
});
}
// Allow Microsoft Edge browsers to test
if (!mediaDB['image/jxr']) {
mediaDB = _.extend(mediaDB, {
'image/jxr' : {
source: 'iana_psmtr',
extensions: ['jxr']
}
});
}
if (!mediaDB['*/*']) {
mediaDB = _.extend(mediaDB, {'*/*' : { source: 'iana'}});
}
//---
// Load in the pegjs configuration files synchronously to detect immediate change errors.
// NOTE: These aren't JSON so not included in configuration inclusions but nearby
var parsers = (function () {
return {
UserScript: peg.generate(fs.readFileSync('./public/pegjs/blockUserScript.pegjs', 'utf8'),
{ allowedStartRules: ['line'] }),
UserLibrary: peg.generate(fs.readFileSync('./public/pegjs/blockUserLibrary.pegjs', 'utf8'),
{ allowedStartRules: ['line'] }),
OpenUserJS: peg.generate(fs.readFileSync('./public/pegjs/blockOpenUserJS.pegjs', 'utf8'),
{ allowedStartRules: ['line'] })
};
})();
exports.parsers = parsers;
var bucketName = 'OpenUserJS.org';
var DEV_AWS_URL = null;
if (isPro) {
AWS.config.update({
region: 'us-east-1'
});
} else {
// You need to install (and ruby too): https://github.com/jubos/fake-s3
// Then run the fakes3.sh script or: fakes3 -r fakeS3 -p 10001
DEV_AWS_URL = process.env.DEV_AWS_URL || 'http://localhost:10001';
AWS.config.update({
accessKeyId: 'fakeId',
secretAccessKey: 'fakeKey',
httpOptions: {
proxy: DEV_AWS_URL,
agent: require('http').globalAgent
}
});
}
// Get UglifyJS harmony installation datestamp once
var stats = fs.statSync('./node_modules/uglify-es/package.json');
var mtimeUglifyJS = new Date(util.inspect(stats.mtime));
// Brute initialization
var store = null;
if (isPro) {
store = new MongoStore(function (ready) {
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(aErr, aDb) {
if (aErr) {
throw aErr;
}
ready(aDb.collection('bruteforce-store'));
});
});
} else {
store = new ExpressBrute.MemoryStore(); // stores state locally, don't use this in production
}
var tooManyRequests = function (aReq, aRes, aNext, aNextValidRequestDate) {
var secondUntilNextRequest = null;
if (isDev) {
secondUntilNextRequest = Math.ceil((aNextValidRequestDate.getTime() - Date.now())/1000);
aRes.header('Retry-After', secondUntilNextRequest);
}
aRes.status(429).send(); // Too Many Requests
}
var sweetFactor = ensureIntegerOrNull(process.env.BRUTE_SWEETFACTOR) || (2);
var installMaxBruteforce = new ExpressBrute(store, {
freeRetries: ensureIntegerOrNull(process.env.BRUTE_FREERETRIES) || (0),
minWait: ensureIntegerOrNull(process.env.BRUTE_MINWAIT) || (1000 * 60), // sec
maxWait: ensureIntegerOrNull(process.env.BRUTE_MAXWAIT) || (1000 * 60 * 15), // min
lifetime: ensureIntegerOrNull(process.env.BRUTE_LIFETIME) || undefined, //
failCallback: tooManyRequests
});
var sourceMaxBruteforce = new ExpressBrute(store, {
freeRetries: ensureIntegerOrNull(process.env.BRUTE_FREERETRIES) || (0),
minWait: ensureIntegerOrNull(process.env.BRUTE_MINWAIT / sweetFactor) ||
ensureIntegerOrNull((1000 * 60) / sweetFactor), // sec
maxWait: ensureIntegerOrNull(process.env.BRUTE_MAXWAIT / sweetFactor) ||
ensureIntegerOrNull((1000 * 60 * 15) / sweetFactor), // min
lifetime: ensureIntegerOrNull(process.env.BRUTE_LIFETIME) || undefined, //
failCallback: tooManyRequests
});
// Enabled with meta requests
var installMinBruteforce = new ExpressBrute(store, {
freeRetries: ensureIntegerOrNull(process.env.BRUTE_FREERETRIES) || (0),
minWait: ensureIntegerOrNull(process.env.BRUTE_MINWAIT) || ensureIntegerOrNull(1000 * (60 / 4)), // sec
maxWait: ensureIntegerOrNull(process.env.BRUTE_MAXWAIT) || ensureIntegerOrNull(1000 * (60 / 4)), // min
lifetime: ensureIntegerOrNull(process.env.BRUTE_LIFETIME) || undefined, //
failCallback: tooManyRequests
});
var sourceMinBruteforce = new ExpressBrute(store, {
freeRetries: ensureIntegerOrNull(process.env.BRUTE_FREERETRIES) || (0),
minWait: ensureIntegerOrNull(process.env.BRUTE_MINWAIT / sweetFactor) ||
ensureIntegerOrNull((1000 * (60 / 4)) / sweetFactor), // sec
maxWait: ensureIntegerOrNull(process.env.BRUTE_MAXWAIT / sweetFactor) ||
ensureIntegerOrNull((1000 * (60 / 4) * 15) / sweetFactor), // min
lifetime: ensureIntegerOrNull(process.env.BRUTE_LIFETIME) || undefined, //
failCallback: tooManyRequests
});
//
function getInstallNameBase(aReq, aOptions) {
//
var base = null;
var username = aReq.params.username;
var scriptname = aReq.params.scriptname;
var rKnownExtensions = /\.(min\.)?((user\.)?js|meta\.js(on)?)$/;
if (!aOptions) {
aOptions = {};
}
if (aOptions.hasExtension) {
scriptname = scriptname.replace(rKnownExtensions, '');
}
switch (aOptions.encoding) {
case 'uri':
base = encodeURIComponent(username) + '/' + encodeURIComponent(scriptname);
break;
case 'url':
base = encode(username) + '/' + encode(scriptname);
default:
base = username + '/' + scriptname;
}
return base;
}
exports.getInstallNameBase = getInstallNameBase;
function caseInsensitive(aInstallName) {
return new RegExp('^' + aInstallName.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") + '$', 'i');
}
exports.caseInsensitive = caseInsensitive;
function caseSensitive(aInstallName, aMoreThanInstallName) {
//
var rMatchExpression = aMoreThanInstallName ? /^(.*)\/(.*)\/(.*)\/(.*)$/ : /^(.*)\/(.*)$/;
var matches = aInstallName.match(rMatchExpression);
var char = null;
var username = '';
var rExpression = null;
if (matches) {
if (aMoreThanInstallName) {
for (char in matches[2]) {
if (matches[2][char].toLowerCase() !== matches[2][char].toUpperCase()) {
username += '[' +
matches[2][char].toLowerCase().replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") +
matches[2][char].toUpperCase().replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") + ']';
} else {
username += matches[2][char].replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
}
rExpression = new RegExp(
'^' +
matches[1] + '/' +
username + '/' +
matches[3].replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") + '/' +
matches[4] + '$',
''
);
} else {
for (char in matches[1]) {
if (matches[1][char].toLowerCase() !== matches[1][char].toUpperCase()) {
username += '[' +
matches[1][char].toLowerCase().replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") +
matches[1][char].toUpperCase().replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") + ']';
} else {
username += matches[1][char].replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
}
rExpression = new RegExp(
'^' +
username + '/' +
matches[2].replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") + '$',
''
);
}
}
return rExpression;
}
exports.caseSensitive = caseSensitive;
exports.getSource = function (aReq, aCallback) {
var installNameBase = getInstallNameBase(aReq, { hasExtension: true });
var isLib = aReq.params.isLib;
Script.findOne({
installName: caseSensitive(installNameBase + (isLib ? '.js' : '.user.js'))
}, function (aErr, aScript) {
var s3Object = null;
var s3 = new AWS.S3();
if (aErr) {
if (isDbg) {
console.error(
'Document lookup failure for',
installNameBase + (isLib ? '.js' : '.user.js'),
aErr.message
);
}
aCallback(null);
return;
}
if (!aScript) {
if (isDbg) {
console.warn(
'Document not found for', installNameBase + (isLib ? '.js' : '.user.js')
);
}
aCallback(null);
return;
}
// Ensure casing on username is identical for S3 retrieval
if (aReq.params.username !== aScript.author) {
aReq.params.username = aScript.author;
installNameBase = getInstallNameBase(aReq, { hasExtension: true });
}
s3Object = s3.getObject({
Bucket: bucketName,
Key: installNameBase + (isLib ? '.js' : '.user.js')
}, function(aErr, aData) {
var bufferStream = null;
if (aErr) {
console.error(
'S3 GET (establishing) ',
aErr.code,
'for', installNameBase + (isLib ? '.js' : '.user.js') + '\n' +
JSON.stringify(aErr, null, ' ') + '\n' +
aErr.stack
);
// Abort
aCallback(null);
// fallthrough
} else {
bufferStream = new stream.PassThrough();
bufferStream.end(new Buffer(aData.Body));
// Get the script
aCallback(aScript, bufferStream);
}
})
});
};
var cacheableScript = function (aReq) {
var pragma = aReq.get('pragma') || null;
var cacheControl = aReq.get('cache-control') || null;
if (pragma && pragma.indexOf('no-cache') !== -1 ||
(cacheControl &&
cacheControl.indexOf('no-cache') !== -1 &&
cacheControl.indexOf('no-store') !== -1 &&
cacheControl.indexOf('no-transform') !== -1)) {
} else {
return true;
}
return false; // Always ensure default is `false`
}
var keyScript = function (aReq, aRes, aNext) {
let pathname = aReq._parsedUrl.pathname;
let isLib = /^\/src\/libs\//.test(pathname);
let installName = pathname.replace(/^\/(?:install|src\/(?:scripts|libs))\//, '');
let parts = installName.split('/');
let userName = parts[0].toLowerCase();
let scriptName = parts[1];
let rJS = /\.js$/;
if (!isLib) {
aNext(userName + '/' + scriptName.replace(/(\.min)?\.(?:user|meta)\.js$/, '.user.js'));
return;
} else if (rJS.test(scriptName)) {
aNext(userName + '/' + scriptName.replace(/(\.min)?\.js$/, '.js'));
return;
}
// No matches so force to end point
aRes.status(400).send(); // Bad Request
}
exports.unlockScript = function (aReq, aRes, aNext) {
let rMetaMinUserLibJS = /(?:\.(?:meta|(?:min\.)?user|min))?\.js$/;
let pathname = aReq._parsedUrl.pathname;
let acceptHeader = aReq.headers.accept || '*/*';
let accepts = null;
let wantsJustAnything = false;
let hasUnacceptable = false;
let hasAcceptable = false;
let rMetaJS = /\.meta\.js$/;
let wantsUserScriptMeta = null;
let isSource = /^\/src\//.test(pathname);
// Test known extensions
if (!rMetaMinUserLibJS.test(pathname)) {
aRes.status(400).send(); // Bad request
return;
}
// Test accepts
accepts = acceptHeader.split(',').map(function (aEl) {
return aEl.trim();
}).reverse();
for (let accept of accepts) {
let media = mediaType.fromString(accept);
if (media.isValid()) {
// Check for unacceptables
let mediaTypeSubtypeSuffix = media.type + '/' + media.subtype + (media.hasSuffix() ? '+' + media.suffix : '');
if (!mediaDB[mediaTypeSubtypeSuffix]) {
if (isDev) {
console.warn('- unacceptable := ', mediaTypeSubtypeSuffix);
}
hasUnacceptable = true;
break;
}
// Check for just anything
if (mediaTypeSubtypeSuffix === '*/*' && accepts.length === 1) {
wantsJustAnything = true;
break;
}
// Check for acceptables
for (let acceptable of
[
'text/x-userscript-meta',
'text/x-userscript',
'text/javascript',
'text/ecmascript',
'application/javascript',
'application/x-javascript',
'text/html',
'application/xhtml+xml',
'*/*'
]
) {
if (mediaTypeSubtypeSuffix === acceptable && mediaTypeSubtypeSuffix !== '*/*') {
hasAcceptable = true;
}
}
} else {
hasUnacceptable = true;
break;
}
}
if (hasUnacceptable || (!wantsJustAnything && !hasAcceptable)) {
aRes.status(406).send(); // Not Acceptable
return;
}
// Determine if .meta.js is wanted
wantsUserScriptMeta =
(aReq.headers.accept || '*/*').split(',').indexOf('text/x-userscript-meta') > -1 ||
rMetaJS.test(pathname);
// Test cacheable
if (isSource) {
if (cacheableScript(aReq) && process.env.FORCE_SCRIPT_NOCACHE !== 'true') {
aNext();
} else {
if (wantsUserScriptMeta) {
sourceMinBruteforce.getMiddleware({key : keyScript})(aReq, aRes, aNext);
} else {
sourceMaxBruteforce.getMiddleware({key : keyScript})(aReq, aRes, aNext);
}
}
} else {
if (cacheableScript(aReq) && process.env.FORCE_SCRIPT_NOCACHE !== 'true') {
aNext();
} else {
if (wantsUserScriptMeta) {
installMinBruteforce.getMiddleware({key : keyScript})(aReq, aRes, aNext);
} else {
installMaxBruteforce.getMiddleware({key : keyScript})(aReq, aRes, aNext);
}
}
}
}
exports.sendScript = function (aReq, aRes, aNext) {
if (aReq.params.type === 'libs') {
aReq.params.isLib = true;
}
let pathname = aReq._parsedUrl.pathname;
let isLib = aReq.params.isLib || /^\/src\/libs\//.test(pathname);
let rMetaJS = /\.meta\.js$/;
if (!isLib &&
((aReq.headers.accept || '*/*').split(',').indexOf('text/x-userscript-meta') > -1 ||
rMetaJS.test(pathname))) {
exports.sendMeta(aReq, aRes, aNext);
return;
}
exports.getSource(aReq, function (aScript, aStream) {
let chunks = [];
let updateURL = null;
let updateUtf = null;
let matches = null;
let rAnyLocalMetaUrl = new RegExp('^https?://(?:openuserjs\.org|oujs\.org' +
(isDev ? '|localhost:' + (process.env.PORT || 8080) : '') +
')/(?:meta|install|src/scripts)/(.+?)/(.+?)\.meta\.js$');
let hasAlternateLocalUpdateURL = false;
let rAnyLocalHost = new RegExp('^(?:openuserjs\.org|oujs\.org' +
(isDev ? '|localhost:' + (process.env.PORT || 8080) : '') + ')');
var lastModified = null;
var eTag = null;
var maxAge = 7 * 60 * 60 * 24; // nth day(s) in seconds
var now = null;
var continuation = true;
if (!aScript) {
aNext();
return;
}
if (process.env.FORCE_BUSY_UPDATEURL_CHECK === 'true') {
// `@updateURL` must be exact here for OUJS hosted checks
// e.g. no `search`, no `hash`
updateURL = findMeta(aScript.meta, 'UserScript.updateURL.0.value');
if (updateURL) {
// Check for decoding error
try {
updateUtf = decodeURIComponent(updateURL);
} catch (aE) {
aRes.set('Warning', '199 ' + aReq.headers.host +
rfc2047.encode(' Invalid @updateURL'));
aRes.status(444).send(); // No Response
return;
}
// Validate `author` and `name` (installNameBase) to this scripts meta only
let matches = updateUtf.match(rAnyLocalMetaUrl);
if (matches) {
if (cleanFilename(aScript.author, '').toLowerCase() +
'/' + cleanFilename(aScript.name, '') === matches[1].toLowerCase() + '/' + matches[2])
{
// Same script
} else {
hasAlternateLocalUpdateURL = true;
}
} else {
// Allow offsite checks
updateURL = URL.parse(updateURL);
if (rAnyLocalHost.test(updateURL.host)) {
hasAlternateLocalUpdateURL = true;
}
}
} else {
if (!aScript.isLib) {
// Don't serve the script anywhere in this mode and if absent
hasAlternateLocalUpdateURL = true;
}
}
if (hasAlternateLocalUpdateURL) {
aRes.set('Warning', '199 ' + aReq.headers.host +
rfc2047.encode(' Invalid @updateURL in lockdown'));
aRes.status(444).send(); // No Response
return;
}
}
// HTTP/1.1 Caching
aRes.set('Cache-Control', 'public, max-age=' + maxAge +
', no-cache, no-transform, must-revalidate');
// Only minify for response that doesn't contain `.min.` extension
if (!/\.min(\.user)?\.js$/.test(aReq._parsedUrl.pathname) ||
process.env.DISABLE_SCRIPT_MINIFICATION === 'true') {
//
lastModified = moment(aScript.updated)
.utc().format('ddd, DD MMM YYYY HH:mm:ss') + ' GMT';
// Convert a based representation of the hex sha512sum
eTag = '"' + Base62.encode(parseInt('0x' + aScript.hash, 16)) + ' .user.js"';
// If already client-side... HTTP/1.1 Caching
if (aReq.get('if-none-match') === eTag || aReq.get('if-modified-since') === lastModified) {
aRes.status(304).send(); // Not Modified
return;
}
//
aStream.on('error', function (aErr) {
// This covers errors during connection in direct view
console.error(
'S3 GET (chunking native) ',
aErr.code,
'for', aScript.installName + '\n' +
JSON.stringify(aErr, null, ' ') + '\n' +
aErr.stack
);
if (continuation) {
continuation = false;
// Abort
aNext();
// fallthrough
}
});
aStream.on('data', function (aData) {
if (continuation) {
chunks.push(aData);
}
});
aStream.on('end', function () {
let source = null;
if (continuation) {
continuation = false;
source = chunks.join(''); // NOTE: Watchpoint
// Send the script
aRes.set('Content-Type', 'text/javascript; charset=UTF-8');
aStream.setEncoding('utf8');
// HTTP/1.0 Caching
aRes.set('Expires', moment(moment() + maxAge * 1000).utc()
.format('ddd, DD MMM YYYY HH:mm:ss') + ' GMT');
// HTTP/1.1 Caching
aRes.set('Last-modified', lastModified);
aRes.set('Etag', eTag);
aRes.write(source);
aRes.end();
// NOTE: Try and force a GC
source = null;
chunks = null;
// Don't count installs on raw source route
if (aScript.isLib || aReq.params.type) {
return;
}
// Update the install count
++aScript.installs;
++aScript.installsSinceUpdate;
// Resave affected properties
aScript.save(function (aErr, aScript) {
// WARNING: No error handling at this stage
});
}
});
} else { // Wants to try minified
//
lastModified = moment(mtimeUglifyJS > aScript.updated ? mtimeUglifyJS : aScript.updated)
.utc().format('ddd, DD MMM YYYY HH:mm:ss') + ' GMT';
// If already client-side... partial HTTP/1.1 Caching
if (isPro && aReq.get('if-modified-since') === lastModified) {
aRes.status(304).send(); // Not Modified
return;
}
aStream.on('error', function (aErr) {
// This covers errors during connection in direct view
console.error(
'S3 GET (chunking minified) ',
aErr.code,
'for', aScript.installName + '\n' +
JSON.stringify(aErr, null, ' ') + '\n' +
aErr.stack
);
if (continuation) {
continuation = false;
// Abort
aNext();
// fallthrough
}
});
aStream.on('data', function (aData) {
if (continuation) {
chunks.push(aData);
}
});
aStream.on('end', function () {
let source = null;
let result = null;
let msg = null;
if (continuation) {
continuation = false;
source = chunks.join(''); // NOTE: Watchpoint
msg = null;
try {
result = UglifyJS.minify(source, {
parse: {
bare_returns: true
},
compress: {
inline: false
},
mangle: false,
output: {
comments: true,
quote_style: 3
}
});
if (result.error) {
throw result.error; // Passthrough the error if present to our handler
} else if(!result.code) {
throw new TypeError('UglifyJS error of `code` being absent');
} else {
source = result.code;
// Calculate a based representation of the hex sha512sum
eTag = '"' + Base62.encode(
parseInt('0x' + crypto.createHash('sha512').update(source).digest('hex'), 16)) +
' .min.user.js"';
}
} catch (aE) { // On any failure default to unminified
console.warn([
'MINIFICATION WARNING (harmony):',
' message: ' + aE.message,
' installName: ' + aScript.installName,
' line: ' + aE.line + ' col: ' + aE.col + ' pos: ' + aE.pos
].join('\n'));
// Set up a `Warning` header with Q encoding under RFC2047
msg = [
'199 ' + aReq.headers.host + ' MINIFICATION WARNING (harmony):',
' ' + rfc2047.encode(aE.message.replace(/\xAB/g, '`').replace(/\xBB/g, '`')),
' line: ' + aE.line + ' col: ' + aE.col + ' pos: ' + aE.pos,
].join('\u0020'); // TODO: Watchpoint... *express*/*node* exception thrown with CRLF SPACE spec
aRes.set('Warning', msg);
// Reset to unminified last modified date stamp
lastModified = moment(aScript.updated)
.utc().format('ddd, DD MMM YYYY HH:mm:ss') + ' GMT';
// Reset to convert a based representation of the hex sha512sum
eTag = '"' + Base62.encode(parseInt('0x' + aScript.hash, 16)) + ' .user.js"';
}
// If already client-side... partial HTTP/1.1 Caching
if (aReq.get('if-none-match') === eTag) {
// Conditionally send lastModified
if (aReq.get('if-modified-since') !== lastModified) {
aRes.set('Last-Modified', lastModified);
}
aRes.status(304).send(); // Not Modified
return;
}
// Send the script
aRes.set('Content-Type', 'text/javascript; charset=UTF-8');
aStream.setEncoding('utf8');
// HTTP/1.0 Caching
aRes.set('Expires', moment(moment() + maxAge * 1000)
.utc().format('ddd, DD MMM YYYY HH:mm:ss') + ' GMT');
// HTTP/1.1 Caching
aRes.set('Last-Modified', lastModified);
aRes.set('Etag', eTag);
aRes.write(source);
aRes.end();
// NOTE: Try and force a GC
source = null;
chunks = null;
// Don't count installs on raw source route
if (aScript.isLib || aReq.params.type) {
return;
}
// Update the install count
++aScript.installs;
++aScript.installsSinceUpdate;
// Resave affected properties
aScript.save(function (aErr, aScript) {
// WARNING: No error handling at this stage
});
}
});
}
});
};
// Send user script metadata block
exports.sendMeta = function (aReq, aRes, aNext) {
function preRender() {
}
function render() {
aRes.end(JSON.stringify(meta, null, isPro ? '' : ' '));
}
function asyncComplete(aErr) {
if (aErr) {
aRes.status(aErr.statusCode).send({status: aErr.statusCode, message: aErr.statusMessage});
return;
}
preRender();
render();
}
var installNameBase = getInstallNameBase(aReq, { hasExtension: true });
var meta = null;
Script.findOne({ installName: caseSensitive(installNameBase + '.user.js') },
function (aErr, aScript) {
var script = null;
var scriptOpenIssueCountQuery = null;
var whitespace = '\u0020\u0020\u0020\u0020';
var tasks = [];
var eTag = null;
var maxAge = 7 * 60 * 60 * 24; // nth day(s) in seconds
if (!aScript) {
aNext();
return;
}
// HTTP/1.1 Caching
aRes.set('Cache-Control', 'public, max-age=' + maxAge +
', no-cache, no-transform, must-revalidate');
script = modelParser.parseScript(aScript);
meta = script.meta; // NOTE: Watchpoint
if (/\.json$/.test(aReq.params.scriptname)) {
// Create a based representation of the hex sha512sum
eTag = '"' + Base62.encode(parseInt('0x' + aScript.hash, 16)) + ' .meta.json"';
// If already client-side... HTTP/1.1 Caching
if (aReq.get('if-none-match') === eTag) {
aRes.status(304).send(); // Not Modified
return;
}
// Okay to send .meta.json...
aRes.set('Content-Type', 'application/json; charset=UTF-8');
// HTTP/1.0 Caching
aRes.set('Expires', moment(moment() + maxAge * 1000).utc()
.format('ddd, DD MMM YYYY HH:mm:ss') + ' GMT');
// HTTP/1.1 Caching
aRes.set('Etag', eTag);
// Check for existance of OUJS metadata block
if (!meta.OpenUserJS) {
meta.OpenUserJS = {};
}
// Overwrite any keys found with the following...
meta.OpenUserJS.installs = [{ value: script.installs }];
meta.OpenUserJS.issues = [{ value: 'n/a' }];
meta.OpenUserJS.hash = aScript.hash ? [{ value: aScript.hash }] : undefined;
// Get the number of open issues
scriptOpenIssueCountQuery = Discussion.find({ category: exports
.caseSensitive(decodeURIComponent(script.issuesCategorySlug), true), open: {$ne: false} });
tasks.push(countTask(scriptOpenIssueCountQuery, meta.OpenUserJS.issues[0], 'value'));
async.parallel(tasks, asyncComplete);
} else {
// Create a based representation of the hex sha512sum
eTag = '"' + Base62.encode(parseInt('0x' + aScript.hash, 16)) + ' .meta.js"';
// If already client-side... HTTP/1.1 Caching
if (aReq.get('if-none-match') === eTag) {
aRes.status(304).send(); // Not Modified
return;
}
// Okay to send .meta.js...
aRes.set('Content-Type', 'text/javascript; charset=UTF-8');
// HTTP/1.0 Caching
aRes.set('Expires', moment(moment() + maxAge * 1000).utc()
.format('ddd, DD MMM YYYY HH:mm:ss') + ' GMT');
// HTTP/1.1 Caching
aRes.set('Etag', eTag);
aRes.write('// ==UserScript==\n');
if (meta.UserScript.version) {
aRes.write('// @version' + whitespace + meta.UserScript.version[0].value + '\n');
}
Object.keys(meta.UserScript.name).forEach(function (aName) {
var key = meta.UserScript.name[aName].key || 'name';
var value = meta.UserScript.name[aName].value;
aRes.write('// @' + key + whitespace + value + '\n');
});
if (meta.UserScript.namespace) {
aRes.write('// @namespace' + whitespace + meta.UserScript.namespace[0].value + '\n');
}
aRes.write('// ==/UserScript==\n');
aRes.end();
}
});
};
function findMeta(aMeta, aQuery) {
var header = aMeta;
var headers = null;
aQuery.split('.').forEach(function (aElement, aIndex, aArray) {
if (header && header[aElement] !== undefined ) {
header = header[aElement];
} else if (header && Array.isArray(header)) {
headers = [];
header.forEach(function(aElement2, aIndex2, aArray2) {
if (headers && header[aIndex2][aElement] !== undefined) {
headers.push(header[aIndex2][aElement]);
} else {
headers = null;
}
});
header = headers;