-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
818 lines (687 loc) · 21.1 KB
/
client.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
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { readAll } from "https://deno.land/[email protected]/io/read_all.ts";
import { Status } from "https://deno.land/[email protected]/http/http_status.ts";
import * as path from "https://deno.land/[email protected]/path/mod.ts";
import { typeByExtension } from "https://deno.land/[email protected]/media_types/type_by_extension.ts";
import { walk } from "https://deno.land/std/fs/mod.ts";
import sortPaths from "https://esm.sh/sort-paths"
import { existsSync } from "https://deno.land/[email protected]/fs/exists.ts";
import { DOMParser } from "https://esm.sh/linkedom";
import { Podcast } from 'npm:podcast';
import { render } from "@sillonious/saga"
import { doingBusinessAs } from "@sillonious/brand"
import { marked } from "marked"
import { config } from "https://deno.land/x/dotenv/mod.ts";
config()
function safeEnv(key) {
const value = Deno.env.get(key)
return value ? `${key}: "${value}",` : ''
}
const terminalHeaders = {
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin',
}
// polyfill window with DOMParser for deno;
self.DOMParser = DOMParser
const command = Deno.args[0];
const commands = {
link,
unlink
}
async function link(pkg) {
const dom = await page()
console.log('should install to the importmap of index.html')
const list = dom.querySelector('[type="importmap"]').innerHTML
console.log(pkg, list)
}
async function unlink(pkg) {
const dom = await page()
console.log('should uninstall from the importmap of index.html')
const list = dom.querySelector('[type="importmap"]').innerHTML
console.log(pkg, list)
}
if(commands[command]) {
const food = Deno.args[1];
await commands[command](Deno.args[1])
console.log(`Running as ${command}, I like ${food}!`);
Deno.exit();
}
async function page() {
const index = await Deno.readTextFile(`./client/public/index.html`)
const dom = new DOMParser().parseFromString(index, "text/html");
dom.head.insertAdjacentHTML('beforeend', `
<script>
self.plan98 = {
env: {
${safeEnv('PLAN98_USERNAME')}
${safeEnv('PLAN98_PASSWORD')}
${safeEnv('ADYEN_API_KEY')}
${safeEnv('ADYEN_MERCHANT_ACCOUNT')}
${safeEnv('ADYEN_CLIENT_KEY')}
${safeEnv('ADYEN_HMAC_KEY')}
${safeEnv('BUTTONDOWN_TOKEN')}
${safeEnv('SUPABASE_URL')}
${safeEnv('SUPABASE_KEY')}
${safeEnv('S3_COMPAT_ACCESS_KEY')}
${safeEnv('S3_COMPAT_SECRET_KEY')}
${safeEnv('S3_COMPAT_ENDPOINT')}
${safeEnv('S3_COMPAT_BUCKET')}
${safeEnv('VAULT_APP_ID')}
${safeEnv('VAULT_APP_SECRET')}
${safeEnv('VAULT_APP_SALT')}
${safeEnv('VAULT_BASE_URL')}
${safeEnv('VAULT_PUBLIC_KEY')}
${safeEnv('BRAID_TEXT_PROXY')}
${safeEnv('STATEBUS_PROXY')}
${safeEnv('POCKETBASE_URL')}
${safeEnv('HEAVY_ASSET_CDN_URL')}
${safeEnv('PLAN98_HOME')}
${safeEnv('PROTOMAPS_API_KEY')}
${safeEnv('FASTMAIL_API_KEY')}
${safeEnv('JITSI_MAGIC_COOKIE')}
${safeEnv('SOLID_URL')}
}
}
</script>
`)
return dom
}
async function markdownSanitizer(md, { endOfHead }) {
const dom = await page()
if(endOfHead) {
dom.head.insertAdjacentHTML('beforeend', endOfHead)
}
dom.getElementById('main').remove()
dom.body.insertAdjacentHTML('afterbegin', `
<scroll-container>
<markdown-styles>
${marked(md)}
</markdown-styles>
</scroll-container>
`)
return `<!DOCTYPE html>${dom.documentElement}`
}
async function sagaSanitizer(saga, { endOfHead, parameters }) {
const dom = await page()
if(endOfHead) {
dom.head.insertAdjacentHTML('beforeend', endOfHead)
}
let attributes = ''
if(parameters) {
attributes = Object.keys(parameters).map(x => `${x}=${parameters[x]}`).join(' ')
}
// remove the lazy-bootstrap to lock the document
//dom.getElementById('lazy-bootstrap').remove()
const main = dom.getElementById('main')
main.parentNode.insertAdjacentHTML('afterbegin', `
<sillonious-brand ${attributes}>
${render(saga)}
</sillonious-brand>
`)
main.remove()
return `<!DOCTYPE html>${dom.documentElement}`
}
const sanitizers = {
'.saga': sagaSanitizer,
'.md': markdownSanitizer,
}
const dynamicExtensions = {
'.md': {
raw: 'text/plain',
rich: 'text/html',
},
}
const contentTypes = {
}
function contentType(pathname, extension) {
const type = pathname.startsWith('/public/') ? 'raw' : 'rich'
if(contentTypes[extension]) {
return contentTypes[extension]
}
return dynamicExtensions[extension]
? dynamicExtensions[extension][type]
: typeByExtension(extension)
}
function buildHeaders(parameters, pathname, extension) {
const debug = parameters.get('debug')
let headers = {
'Cross-Origin-Resource-Policy': 'same-origin',
'content-type': contentType(pathname, extension)
}
if(debug === 'true') {
headers = {
...headers,
...terminalHeaders
}
}
return headers
}
const USERNAME = "user";
const PASSWORD = "password";
// Helper function to decode the base64 credentials from the Authorization header
function parseBasicAuth(header) {
const regex = /^Basic (.+)$/;
const match = header.match(regex);
if (!match) return null;
const base64Credentials = match[1];
const decodedCredentials = atob(base64Credentials);
const [username, password] = decodedCredentials.split(":", 2);
return [username, password];
}
async function router(request, context) {
// only require authorization if we have a username
if(Deno.env.get('PLAN98_USERNAME')) {
const authHeader = request.headers.get("Authorization");
if (!authHeader) {
return new Response("Unauthorized", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Secure Area"',
},
});
}
const [username, password] = parseBasicAuth(authHeader) || [];
// Check if the credentials match the expected ones
if (!(username === Deno.env.get('PLAN98_USERNAME') && password === Deno.env.get('PLAN98_PASSWORD'))) {
return new Response("Unauthorized", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Secure Area"',
},
});
}
}
const { pathname, host, search } = new URL(request.url);
const parameters = new URLSearchParams(search)
const world = parameters.get('world') || host || 'sillyz.computer'
const business = doingBusinessAs[world] || {}
const extension = path.extname(pathname);
const headers = buildHeaders(parameters, pathname, extension);
let file
let statusCode = Status.Success
if(request.method === 'POST') {
const data = await request.json()
if(pathname === '/plan98/subscribe') {
return ResponseData({ subscribe: await createEmailSubscriber(data) })
}
if(pathname === '/plan98/pay-by-link') {
return data.mode === 'CREATE'
? ResponseData({ payment: await newPayment(data) })
: ResponseData({ payment: await getPaymentStatus(data) })
}
try {
const segments = data.src.split('/')
const shortPath = segments.slice(0, -1).join('/')
await Deno.mkdir(`./client/` + shortPath, { recursive: true });
await Deno.writeTextFile(`./client${data.src}`, data.file, {create: true})
return new Response(JSON.stringify({ ok: 'ok' }, null, 2), {
headers: { "content-type": "application/json; charset=utf-8" },
status: 200
});
} catch (error) {
console.error(error)
return new Response(JSON.stringify({ error }, null, 2), {
headers: { "content-type": "application/json; charset=utf-8" },
status: 400
});
}
}
if(pathname === '/') {
const file = await home(request, business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
// temporary workaround for go live
if(pathname === '/weird-variety') {
const file = await showApp(request, 'weird-variety', business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
if(pathname === '/admin') {
const file = await showApp(request, 'enterprise-dashboard', business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
if(pathname.startsWith('/app/')) {
const [app] = pathname.split('/app/')[1].split('/')
const file = await showApp(request, app, business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
if(pathname.startsWith('/9/')) {
const src = '/' + pathname.split('/9/')[1] + '?' + parameters.toString().replace('%2F', '/')
const file = await remix(request, { src, tag: 'plan9-zune' }, business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
if(pathname.startsWith('/98/')) {
const src = '/' + pathname.split('/98/')[1] + '?' + parameters.toString().replace('%2F', '/')
const file = await remix(request, { src, tag: 'plan98-intro' }, business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
if(pathname.startsWith('/x/iphone/')) {
const src = '/' + pathname.split('/x/iphone/')[1] + '?' + parameters.toString().replace('%2F', '/')
const file = await remix(request, {
src,
tag: 'proto-type',
attributes: 'class="iphone"'
}, business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
if(pathname.startsWith('/x/watch/')) {
const src = '/' + pathname.split('/x/watch/')[1] + '?' + parameters.toString().replace('%2F', '/')
const file = await remix(request, {
src,
tag: 'proto-type',
attributes: 'class="timemachine"'
}, business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
if(pathname.startsWith('/x/elf/')) {
const src = '/' + pathname.split('/x/elf/')[1] + '?' + parameters.toString().replace('%2F', '/')
const file = await remix(request, {
src,
tag: 'generic-park',
}, business)
if(file) {
return new Response(file, {
headers,
status: statusCode
})
}
}
if(pathname === '/news.xml') {
const feed = new Podcast({
title: 'title',
description: 'description',
feedUrl: 'http://example.com/rss.xml',
siteUrl: 'http://example.com',
imageUrl: 'http://example.com/icon.png',
docs: 'http://example.com/rss/docs.html',
author: 'Dylan Greene',
managingEditor: 'Dylan Greene',
webMaster: 'Dylan Greene',
copyright: '2013 Dylan Greene',
language: 'en',
categories: ['Category 1','Category 2','Category 3'],
pubDate: 'May 20, 2012 04:00:00 GMT',
ttl: 60,
itunesAuthor: 'Max Nowack',
itunesSubtitle: 'I am a sub title',
itunesSummary: 'I am a summary',
itunesOwner: { name: 'Max Nowack', email: '[email protected]' },
itunesExplicit: false,
itunesCategory: [{
text: 'Entertainment',
subcats: [{
text: 'Television'
}]
}],
itunesImage: 'http://example.com/image.png'
});
/* loop over data and add to feed */
feed.addItem({
title: 'item title',
description: '<ul><li>aw, yiss</li><li>aw, yiss</li><li>yee haw</li></ul>',
url: 'http://example.com/article4?this&that', // link to the item
guid: '1123', // optional - defaults to url
categories: ['Category 1','Category 2','Category 3','Category 4'], // optional - array of item categories
author: 'Guest Author', // optional - defaults to feed author property
date: 'May 27, 2012', // any format that js Date can parse.
lat: 33.417974, //optional latitude field for GeoRSS
long: -111.933231, //optional longitude field for GeoRSS
itunesAuthor: 'Max Nowack',
itunesExplicit: false,
itunesSubtitle: 'I am a sub title',
itunesSummary: 'I am a summary',
itunesDuration: 12345,
itunesNewFeedUrl: 'https://newlocation.com/example.rss',
});
let xml
try {
xml = feed.buildXml();
const stylesheetPI = '<?xml-stylesheet type="text/xsl" href="news.xsl"?>';
xml = xml.replace(/<\?xml version="1.0" encoding="UTF-8"\?>/, `$&\n${stylesheetPI}`);
} catch(e) {
console.error(e)
}
// Set content type as XML
const headers = new Headers();
headers.set("Content-Type", "text/xml");
return new Response(xml, { headers });
}
if(pathname === '/plan98/about') {
return about(headers, request)
}
if(pathname === '/plan98/mp3s') {
return mp3s(headers, request)
}
if(pathname === '/plan98/owncast') {
return owncast(headers, request)
}
try {
if(existsSync(`./client/${pathname}`, { isFile: true })) {
file = await Deno.readFile(`./client/${pathname}`)
return new Response(file, {
headers,
status: statusCode
})
}
} catch (e) {
console.error(e)
}
try {
if(sanitizers[extension]) {
file = await Deno.readTextFile(`./client/public${pathname}`)
file = await sanitizers[extension](file, business)
} else {
file = await Deno.readFile(`./client/public${pathname}`)
}
} catch (e) {
let file
if(pathname.startsWith('/public/')) {
file = await Deno.readTextFile(`./client/public/404.saga`)
} else {
const saga = await Deno.readTextFile(`./client/public/404.saga`)
file = await sagaSanitizer(saga, {
...business,
})
}
statusCode = Status.NotFound
console.error(e + '\n' + pathname + '\n' + e)
return new Response(file, {
headers: { ...headers },
status: statusCode
})
}
return new Response(file, {
headers,
status: statusCode
})
}
const byPath = (x) => x.path
const byName = (x) => x.name
async function home(request, business) {
console.log(request)
if(business.page) {
let file
try {
console.log(business.page)
file = await Deno.readTextFile(`./client${business.page}`)
.catch(console.error)
} catch (e) {
console.error(e + '\n' + pathname + '\n' + e)
}
return file
}
if(!business.saga) {
const dom = await page()
return `<!DOCTYPE html>${dom.documentElement}`
}
let file
try {
const { saga } = business
file = await Deno.readTextFile(`./client/${saga}`)
file = await sanitizers['.saga'](file, business)
} catch (e) {
console.error(e + '\n' + pathname + '\n' + e)
}
return file
}
async function showApp(request, tag, { endOfHead }) {
const url = new URL(request.url)
let attributes = ''
for(const p of url.searchParams) {
attributes += `${[p[0]]}="${p[1]}"`
}
const dom = await page()
if(endOfHead) {
dom.head.insertAdjacentHTML('beforeend', endOfHead)
}
const main = dom.getElementById('main')
main.parentNode.insertAdjacentHTML('afterbegin', `
<sillonious-brand>
<${tag} ${attributes}></${tag}>
</sillonious-brand>
`)
main.remove()
return `<!DOCTYPE html>${dom.documentElement}`
}
async function remix(request, { src, tag, attributes=''}, { endOfHead }) {
const dom = await page()
if(endOfHead) {
dom.head.insertAdjacentHTML('beforeend', endOfHead)
}
const main = dom.getElementById('main')
main.parentNode.insertAdjacentHTML('afterbegin', `
<sillonious-brand>
<${tag} src="${src}" ${attributes}></${tag}>
</sillonious-brand>
`)
main.remove()
return `<!DOCTYPE html>${dom.documentElement}`
}
async function about(headers, request) {
const { search } = new URL(request.url);
const parameters = new URLSearchParams(search)
const world = parameters.get('world')
if(world) {
const data = await fetch('https://'+world+'/plan98/about').then(res => res.json())
return new Response(JSON.stringify(data, null, 2), {
headers: {
...headers,
"content-type": "application/json; charset=utf-8"
},
});
} else {
let paths = []
const currentPath = Deno.cwd() + '/client'
const files = walk(currentPath, {
skip: [
/\.git/,
/\.autosave/,
/\.swp/,
/\.swo/,
/\.env/,
/node_modules/,
/backup/,
/db/
],
includeDirs: true,
})
for await(const file of files) {
const { name } = file
const [_, path] = file.path.split(currentPath)
paths.push({ path, name, isDirectory: file.isDirectory })
}
paths = sortPaths([...paths], byPath, '/')
const data = {
plan98: {
type: 'FileSystem',
children: [kids(paths)]
}
}
return new Response(JSON.stringify(data, null, 2), {
headers: {
...headers,
"content-type": "application/json; charset=utf-8"
},
});
}
}
async function mp3s(headers, request) {
const { search } = new URL(request.url);
const parameters = new URLSearchParams(search)
const world = parameters.get('world')
if(world) {
const data = await fetch('https://'+world+'/plan98/about').then(res => res.json())
return new Response(JSON.stringify(data, null, 2), {
headers: {
...headers,
"content-type": "application/json; charset=utf-8"
},
});
} else {
let paths = []
const currentPath = Deno.cwd() + '/client'
const files = walk(currentPath, {
skip: [
/\.git/,
/\.autosave/,
/\.swp/,
/\.swo/,
/\.env/,
/node_modules/,
/backup/,
/db/
],
includeDirs: false
})
for await(const file of files) {
const { name } = file
const [_, path] = file.path.split(currentPath)
if(name.endsWith('.mp3')) {
paths.push({ path, name })
}
}
paths = sortPaths([...paths], byPath, '/')
const data = {
plan98: {
type: 'FileSystem',
children: [kids(paths)]
}
}
return new Response(JSON.stringify(data, null, 2), {
headers: {
...headers,
"content-type": "application/json; charset=utf-8"
},
});
}
}
function ResponseData(data) {
return new Response(JSON.stringify(data, null, 2), {
headers: { "content-type": "application/json; charset=utf-8" },
});
}
async function owncast(headers, request) {
const onlinePromise = fetch('https://94404-969-g-edgewater-blvd-123.thelanding.page/api/status').then(res => res.json())
const data = { broadcast: await onlinePromise }
return new Response(JSON.stringify(data, null, 2), {
headers: {
...headers,
"content-type": "application/json; charset=utf-8"
},
});
}
function kids(paths) {
const root = { name: '', path: '/', type: 'Directory', children: [] };
for (const system of paths) {
const [_, ...pathComponents] = system.path.split('/');
let currentNode = root;
for (const component of pathComponents) {
if (!currentNode.children) {
currentNode.children = [];
}
let childNode = currentNode.children.find(node => node.name === component);
if (!childNode) {
childNode = { path: system.path, name: component, type: 'Directory', children: [] };
currentNode.children.push(childNode);
}
currentNode = childNode;
}
currentNode.type = system.isDirectory ? 'Directory' : 'File';
delete currentNode.children
}
return root;
}
serve(router);
console.log("Listening on http://localhost:8000");
async function createEmailSubscriber(data) {
const response = await fetch('https://api.buttondown.email/v1/subscribers', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token ' + Deno.env.get('BUTTONDOWN_TOKEN'),
},
body: JSON.stringify({
"email": data.email,
})
}).then( response => response.text())
try {
return JSON.parse(response)
} catch(e) {
return { error: e, note: 'Failed to parse response...' }
}
}
async function newPayment(data) {
const response = await fetch('https://checkout-test.adyen.com/v70/paymentLinks', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-API-key': Deno.env.get('ADYEN_API_KEY'),
},
body: JSON.stringify({
"reference": data.reference,
"amount": data.amount,
"shopperReference": data.shopperReference,
"description": data.description,
"countryCode": data.countryCode,
"merchantAccount": Deno.env.get('ADYEN_MERCHANT_ACCOUNT'),
"shopperLocale": data.shopperLocale
})
}).then( response => response.text())
try {
return JSON.parse(response)
} catch(e) {
return { error: e, note: 'Failed to parse response...' }
}
}
async function getPaymentStatus(data) {
const response = await fetch(`https://checkout-test.adyen.com/v68/paymentLinks/${data.id}`, {
headers: {
'Content-Type': 'application/json',
'x-API-key': Deno.env.get('ADYEN_API_KEY'),
}
}).then(res => res.text())
try {
return JSON.parse(response)
} catch(e) {
return { error: e, note: 'Failed to parse response...' }
}
}