forked from BrowserBox/BrowserBox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
792 lines (723 loc) · 21.6 KB
/
index.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
#!/usr/bin/env node
'use strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import url from 'url';
import childProcess from 'child_process';
import http from 'http';
import https from 'https';
import helmet from 'helmet';
import compression from 'compression';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import rateLimit from 'express-rate-limit';
import csrf from 'csurf';
import express from 'express';
import exitOnEpipe from 'exit-on-epipe';
import {WebSocket,WebSocketServer} from 'ws';
import {Reader,Writer} from '@dosy/wav';
import {
DEBUG as APP_DEBUG, APP_ROOT, GO_SECURE,
COOKIENAME, ALLOWED_3RD_PARTY_EMBEDDERS,
CONFIG
} from '../../../common.js';
const DEBUG = {
showAllData: false,
showDroppedSilents: false,
showPrimeFilter: false,
showPrimeChecks: false,
showAllMessages: false,
showAcks: false,
showConnections: true,
val: 1,
showFormat: true,
mode: 'dev',
goSecure: true
}
const Clients = new Set();
const sockets = new Set();
const SAMPLE_RATE = DEBUG.windowsUses48KAudio && process.platform.startsWith('win') ? 48000 : 44100;
const FORMAT_BIT_DEPTH = 16;
const BYTE_ALIGNMENT = FORMAT_BIT_DEPTH >> 3;
const MAX_DATA_SIZE = 1200; //SAMPLE_RATE * (FORMAT_BIT_DEPTH/8) // we actually only get around 300 bytes per chunk on average, ~ 3 msec;
const CutOff = {};
const primeCache = [2, 3, 5];
let Encoders = new Set();
let primeSet = new Set(primeCache);
const SparsePrimes = createSparsePrimes(MAX_DATA_SIZE);
const argv = process.argv;
let device = argv[3] || 'rtp.monitor' || 'auto_null.monitor';
const encoders = {
mp3: {
contentType: 'audio/mpeg',
command: 'lame',
/*args: ['-S', '--noreplaygain', '-f', '-r', '-B', '20', '-', '-'],*/
args: ['-S', '-r', '-', '-']
},
wav: {
contentType: 'audio/wav',
...(process.env.TORBB ? {
command: () => new Writer({
endianness: 'LE',
sampleRate: SAMPLE_RATE,
bitDepth: FORMAT_BIT_DEPTH,
channels: 1
}),
} : {})
},
flac: {
contentType: 'audio/flac',
command: 'flac',
args: [
'-0',
'--endian=little',
'--sign=signed',
`--sample-rate=${SAMPLE_RATE}`,
`--bps=${FORMAT_BIT_DEPTH}`,
'--channels=2',
'--silent',
'-'
]
}
};
const encoderType = process.env.TORBB ? 'wav' : 'wav';
var hooks = 0;
let parec = undefined;
let savedEncoder;
let encoderExpiration;
const ENCODER_EXPIRY_MS = 13*60*1000; // shut down encoder after 13 minutes of nobody listening
const SSL_OPTS = {};
const COOKIE_OPTS = {
secure: true,
httpOnly: true,
maxAge: 345600000,
sameSite: 'None'
};
const RateLimiter = rateLimit({
windowMs: 1000 * 60 * 3,
max: DEBUG.mode == 'dev' ? 10000 : 2000
});
function maybeStartEncoderExpiryClock(client) {
Clients.delete(client);
hooks--;
if (hooks > 0) return;
DEBUG.val && console.log(`Starting encoder expiration clock`);
encoderExpiration = setTimeout(killAudio, ENCODER_EXPIRY_MS);
}
function killAudio() {
DEBUG.val && console.log('killing encoder because nobody is listening');
for( let encoder of Encoders.values()) {
try {
encoder?.kill?.('SIGINT');
encoder?.parec?.kill?.('SIGINT');
} catch(e) {
console.warn('error killing encoder', e, encoder);
}
}
Encoders = new Set();
}
function stopEncoderExpiryClock(client) {
DEBUG.val && console.log(`Stopping encoder expiration clock`);
Clients.add(client);
hooks++;
clearTimeout(encoderExpiration);
encoderExpiration = false;
}
const port = parseInt(argv[2]);
const PORT = port;
const COOKIE = process.argv[4];
const TOKEN = process.argv[5];
DEBUG.val && console.log('starting http server on port', port);
console.log({ALLOWED_3RD_PARTY_EMBEDDERS});
let certsFound = false;
if ( DEBUG.goSecure ) {
try {
Object.assign(SSL_OPTS, {
key: fs.readFileSync(path.resolve(os.homedir(), CONFIG.sslcerts(port), 'privkey.pem')),
cert: fs.readFileSync(path.resolve(os.homedir(), CONFIG.sslcerts(port), 'fullchain.pem')),
ca: fs.existsSync(path.resolve(os.homedir(), CONFIG.sslcerts(port), 'chain.pem')) ?
fs.readFileSync(path.resolve(os.homedir(), CONFIG.sslcerts(port), 'chain.pem'))
:
undefined
});
certsFound = true;
} catch(e) {
DEBUG.err && console.warn(e);
}
DEBUG.val && console.log(SSL_OPTS, {GO_SECURE});
console.log(SSL_OPTS, {GO_SECURE}, path.resolve(os.homedir(), CONFIG.sslcerts(port), 'privkey.pem'));
}
const MODE = certsFound ? https: http;
const app = express();
let shuttingDown = false;
let audioProcessShuttingDown = false;
app.set('etag', false);
if ( ! APP_DEBUG.noSecurityHeaders ) {
app.use(helmet({
frameguard: false,
crossOriginResourcePolicy: { policy: "cross-origin" },
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
imgSrc: [
"'self'",
"data:",
"blob:"
],
mediaSrc: [
"'self'",
"https://link.local:*",
"https://localhost:*",
"https://*.dosyago.com:*",
"https://*.browserbox.pro:*"
],
frameSrc: [
"'self'",
`https://*.dosyago.com:${PORT+1}`,
`https://*.dosyago.com:${PORT+2}`,
`https://*.dosyago.com:${PORT+3}`,
"https://*.browserbox.pro:*",
...ALLOWED_3RD_PARTY_EMBEDDERS
],
frameAncestors: [
"'self'",
"https://localhost:*",
"https://link.local:*",
"https://*.dosyago.com:*",
"https://*.browserbox.pro:*",
...ALLOWED_3RD_PARTY_EMBEDDERS
],
connectSrc: [
"'self'",
"wss://*.link.local:*",
`https://*.link.local:${PORT+1}`,
"wss://*.dosyago.com:*",
`https://*.dosyago.com:${PORT+1}`,
"wss://*.browserbox.pro:*",
`https://${process.env.DOMAIN}:*`, // main service (for data: urls seemingly)
`wss://${process.env.DOMAIN}:*`, // main service (for data: urls seemingly)
],
styleSrc: [
"'self'",
"'unsafe-inline'"
],
scriptSrc: [
"'self'",
"'unsafe-eval'",
"'sha256-ktnwD9kIpbxpOmbTg7NUsKRlpicCv8bryYhIbiRDFaQ='",
],
objectSrc: ["'none'"],
upgradeInsecureRequests: [],
},
reportOnly: false,
}
}));
} else {
app.use(cors());
}
app.use(compression({
level: 4
}));
app.use(RateLimiter);
app.use(express.urlencoded({extended:true}));
app.use(cookieParser());
app.use(csrf({cookie:{sameSite:'None', secure:true}}));
const staticPath = path.resolve(APP_ROOT, 'services', 'instance', 'parec-server', 'public');
const serverPath = path.resolve(APP_ROOT, 'services', 'instance', 'parec-server');
console.log({staticPath});
app.use(express.static(staticPath));
app.use((req,res,next) => {
res.set('Cache-Control', 'no-store');
next();
});
app.get('/login', (req, res) => {
res.type('html');
const {token} = req.query;
const cookie = req.cookies[COOKIENAME+PORT];
let loggedIn = false;
if ( token == TOKEN ) {
res.cookie(COOKIENAME+PORT, COOKIE, COOKIE_OPTS);
loggedIn = true;
} else if ( cookie == COOKIE ) {
loggedIn = true;
}
if ( loggedIn ) {
res.end(`
<!DOCTYPE html>
<script src=request_audio.js></script>
`);
} else {
res.end(`
<!DOCTYPE html>
<script src=request_login.js></script>
`);
}
});
if ( process.env.TORBB ) {
app.get('/', async (request, response) => {
const {token} = request.query;
const cookie = request.cookies[COOKIENAME+PORT];
if ( token == TOKEN || cookie == COOKIE ) {
var contentType = encoders[encoderType].contentType;
DEBUG.val && console.log(' setting Content-Type to', contentType);
response.writeHead(200, {
'Connection': 'keep-alive',
'Content-Type': contentType
});
const enc = await getEncoder();
let unpipe;
if ( enc?.stdout ) {
DEBUG.val && console.log('Setting encoder stdout to pipe');
enc.stdout.pipe(response);
unpipe = () => enc.stdout.unpipe(resopnse);
} else if ( enc?.pipe ) {
DEBUG.val && console.log('Setting encoder to pipe');
enc.pipe(response);
unpipe = () => enc.unpipe(response);
} else {
console.warn(`Encoder has no stdout or pipe properties`);
}
exitOnEpipe(response);
request.on('close', function() {
DEBUG.val && console.log('Request closing');
try {
unpipe();
if ( process.env.TORBB ) {
killEncoder(enc);
}
} catch(e) {
console.warn(`Error on unpipe at end of request / resopnse`);
}
response.end();
});
} else {
response.sendStatus(401);
}
});
}
const server = MODE.createServer(SSL_OPTS, app);
const socketWaveStreamer = new WebSocketServer({
server,
perMessageDeflate: false,
});
socketWaveStreamer.on('connection', async (ws, req) => {
cookieParser()(req, {}, () => console.log('cookie parsed'));
const cookie = req.cookies[COOKIENAME+PORT];
console.log({cookie});
if ( cookie == COOKIE ) {
console.log('auth');
} else {
console.log('Audio: closing as not authorized');
ws.send("closing as not authorized");
ws.close();
return;
}
const client = {
ACK_VALUE: 3,
DATA_SIZE: SAMPLE_RATE,
BUF_WINDOW: 4,
ackReceived: 0,
firstAck: true,
buffer: [],
packet: [],
ip: `${ws?._socket?.remoteAddress}:${ws?._socket?.remotePort}`,
};
stopEncoderExpiryClock(client);
DEBUG.showConnections && console.log(`Now have ${Clients.size} clients`, Clients);
try {
DEBUG.val && console.log('ws (wave header + pcm stream) connection (server #2)');
const reader = (await getEncoder()).stdout;
ws.send("give me ack");
let totalLength = 0;
const processData = data => {
DEBUG.showAllData && console.log(`Got data with length`, data.length);
if ( CONFIG.audioDropPossiblySilentFrames && isSilent(data) ) {
DEBUG.showDroppedSilents && console.log('drop', data.length, data);
client.packet.length = 0;
totalLength = 0;
client.buffer.length = 0;
return;
}
totalLength += data.length;
client.packet.push(data);
if ( totalLength >= client.DATA_SIZE ) {
const misAlignment = totalLength % BYTE_ALIGNMENT;
let packet = Buffer.concat(client.packet, totalLength);
client.packet.length = 0;
if ( misAlignment != 0 ) {
const remainder = packet.subarray(totalLength, misAlignment);
totalLength -= misAlignment;
packet = packet.subarray(0, totalLength);
client.packet.push(remainder);
totalLength = misAlignment;
} else {
totalLength = 0;
}
client.buffer.push(packet);
console.log(`Pushing packet length: ${packet.length}`);
}
while ( client.buffer.length > client.BUF_WINDOW ) {
client.buffer.shift();
}
if ( client.buffer.length && client.ackReceived && ws.readyState < WebSocket.CLOSING ) {
DEBUG.showAllData && console.log(`sending`, Array.from(data).join(' '), 'silent?', isSilent(data));
ws.send(client.buffer.shift());
client.ackReceived--;
}
};
reader.on('data', processData);
function isSilent(data) {
return data[0] === 0 && data[data.length-1] === 0 && checks(data);
}
function checks(dat) {
const sz = dat.length;
if ( sz < 3 ) return true;
const pr = SparsePrimes.slice(0, CutOff[sz]);
const P = pr.length;
DEBUG.showPrimeChecks && console.log(
"miss end by", dat.length - 1 - pr[pr.length-1], "last dat at", dat.length - 1, "last check at", pr[pr.length-1]
);
for(let i = 0, p; i < P; i++) {
p = pr[i];
if ( dat[p] !== 0 ) {
DEBUG.showPrimeChecks && console.log({p, datp: dat[p], p, len: dat.length});
return false;
}
}
return true;
}
ws.on('open', () => {
client.packet.length = 0;
totalLength = 0;
client.buffer.length = 0;
});
ws.on('message', async msg => {
msg = msg.toString();
DEBUG.showAllMessages && console.log(msg);
if ( msg === "ack" ) {
DEBUG.showAcks && console.log(`Ack received`);
if ( client.isFirstAck ) {
client.firstAck = false;
client.packet.length = 0;
totalLength = 0;
client.buffer.length = 0;
console.log("first ack", true, client.ackReceived);
}
client.ackReceived = client.ACK_VALUE;
while ( client.ackReceived && client.buffer.length && ws.readyState < WebSocket.CLOSING ) {
DEBUG.val && console.log(`sending`, client.buffer[0]);
ws.send(client.buffer.shift());
client.ackReceived--;
}
} else if ( msg === "stop" ) {
/*
client.packet.length = 0;
totalLength = 0;
client.buffer.length = 0;
*/
}
});
ws.on('error', err => console.warn('WebSocket error', err));
ws.on('close', info => {
console.log(`WebSocket closing`, info);
reader.off('data', processData);
maybeStartEncoderExpiryClock(client);
client.packet.length = 0;
totalLength = 0;
client.buffer.length = 0;
});
} catch(e) {
console.warn(e);
}
});
server.on('connection', function(socket) {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
DEBUG.showConnections && console.log('New http connection: setting no delay true');
socket.setNoDelay(true);
});
server.on('upgrade', (req, socket, head) => {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
console.log('http upgrade');
const {pathname} = url.parse(req.url);
switch(pathname) {
case "/stream": {
if ( process.env.TORBB ) { // reject all audio websocket connections in TOR
console.log('Destroying socket as tor mode cannot use webaudio for streaming, need a raw (and laggy) audio tag only)', pathname);
sockets.delete(socket);
socket.destroy();
}
}; break;
default: {
console.log('Destroying socket as wrong path', pathname);
sockets.delete(socket);
socket.destroy();
}; break;
}
});
server.listen(port);
if ( ! process.platform.startsWith('win') ) {
try {
childProcess.execSync(`sudo renice -n ${CONFIG.reniceValue} -p ${process.pid}`);
} catch(e) {
console.info(e);
console.warn(`Could not renice node audio service`);
}
}
console.warn('Shut down buries errors');
//process.on('SIGINT', shutDown);
//process.on('SIGUSR2', shutDown);
//process.on('exit', shutDown);
async function getEncoder() {
audioProcessShuttingDown = false;
if (savedEncoder) return savedEncoder;
let encoder = undefined;
let parec = undefined;
DEBUG.val && console.log('starting encoder');
if ( process.platform == 'win32' ) {
try {
encoder = childProcess.spawn('fmedia.exe', [
`--channels=mono`, `--rate=44100`, `--format=int16`,
`--notui`,
`--record`,
`--dev-loopback=1`
]);
exitOnEpipe(encoder.stdout);
exitOnEpipe(encoder.stderr);
encoder.stderr.pipe(process.stdout);
encoder.on('error', e => {
console.log('encoder error', e);
killEncoder(encoder);
//shutDown();
});
encoder.on('close', e => {
console.log('encoder close', e);
killEncoder(encoder);
//shutDown();
});
encoder.on('exit', e => {
console.log('encoder exit', e);
killEncoder(encoder);
//shutDown();
});
if ( ! process.env.TORBB ) {
savedEncoder = encoder;
}
console.log(encoder);
return encoder;
} catch(e) {
console.warn(`error starting encoder`, e);
}
} else {
// Notes on args
/*
note that the following args break it or are unnecessary
'--fix-rate', // break
'--fix-format', // break
'--no-remix', // unknown if break or unnecessary
*/
const args = [
'-r', /* record: the default if run as parec */
`--rate=${SAMPLE_RATE}`,
`--format=s${FORMAT_BIT_DEPTH}le`,
'--channels=1',
'--process-time-msec=100',
'--latency-msec=100',
...(process.platform == 'darwin' ? [] : [
'-d', device
])
]
parec = childProcess.spawn('pacat', args);
parec.on('spawn', e => {
console.log('parec spawned', {error:e, pid: parec.pid, args: args.join(' ')});
if ( ! process.platform.startsWith('win') ) {
try {
childProcess.execSync(`sudo renice -n ${CONFIG.reniceValue} -p ${parec.pid}`);
console.log(`reniced parec`);
} catch(e) {
console.warn(`Error renicing parec`, e);
}
}
});
exitOnEpipe(parec.stdout);
exitOnEpipe(parec.stderr);
parec.stderr.pipe(process.stdout);
parec.on('error', e => {
console.log('parec error', e);
killEncoder(encoder);
//shutDown();
});
parec.on('close', e => {
console.log('parec close', e);
killEncoder(encoder);
//shutDown();
});
parec.on('exit', e => {
console.log('parec exit', e);
killEncoder(encoder);
//shutDown();
});
const encoderCommand = encoders[encoderType];
if ( typeof encoderCommand?.command === "string" ) {
encoder = childProcess.spawn(encoderCommand.command, encoderCommand.args);
encoder.parec = parec;
Encoders.add(encoder);
exitOnEpipe(encoder.stdout);
exitOnEpipe(encoder.stderr);
encoder.stderr.pipe(process.stdout);
encoder.on('error', e => {
console.log('encoder error', e);
killEncoder(encoder);
});
encoder.on('close', e => {
console.log('encoder close', e);
killEncoder(encoder);
});
encoder.on('exit', e => {
console.log('encoder exit', e);
killEncoder(encoder);
});
if ( ! process.platform.startsWith('win') ) {
try {
childProcess.execSync(`sudo renice -n ${CONFIG.reniceValue} -p ${encoder.pid}`);
} catch(e) {
console.warn(`Error renicing encoder.`, e);
}
}
parec.stdout.pipe(encoder.stdin);
if ( ! process.env.TORBB ) {
savedEncoder = encoder;
}
return encoder;
} else if ( typeof encoderCommand?.command === "function" ) {
encoder = encoderCommand.command();
encoder.parec = parec;
Encoders.add(encoder);
parec.stdout.pipe(encoder);
if ( ! process.env.TORBB ) {
savedEncoder = encoder;
}
return encoder;
} else {
encoder = parec;
if ( ! process.env.TORBB ) {
savedEncoder = parec;
}
return parec;
}
}
}
function killEncoder(encoder) {
console.log('killing encoder');
if ( encoder ) {
try {
encoder?.kill?.();
encoder?.parec?.kill?.();
Encoders.delete(encoder);
encoder = null;
} catch(e) {
console.log(`Error killing encoder`, e);
}
}
}
function audioProcessShutDown() {
if ( audioProcessShuttingDown ) return;
audioProcessShuttingDown = true;
for( let encoder of Encoders.values()) {
if ( encoder ) {
try {
encoder?.kill && encoder.kill();
encoder = null;
} catch(e) {
console.log(`Error killing encoder`, e);
}
}
}
Encoders = new Set();
if ( parec ) {
try {
parec?.kill && parec.kill();
parec = null;
} catch(e) {
console.log(`Error killing parec`, e);
}
}
}
function shutDown(...args) {
if ( shuttingDown ) return;
shuttingDown = true;
audioProcessShutDown();
server.close(() => console.info(`Server closed on ${[args].join(',')}`));
sockets.forEach(socket => {
try { socket.destroy(); sockets.delete(socket); } catch(e) {
DEBUG && console.warn(`MAIN SERVER: port ${port}, error closing socket`, e)
}
});
process.exit(0);
};
function createSparsePrimes(len) {
// take the primes up to len and then weed out 61.8 % of them
const primes = primesUpTo(len);
const filteredPrimes = primes.filter(() => Math.random() <= 0.618);
for(let j = 1, end = 0, p = filteredPrimes[0], nextP = filteredPrimes[1]; j < filteredPrimes.length && end < MAX_DATA_SIZE; end++) {
if ( end > nextP ) {
j++;
p = nextP;
nextP = filteredPrimes[j];
}
CutOff[end] = j;
}
DEBUG.showPrimeFilter && console.log(filteredPrimes.join(' '), CutOff);
return filteredPrimes;
}
/*
from my code:
https://github.com/crisdosyago/weird-json/blob/9f8868a68e523317b51f9ed1f328b4d52dd6ff58/src/prime-code/index.js
*/
function primesUpTo(n, beginning = 2) {
// return primes up to n, optionally starting at beginning
let fillCache = beginning == 2;
const primes = [];
let i = beginning;
while(i <= n) {
if ( isPrime(i) ) {
primes.push(i);
if ( fillCache && primes.length > primeCache.length ) {
primeCache.push(i);
}
}
i++;
}
primeSet = new Set(primeCache);
return primes;
}
function isPrime(n) {
if ( n === 2 || n === 3 ) return true;
let remainder = n % 2;
if ( remainder === 0 ) return false;
remainder = n % 3;
if ( remainder === 0 ) return false;
if ( primeSet.has(n) ) return true;
const maxFactor = Math.floor(Math.sqrt(n));
let primeIndex = 2;
let factor = primeCache[primeIndex]; // 5
while(factor <= maxFactor) {
remainder = n % factor;
if ( remainder === 0 ) return false;
primeIndex++;
if ( primeIndex < primeCache.length ) {
factor = primeCache[primeIndex];
} else {
const sixRemainder = factor % 6;
if ( sixRemainder === 5 ) {
factor += 2;
} else if ( sixRemainder === 1 ) {
factor += 4;
}
}
}
return true;
}