-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2490 lines (2261 loc) · 110 KB
/
Copy pathindex.js
File metadata and controls
2490 lines (2261 loc) · 110 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
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
// Cloudflare Worker — AIDEN AI proxy + Page View Counter + Audio Transcription
// Holds the API key securely on the server, never exposed to the browser
// Maintainers: Natalie Spiva (spivanatalie64), Darren Clift (cobra3282000)
// Website: https://acreetionos.org — contact via the project channels for AIDEN
// The worker proxies the site to OpenRouter server-side. Pollinations.ai support removed.
// This worker provides:
// GET /api/news — aggregates AcreetionOS news from GitHub, GitLab, and RSS, generates articles with AI
// POST /api/chat — server-side OpenRouter chat (free model)
// POST /api/transcribe — audio transcription via OpenRouter Whisper (free)
// GET /api/counter — returns current active user count
// POST /api/counter — increments and returns new count
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';
const WHISPER_URL = 'https://openrouter.ai/api/v1/audio/transcriptions';
const TTS_URL = 'https://openrouter.ai/api/v1/audio/speech';
// Use only explicitly free community models. Keep the values in one place.
const FREE_MODEL = 'openrouter/auto';
const WHISPER_MODEL = 'openai/whisper-large-v3';
const TTS_MODEL = 'cartesia-ai/cartesia-tts';
const ALLOWED_ORIGINS = [
'https://acreetionos.org',
'https://www.acreetionos.org',
'https://acreetionos-code.github.io',
'http://localhost:8080',
'http://localhost:3000',
'http://127.0.0.1:8080',
'http://127.0.0.1:3000'
];
function securityHeaders() {
return {
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload',
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://static.cloudflareinsights.com https://ajax.cloudflare.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com https://cdn.jsdelivr.net; connect-src 'self' https://api.github.com https://gitlab.acreetionos.org https://cloudflareinsights.com https://openrouter.ai; base-uri 'self'; form-action 'self' https://www.qwant.com"
};
}
function corsHeaders(request) {
const origin = request.headers.get('Origin') || '';
const allowed = ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0];
return {
'Access-Control-Allow-Origin': allowed,
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Content-Encoding, Authorization',
'Access-Control-Max-Age': '86400',
...securityHeaders()
};
}
let visitorCount = 0;
let lastPersistTime = 0;
const CACHE_KEY = 'https://acreetion-counter/count';
async function loadCount() {
try {
const cache = caches.default;
const cached = await cache.match(CACHE_KEY);
if (cached) {
const data = await cached.json();
visitorCount = data.count || 0;
}
} catch (e) {}
}
async function persistCount() {
try {
const cache = caches.default;
const response = new Response(JSON.stringify({ count: visitorCount, ts: Date.now() }), {
headers: { 'Content-Type': 'application/json', 'Cache-Control': 's-maxage=86400' }
});
// Don't await — fire and forget
cache.put(CACHE_KEY, response.clone());
} catch (e) {}
}
async function handleNews(env) {
const GH_ORG = 'AcreetionOS-Code';
const GL_URL = 'https://gitlab.acreetionos.org';
const RSS_FEEDS = [
'https://news.google.com/rss/search?q=%22AcreetionOS%22&hl=en-US&gl=US&ceid=US:en',
'https://news.google.com/rss/search?q=AcreetionOS+Arch+Linux&hl=en-US&gl=US&ceid=US:en',
'https://news.google.com/rss/search?q=Arch+Linux+news&hl=en-US&gl=US&ceid=US:en'
];
try {
const [gh, gl, rss] = await Promise.all([
(async () => {
try {
const reposRes = await fetch('https://api.github.com/orgs/' + GH_ORG + '/repos?per_page=5&sort=pushed');
if (!reposRes.ok) return [];
const repos = await reposRes.json();
const repoFetches = repos.slice(0, 3).map(repo =>
Promise.all([
fetch('https://api.github.com/repos/' + GH_ORG + '/' + repo.name + '/commits?per_page=2'),
fetch('https://api.github.com/repos/' + GH_ORG + '/' + repo.name + '/releases?per_page=1')
]).then(async ([commitsRes, releasesRes]) => {
const items = [];
if (commitsRes.ok) {
const commits = await commitsRes.json();
for (const c of commits) {
items.push({ type: 'commit', repo: repo.name, message: (c.commit.message || '').split('\n')[0], author: c.commit.author?.name || 'Unknown', date: c.commit.author?.date, url: c.html_url, source: 'GitHub' });
}
}
if (releasesRes.ok) {
const releases = await releasesRes.json();
for (const r of releases) {
items.push({ type: 'release', repo: repo.name, name: r.tag_name, desc: (r.body || '').split('\n')[0], date: r.published_at || r.created_at, url: r.html_url, source: 'GitHub' });
}
}
return items;
}).catch(() => [])
);
const nested = await Promise.all(repoFetches);
return nested.flat();
} catch (e) { return []; }
})(),
(async () => {
try {
const projectsRes = await fetch(GL_URL + '/api/v4/projects?per_page=5&order_by=last_activity_at');
if (!projectsRes.ok) return [];
const projects = await projectsRes.json();
const projFetches = projects.slice(0, 3).map(proj =>
fetch(GL_URL + '/api/v4/projects/' + proj.id + '/repository/commits?per_page=2')
.then(async (commitsRes) => {
const items = [];
if (commitsRes.ok) {
const commits = await commitsRes.json();
for (const c of commits) {
items.push({ type: 'commit', repo: proj.path_with_namespace || proj.name, message: c.title || c.message || '', author: c.author_name || 'Unknown', date: c.created_at, url: c.web_url || (GL_URL + '/' + proj.path_with_namespace + '/-/commit/' + c.id), source: 'GitLab' });
}
}
return items;
}).catch(() => [])
);
const nested = await Promise.all(projFetches);
return nested.flat();
} catch (e) { return []; }
})(),
(async () => {
const feedFetches = RSS_FEEDS.map(feedUrl =>
fetch(feedUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (compatible; AcreetionOS-News-Bot)' } })
.then(async (res) => {
if (!res.ok) return [];
const xml = await res.text();
const items = xml.match(/<item>[\s\S]*?<\/item>/gi) || [];
return items.slice(0, 4).map(item => {
const title = (item.match(/<title>(?:<!\[CDATA\[)?([^\]]*)(?:\]\]>)?<\/title>/) || [,''])[1].trim();
const link = (item.match(/<link>(?:<!\[CDATA\[)?([^\]]*)(?:\]\]>)?<\/link>/) || [,''])[1].trim();
const desc = (item.match(/<description>(?:<!\[CDATA\[)?([^\]]*)(?:\]\]>)?<\/description>/) || [,''])[1].trim().replace(/<[^>]+>/g, '').slice(0, 200);
const pubDate = (item.match(/<pubDate>([^<]*)<\/pubDate>/) || [,''])[1];
if (title && link) return { type: 'news', message: title, desc, date: pubDate, url: link, source: 'Google News' };
return null;
}).filter(Boolean);
}).catch(() => [])
);
const nested = await Promise.all(feedFetches);
return nested.flat();
})()
]);
const directArticles = gh.filter(a => a.type === 'release').slice(0, 3).concat(gl.slice(0, 2)).concat(rss.slice(0, 4)).slice(0, 6).map(item => ({
type: 'direct',
title: item.type === 'release' ? item.name + ' released' : item.message || 'AcreetionOS update',
desc: item.desc || item.message || 'Recent activity from ' + item.source,
tag: item.type === 'release' ? 'Release' : 'Community',
tagClass: item.type === 'release' ? 'tag-release' : 'tag-community',
url: item.url || 'https://acreetionos.org',
source: item.source || 'acreetionos.org',
date: item.date
}));
const activityData = [...gh, ...gl, ...rss].sort((a, b) => new Date(b.date || 0) - new Date(a.date || 0));
return new Response(JSON.stringify({
articles: directArticles,
activity: activityData.slice(0, 20).map(a => ({
type: a.type, repo: a.repo || '', message: a.message || a.name || '', author: a.author || '', date: a.date, url: a.url || '', source: a.source || ''
})),
meta: { directFound: directArticles.length, activityCount: activityData.length }
}), {
headers: { 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=300', ...corsHeaders({ headers: { get: () => '' } }) }
});
} catch (e) {
return new Response(JSON.stringify({ error: 'News fetch failed', articles: [], activity: [] }), {
status: 500, headers: { 'Content-Type': 'application/json', ...corsHeaders({ headers: { get: () => '' } }) }
});
}
}
// ─── Hosting Provider Vetting ─────────────────────────────────
const THREAT_ACTORS = new Set([
'lazarus', 'kimsuks', 'apt38', 'hiddencobra', 'bluenoroff',
'fancybear', 'apt28', 'sofacy', 'pawnstorm', 'sednit',
'cozybear', 'apt29', 'midnightblizzard', 'nobelium',
'wizardspider', 'trickbot', 'fin7', 'carbanak',
'darkhotel', 'apt32', 'oceanlotus', 'mustangpanda',
'taowu', 'panda', 'apt1', 'commentcrew',
'shuckworm', 'armageddon', 'gamaredon', 'actinium',
'belarusian', 'ghostwriter', 'unc1151', 'stardust',
'sandworm', 'apt44', 'blackenergy', 'telebots',
'scatteredspider', 'scatteredsPIDEr', '0ktapus', 'octopus',
'apt41', 'winnti', 'blacktech', 'bronzesunset',
'bluenorthern', 'redquiet', 'blessed', 'muddywater',
'tortoiseshell', 'imperialkitten', 'raqqah', 'thedarkoverlord',
'darkoverlord', 'thedarkoverlord', 'thedarkoverlord',
'conti', 'revil', 'ransomware', 'lockbit', 'blackcat',
'alphv', 'clop', 'cryak', 'darkside', 'blackmatter',
'blypts', 'grief', 'nokoyawa', 'vicesociety', 'ransomhouse',
'vigorous', 'rigorous', 'hades', 'hellokitty',
'lapsus', 'lapus', 'lgroth', 'teamtnt', 'webshell',
'chinanet', 'barium', 'mgbot', 'mirai', 'botnet',
'c2server', 'payloadbin', 'ddos', 'stresser', 'booter',
'nulled', 'cracked', 'hackforums', 'raidforums',
'breachforums', 'exploit', 'exploit.in', 'xss.is',
'dread', 'hackerwanted', 'mostwanted', 'cybercriminal',
'carding', 'carder', 'dumps', 'fullz', 'ssndob',
'hijack', 'phish', 'phishing', 'malware', 'ransomware',
'bankingtrojan', 'infostealer', 'inifil', 'formbook',
'agenttesla', 'nanocore', 'remcos', 'darkcomet',
]);
const SANCTIONED_COUNTRIES = ['iran', 'north korea', 'syria', 'cuba', 'russia', 'belarus', 'crimea'];
async function checkEmailBreaches(env, email) {
// Have I Been Pwned k-anonymity API (no key needed)
try {
const crypto = globalThis.crypto || {};
const encoder = new TextEncoder();
const data = encoder.encode(email);
const hashBuffer = await crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('').toUpperCase();
const prefix = hashHex.slice(0, 5);
const suffix = hashHex.slice(5);
const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, { signal: AbortSignal.timeout(10000) });
if (res.ok) {
const text = await res.text();
const match = text.split('\n').find(line => line.startsWith(suffix));
if (match) {
const count = parseInt(match.split(':')[1] || '0');
if (count > 3) return { breached: true, breach_count: count, url: `https://haveibeenpwned.com/account/${encodeURIComponent(email)}` };
}
}
} catch (e) { console.error('HIBP check failed:', e); }
return { breached: false };
}
async function validateOrgDomain(env, email, org, isPersonal) {
// Skip validation if personal checkbox was checked
if (isPersonal) return { valid: true, note: 'personal' };
const domain = email.split('@')[1];
if (!domain) return { valid: false, reason: 'Invalid email domain' };
// Known open source project hosting platforms
const ossPlatforms = ['github.io', 'gitlab.io', 'bitbucket.io', 'sourceforge.io', 'gitlab.com', 'github.com'];
const isOSS = ossPlatforms.some(p => domain.endsWith('.' + p) || domain === p);
if (isOSS) return { valid: true, note: 'open_source_platform' };
try {
// Check if domain has a resolvable website (proves it's a real organization)
const headRes = await fetch(`https://${domain}`, {
method: 'HEAD',
signal: AbortSignal.timeout(8000)
}).catch(() => null);
// Also check www subdomain
const wwwRes = !headRes?.ok ? await fetch(`https://www.${domain}`, {
method: 'HEAD',
signal: AbortSignal.timeout(8000)
}).catch(() => null) : headRes;
if (wwwRes?.ok || headRes?.ok) {
return { valid: true, note: 'verified_domain' };
}
// Try HTTP as fallback
const httpRes = !headRes && !wwwRes ? await fetch(`http://${domain}`, {
method: 'HEAD',
signal: AbortSignal.timeout(5000)
}).catch(() => null) : null;
if (httpRes?.ok) {
return { valid: true, note: 'verified_domain_http' };
}
return { valid: false, reason: `Domain "${domain}" has no reachable website. Organization email must belong to an open source project or business with an active website, or check "personal use".` };
} catch (e) {
return { valid: false, reason: `Could not verify domain "${domain}": ${e.message}` };
}
}
async function vetProvider(env, body) {
const { org, email, website, mirror_url, location, notes } = body;
const flags = [];
let score = 0;
const orgLower = (org || '').toLowerCase();
const emailLower = (email || '').toLowerCase();
const notesLower = (notes || '').toLowerCase();
const locationLower = (location || '').toLowerCase();
// 1. Check org name against known threat actors
for (const actor of THREAT_ACTORS) {
if (orgLower.includes(actor)) {
flags.push(`Organization name matches known threat actor keyword: "${actor}"`);
score += 50;
}
if (notesLower.includes(actor) || emailLower.includes(actor)) {
flags.push(`Communication references threat actor: "${actor}"`);
score += 40;
}
}
// 2. Check email for breach history
const breachCheck = await checkEmailBreaches(env, email);
if (breachCheck.breached) {
flags.push(`Email appears in ${breachCheck.breach_count} known data breaches (${breachCheck.url})`);
score += breachCheck.breach_count > 20 ? 30 : 15;
}
// 3. Check domain against threat intel blocklist
let domain = '';
try {
domain = new URL(mirror_url || website || '').hostname.replace(/^www\./, '').toLowerCase();
} catch (e) {}
if (domain && env.CLOUDFLARE_API_TOKEN && env.CLOUDFLARE_ACCOUNT_ID) {
const blockedDomains = [];
try {
const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/r2/buckets/acreetionos-hosting/objects/threat-intel%2Fall-blocked-domains.txt`, {
headers: { 'Authorization': `Bearer ${env.CLOUDFLARE_API_TOKEN}` }
});
if (res.ok) {
const text = await res.text();
blockedDomains.push(...text.split('\n').map(s => s.trim().toLowerCase()).filter(Boolean));
}
} catch (e) {}
for (const b of blockedDomains) {
if (domain === b || domain.endsWith('.' + b)) {
flags.push(`Domain "${domain}" appears in threat intelligence blocklist (matched: ${b})`);
score += 45;
break;
}
}
}
// 4. Check location against sanctioned countries
for (const country of SANCTIONED_COUNTRIES) {
if (locationLower.includes(country)) {
flags.push(`Location "${location}" is a sanctioned/embargoed country`);
score += 40;
}
}
// 5. Check notes for suspicious patterns
const suspiciousPatterns = [
{ pattern: /(credit.?card|cc.?num|ssn|social.?security|dumps|fullz)/i, weight: 40, msg: 'Financial fraud indicators in notes' },
{ pattern: /(hack|crack|c2|rat|remote.?access.?trojan|keylogger|spyware)/i, weight: 35, msg: 'Hacking tools referenced in notes' },
{ pattern: /(terrorist|extremist|jihad|isil|isis|taliban)/i, weight: 50, msg: 'Extremist references in notes' },
{ pattern: /(proxy|vpn|relay|tor|onion|i2p)/i, weight: 5, msg: 'Anonymization tools referenced' },
{ pattern: /(money.?launder|wash|sanction.?evade|tax.?haven)/i, weight: 45, msg: 'Financial crime indicators in notes' },
];
for (const sp of suspiciousPatterns) {
if (sp.pattern.test(notesLower) || sp.pattern.test(orgLower)) {
flags.push(sp.msg);
score += sp.weight;
}
}
// 6. Check if email domain is a disposable/temporary email provider
const disposableDomains = [
'mailinator.com', 'guerrillamail.com', 'tempmail.com', '10minutemail.com',
'throwaway.email', 'yopmail.com', 'mail.tm', 'tempmail.net', 'temp-mail.org',
'dispostable.com', 'getnada.com', 'sharklasers.com', 'burnermail.io',
'spamgourmet.com', 'mailmetrash.com', 'trashmail.com', 'fakeinbox.com',
'mailexpire.com', 'emailondeck.com', 'temp-mail.io', 'temp-inbox.com',
];
const emailDomain = emailLower.split('@')[1];
if (disposableDomains.includes(emailDomain)) {
flags.push(`Disposable email provider: ${emailDomain}`);
score += 25;
}
// 7. Check if mirror URL matches known malicious URL patterns
try {
const mirrorPath = new URL(mirror_url).pathname.toLowerCase();
if (/\.(exe|bat|cmd|scr|ps1|vbs|jar|dll)$/i.test(mirrorPath)) {
flags.push(`Mirror URL points to executable, not ISO`);
score += 30;
}
} catch (e) {}
const verdict = score >= 40 ? 'rejected' : score >= 15 ? 'flagged' : 'pending';
return {
verdict,
score,
flags,
auto_rejected: score >= 40,
needs_manual_review: score >= 15 && score < 40,
clean: score < 15,
};
}
// ─── ISO Hosting Provider Management ───────────────────────────────
async function getR2(env, bucket, key) {
if (!env.CLOUDFLARE_API_TOKEN || !env.CLOUDFLARE_ACCOUNT_ID) return null;
const url = `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/r2/buckets/${bucket}/objects/${key}`;
const res = await fetch(url, { headers: { 'Authorization': `Bearer ${env.CLOUDFLARE_API_TOKEN}` } });
if (!res.ok) return null;
// R2 GET returns the raw object body directly (not wrapped in { result: ... })
return await res.json();
}
async function putR2(env, bucket, key, body) {
if (!env.CLOUDFLARE_API_TOKEN || !env.CLOUDFLARE_ACCOUNT_ID) return false;
const url = `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/r2/buckets/${bucket}/objects/${key}`;
const res = await fetch(url, {
method: 'PUT',
headers: { 'Authorization': `Bearer ${env.CLOUDFLARE_API_TOKEN}`, 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
return res.ok;
}
async function deleteR2(env, bucket, key) {
if (!env.CLOUDFLARE_API_TOKEN || !env.CLOUDFLARE_ACCOUNT_ID) return false;
const url = `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/r2/buckets/${bucket}/objects/${key}`;
const res = await fetch(url, { method: 'DELETE', headers: { 'Authorization': `Bearer ${env.CLOUDFLARE_API_TOKEN}` } });
return res.ok;
}
async function listR2(env, bucket, prefix) {
if (!env.CLOUDFLARE_API_TOKEN || !env.CLOUDFLARE_ACCOUNT_ID) return [];
const url = `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/r2/buckets/${bucket}/objects?prefix=${prefix}`;
const res = await fetch(url, { headers: { 'Authorization': `Bearer ${env.CLOUDFLARE_API_TOKEN}` } });
if (!res.ok) return [];
const data = await res.json();
return data?.result?.objects || [];
}
function hashPassword(password) {
let h = 0;
for (let i = 0; i < password.length; i++) { const c = password.charCodeAt(i); h = ((h << 5) - h) + c; h |= 0; }
return 'h' + Math.abs(h).toString(36);
}
function getCors() {
return { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' };
}
async function sendDiscordWebhook(env, message) {
const webhook = env.DISCORD_WEBHOOK_URL;
if (!webhook) return;
try {
await fetch(webhook, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: message })
});
} catch (e) { console.error('Discord webhook failed:', e); }
}
async function sendHostingEmail(env, to, subject, body) {
// Store email job in R2 for Cloudflare Email Worker to pick up
const job = { to, subject, body, from: env.EMAIL_FROM || 'developers@acreetionos.org', created: new Date().toISOString() };
const key = 'email-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
await putR2(env, 'acreetionos-hosting', key, job);
}
async function handleHostingGetProviders(env) {
const objects = await listR2(env, 'acreetionos-hosting', 'provider-');
const providers = [];
for (const obj of objects) {
const data = await getR2(env, 'acreetionos-hosting', obj.key);
if (data) providers.push(data);
}
return new Response(JSON.stringify({ providers }), { headers: getCors() });
}
async function handleHostingRegister(request, env) {
try {
const body = await request.json();
if (!body.org || !body.email || !body.password || !body.mirror_url || !body.location) {
return new Response(JSON.stringify({ error: 'org, email, password, mirror_url, and location are required' }), { status: 400, headers: getCors() });
}
// Validate organization domain (skip if personal checkbox checked)
const orgCheck = await validateOrgDomain(env, body.email, body.org, body.personal_email === true);
if (!orgCheck.valid) {
return new Response(JSON.stringify({ success: false, error: orgCheck.reason }), { status: 400, headers: getCors() });
}
// Run background vetting checks
const vetResult = await vetProvider(env, body);
if (vetResult.auto_rejected) {
sendDiscordWebhook(env,
`**🚫 Registration Auto-Rejected (Vetting Failed)**\n**Organization:** ${body.org}\n**Email:** ${body.email}\n**Location:** ${body.location}\n**Risk Score:** ${vetResult.score}\n**Flags:**\n${vetResult.flags.map(f => '- ' + f).join('\n')}\n\nRegistration was automatically rejected by security vetting.`
);
return new Response(JSON.stringify({
success: false, error: 'Registration rejected by automated security vetting. Contact developers@acreetionos.org if you believe this is an error.',
vetting: { score: vetResult.score, flags: vetResult.flags }
}), { status: 403, headers: getCors() });
}
const id = 'p_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8);
const provider = {
id, org: body.org, email: body.email, website: body.website || '',
mirror_url: body.mirror_url, location: body.location,
bandwidth: body.bandwidth || '', notes: body.notes || '',
password: hashPassword(body.password),
status: vetResult.needs_manual_review ? 'flagged' : 'pending',
created: new Date().toISOString(),
removal_requested: false,
discord_user_id: body.discord_user_id || '',
subscribed: body.subscribe === true,
vetting: { score: vetResult.score, flags: vetResult.flags },
personal_email: body.personal_email === true,
last_seen: new Date().toISOString(),
expiry_warning_sent: false
};
const ok = await putR2(env, 'acreetionos-hosting', 'provider-' + id, provider);
if (!ok) return new Response(JSON.stringify({ error: 'Storage error' }), { status: 500, headers: getCors() });
// Mailing list subscription
if (body.subscribe && body.email) {
await putR2(env, 'acreetionos-hosting', 'subscriber-' + body.email.replace(/[@.]/g, '_'), {
email: body.email, org: body.org, subscribed: new Date().toISOString(), unsubscribe_token: Math.random().toString(36).slice(2, 10)
});
}
const statusEmoji = vetResult.needs_manual_review ? '⚠️' : '✅';
const statusLabel = vetResult.needs_manual_review ? 'Flagged — Manual Review Required' : 'Pending Approval';
// Notify Discord
sendDiscordWebhook(env,
`${statusEmoji} **New Hosting Provider Registration**\n**Organization:** ${body.org}\n**Email:** ${body.email}\n**Location:** ${body.location}\n**Mirror:** ${body.mirror_url}\n**Website:** ${body.website || 'N/A'}\n**Discord User ID:** ${body.discord_user_id || 'N/A'}\n**Subscribed:** ${body.subscribe ? 'Yes' : 'No'}\n**Vetting Score:** ${vetResult.score}\n**Status:** ${statusLabel}\n**ID:** ${id}\n\nTo approve: POST to /api/hosting/admin/approve-removal with { provider_id: "${id}", admin_key: "YOUR_ADMIN_KEY" }\nTo reject: POST to /api/hosting/admin/reject-removal with same\nAdmin page: https://acreetionos.org/api/hosting/admin/pending`
);
if (vetResult.flags.length > 0) {
sendDiscordWebhook(env,
`**Vetting Details for ${body.org}**\n${vetResult.flags.map(f => '- ' + f).join('\n')}`
);
}
const msg = vetResult.auto_rejected
? 'Registration rejected by security vetting'
: vetResult.needs_manual_review
? 'Registration submitted — flagged for manual review due to security indicators'
: 'Registration submitted for review';
return new Response(JSON.stringify({ success: true, message: msg, id, vetting: { score: vetResult.score, flagged: vetResult.needs_manual_review } }), { headers: getCors() });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: getCors() });
}
}
async function handleHostingRemoveRequest(request, env) {
try {
const body = await request.json();
if (!body.email || !body.password) {
return new Response(JSON.stringify({ error: 'email and password required' }), { status: 400, headers: getCors() });
}
const objects = await listR2(env, 'acreetionos-hosting', 'provider-');
let found = null;
for (const obj of objects) {
const data = await getR2(env, 'acreetionos-hosting', obj.key);
if (data && data.email === body.email && data.password === hashPassword(body.password)) { found = data; break; }
}
if (!found) return new Response(JSON.stringify({ error: 'Provider not found or password incorrect' }), { status: 404, headers: getCors() });
found.removal_requested = true;
found.removal_reason = body.notes || 'No reason given';
await putR2(env, 'acreetionos-hosting', 'provider-' + found.id, found);
sendDiscordWebhook(env, `**Removal Requested**\n**Provider:** ${found.org} (${found.email})\n**Reason:** ${body.notes || 'None'}\n**ID:** ${found.id}`);
return new Response(JSON.stringify({ success: true, message: 'Removal request submitted for admin approval' }), { headers: getCors() });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: getCors() });
}
}
async function handleHostingUpdateRequest(request, env) {
try {
const body = await request.json();
if (!body.email || !body.password) {
return new Response(JSON.stringify({ error: 'email and password required' }), { status: 400, headers: getCors() });
}
const objects = await listR2(env, 'acreetionos-hosting', 'provider-');
let found = null;
for (const obj of objects) {
const data = await getR2(env, 'acreetionos-hosting', obj.key);
if (data && data.email === body.email && data.password === hashPassword(body.password)) { found = data; break; }
}
if (!found) return new Response(JSON.stringify({ error: 'Provider not found or password incorrect' }), { status: 404, headers: getCors() });
found.notes = body.notes || found.notes;
await putR2(env, 'acreetionos-hosting', 'provider-' + found.id, found);
return new Response(JSON.stringify({ success: true, message: 'Listing updated' }), { headers: getCors() });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: getCors() });
}
}
async function handleHostingAdminApprove(request, env) {
try {
const body = await request.json();
if (!body.admin_key || body.admin_key !== env.ADMIN_KEY) return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 403, headers: getCors() });
if (!body.provider_id) return new Response(JSON.stringify({ error: 'provider_id required' }), { status: 400, headers: getCors() });
const data = await getR2(env, 'acreetionos-hosting', 'provider-' + body.provider_id);
if (!data) return new Response(JSON.stringify({ error: 'Provider not found' }), { status: 404, headers: getCors() });
if (body.action === 'approve-removal' || body.action === 'remove') {
await deleteR2(env, 'acreetionos-hosting', 'provider-' + body.provider_id);
sendDiscordWebhook(env, `**Provider Removed (Admin Approved)**\n**Provider:** ${data.org} (${data.email})`);
// Notify mailing list about removal
if (data.subscribed && data.email) {
sendHostingEmail(env, data.email, 'AcreetionOS Hosting - Your Provider Has Been Removed',
`Hi ${data.org},\n\nYour hosting provider listing for AcreetionOS has been removed as requested.\n\nThank you for your support.\n- AcreetionOS Team`);
}
triggerRedeploy(env);
return new Response(JSON.stringify({ success: true, message: 'Provider removed and redeploy triggered' }), { headers: getCors() });
}
// Approve registration
data.status = 'active';
await putR2(env, 'acreetionos-hosting', 'provider-' + body.provider_id, data);
sendDiscordWebhook(env, `**Provider Approved**\n**Provider:** ${data.org} (${data.email}) is now active.`);
// Send welcome email to subscribed providers
if (data.subscribed && data.email) {
sendHostingEmail(env, data.email, 'Welcome to AcreetionOS Hosting Program!',
`Hi ${data.org},\n\nYour hosting provider application has been approved!\n\nMirror URL: ${data.mirror_url}\nStatus: Active\n\nYou are now subscribed to hosting updates. We'll notify you of any changes.\n\nTo unsubscribe: https://acreetionos.org/api/hosting/unsubscribe?email=${encodeURIComponent(data.email)}\n\n- AcreetionOS Team`);
}
triggerRedeploy(env);
return new Response(JSON.stringify({ success: true, message: 'Provider approved and redeploy triggered' }), { headers: getCors() });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: getCors() });
}
}
async function handleHostingAdminReject(request, env) {
try {
const body = await request.json();
if (!body.admin_key || body.admin_key !== env.ADMIN_KEY) return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 403, headers: getCors() });
if (!body.provider_id) return new Response(JSON.stringify({ error: 'provider_id required' }), { status: 400, headers: getCors() });
await deleteR2(env, 'acreetionos-hosting', 'provider-' + body.provider_id);
sendDiscordWebhook(env, `**Provider Registration Rejected**\n**ID:** ${body.provider_id}`);
return new Response(JSON.stringify({ success: true, message: 'Provider registration rejected and removed' }), { headers: getCors() });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: getCors() });
}
}
async function handleHostingAdminPending(env) {
const objects = await listR2(env, 'acreetionos-hosting', 'provider-');
const all = [];
for (const obj of objects) {
const data = await getR2(env, 'acreetionos-hosting', obj.key);
if (data) all.push(data);
}
const pending = all.filter(p => p.status === 'pending' || p.removal_requested);
return new Response(JSON.stringify({ pending, total: all.length }), { headers: getCors() });
}
async function handleHostingSubscribe(request, env) {
try {
const body = await request.json();
if (!body.email) return new Response(JSON.stringify({ error: 'email required' }), { status: 400, headers: getCors() });
const key = 'subscriber-' + body.email.replace(/[@.]/g, '_');
const existing = await getR2(env, 'acreetionos-hosting', key);
if (existing) return new Response(JSON.stringify({ success: true, message: 'Already subscribed' }), { headers: getCors() });
await putR2(env, 'acreetionos-hosting', key, {
email: body.email, org: body.org || '', subscribed: new Date().toISOString(), unsubscribe_token: Math.random().toString(36).slice(2, 10)
});
return new Response(JSON.stringify({ success: true, message: 'Subscribed to hosting updates' }), { headers: getCors() });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: getCors() });
}
}
async function handleHostingUnsubscribe(request, env) {
const email = request.url.searchParams?.get?.('email') || '';
if (!email) return new Response(JSON.stringify({ error: 'email required' }), { status: 400, headers: getCors() });
const key = 'subscriber-' + email.replace(/[@.]/g, '_');
await deleteR2(env, 'acreetionos-hosting', key);
return new Response(JSON.stringify({ success: true, message: 'Unsubscribed' }), { headers: getCors() });
}
// ─── Malware Scanning ──────────────────────────────────────────
const SUSPICIOUS_FILENAME_PATTERNS = /\.(exe|bat|cmd|scr|ps1|vbs|jar|dll|zip|rar|7z)$/i;
const ISO_MAGIC = new Uint8Array([0x43, 0x44, 0x30, 0x30, 0x31]); // "CD001" at offset 32769
const SCAN_QUOTA_KEY = 'scan-quota-state';
async function getScanQuota(env) {
const data = await getR2(env, 'acreetionos-hosting', SCAN_QUOTA_KEY);
return data || { vt_remaining: 500, vt_reset: Date.now() + 86400000, vt_disabled: false };
}
async function saveScanQuota(env, quota) {
await putR2(env, 'acreetionos-hosting', SCAN_QUOTA_KEY, quota);
}
async function getThreatIntel(env) {
try {
const data = await getR2(env, 'acreetionos-hosting', 'threat-intel/all-blocked-domains.txt');
if (data && typeof data === 'object' && data.body) {
return data.body.split('\n').map(s => s.trim().toLowerCase()).filter(Boolean);
}
// raw text stored differently - try fetching directly
const url = `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/r2/buckets/acreetionos-hosting/objects/threat-intel%2Fall-blocked-domains.txt`;
const res = await fetch(url, { headers: { 'Authorization': `Bearer ${env.CLOUDFLARE_API_TOKEN}` } });
if (res.ok) {
const text = await res.text();
return text.split('\n').map(s => s.trim().toLowerCase()).filter(Boolean);
}
} catch (e) { console.error('Threat intel fetch failed:', e); }
return [];
}
function checkThreatIntel(domain, blockedDomains) {
const d = domain.toLowerCase();
for (const b of blockedDomains) {
if (d === b || d.endsWith('.' + b) || d.includes(b)) return b;
}
return null;
}
async function localScanISO(env, data) {
// Local fallback scan when VirusTotal quota is exhausted
const issues = [];
const isoUrl = data.mirror_url;
const blockedDomains = await getThreatIntel(env);
try {
// 1. HEAD request to verify URL is reachable and looks like an ISO
const headRes = await fetch(isoUrl, { method: 'HEAD', signal: AbortSignal.timeout(15000) });
if (!headRes.ok) {
issues.push('ISO URL returned ' + headRes.status);
}
const contentType = headRes.headers.get('Content-Type') || '';
const contentLength = parseInt(headRes.headers.get('Content-Length') || '0');
if (contentLength > 0 && contentLength < 104857600) {
issues.push(`ISO too small (${(contentLength/1048576).toFixed(1)} MB) — likely not a real ISO`);
}
// 2. Check filename for suspicious extensions
const pathname = new URL(isoUrl).pathname;
if (SUSPICIOUS_FILENAME_PATTERNS.test(pathname)) {
issues.push(`Suspicious file extension in URL: ${pathname.match(/\.[^.]+$/)[0]}`);
}
// 3. Check ISO magic bytes in the first chunk
const getRes = await fetch(isoUrl, {
headers: { 'Range': 'bytes=32769-32773' },
signal: AbortSignal.timeout(15000)
});
if (getRes.ok) {
const chunk = await getRes.arrayBuffer();
const bytes = new Uint8Array(chunk);
const isIso = ISO_MAGIC.every((b, i) => bytes[i] === b);
if (!isIso) {
issues.push('Missing ISO 9660 magic bytes — file may not be a valid ISO');
}
}
// 4. Check domain against threat intelligence feeds
try {
const domain = new URL(isoUrl).hostname.replace(/^www\./, '');
const match = checkThreatIntel(domain, blockedDomains);
if (match) {
issues.push(`Domain blocked by threat intelligence feed (match: ${match})`);
}
} catch (e) {
// Invalid URL, skip domain check
}
// 5. Check for ISO in pathname (should contain .iso)
if (!pathname.toLowerCase().includes('.iso')) {
issues.push('URL does not point to an ISO file');
}
// 6. Flag for CI ClamAV deep scan
if (issues.length === 0) {
return { clean: true, scan_method: 'local_quick' };
}
return { clean: false, scan_method: 'local_quick', issues, auto_deregister: false, needs_clamav: true };
} catch (e) {
return { clean: false, scan_method: 'local_quick', issues: [`Scan error: ${e.message}`], auto_deregister: false, needs_clamav: true };
}
}
async function scanISOSuspicious(env) {
const objects = await listR2(env, 'acreetionos-hosting', 'provider-');
const flagged = [];
const errors = [];
const vtQuarantined = [];
const vtDisabled = [];
let quota = await getScanQuota(env);
let useVt = !quota.vt_disabled && env.VIRUSTOTAL_API_KEY;
for (const obj of objects) {
const data = await getR2(env, 'acreetionos-hosting', obj.key);
if (!data || (data.status !== 'active' && data.status !== 'reactivating')) continue;
const isoUrl = data.mirror_url;
if (!isoUrl) continue;
let result;
if (useVt) {
try {
const submitRes = await fetch('https://www.virustotal.com/api/v3/urls', {
method: 'POST',
headers: { 'x-apikey': env.VIRUSTOTAL_API_KEY, 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ url: isoUrl })
});
if (submitRes.status === 429 || submitRes.status === 403) {
// Quota exhausted or key invalid — switch to local scan for all remaining
quota.vt_disabled = true;
quota.vt_disabled_at = Date.now();
await saveScanQuota(env, quota);
sendDiscordWebhook(env,
`**VirusTotal Quota Exhausted** — Switching to local fallback scanning.\nStatus: ${submitRes.status}\nAll remaining providers will be scanned locally and flagged for ClamAV CI verification.`
);
useVt = false;
vtDisabled.push(data.org);
result = await localScanISO(env, data);
} else if (!submitRes.ok) {
errors.push(`${data.org}: VT submit failed ${submitRes.status}`);
result = await localScanISO(env, data);
} else {
const submitData = await submitRes.json();
const analysisId = submitData?.data?.id;
if (analysisId) {
await new Promise(r => setTimeout(r, 5000));
const resultRes = await fetch(`https://www.virustotal.com/api/v3/analyses/${analysisId}`, {
headers: { 'x-apikey': env.VIRUSTOTAL_API_KEY }
});
if (resultRes.ok) {
const resultData = await resultRes.json();
const stats = resultData?.data?.attributes?.stats;
if (stats && (stats.malicious > 0 || stats.suspicious > 0)) {
result = { clean: false, scan_method: 'virustotal', malicious: stats.malicious, suspicious: stats.suspicious, total: (stats.harmless||0)+(stats.malicious||0)+(stats.suspicious||0)+(stats.undetected||0) };
} else {
result = { clean: true, scan_method: 'virustotal' };
}
} else {
errors.push(`${data.org}: VT result fetch failed`);
result = await localScanISO(env, data);
}
} else {
errors.push(`${data.org}: no VT analysis ID`);
result = await localScanISO(env, data);
}
}
if (useVt) {
quota.vt_remaining = (quota.vt_remaining || 500) - 1;
if (quota.vt_remaining <= 0) {
quota.vt_disabled = true;
quota.vt_disabled_at = Date.now();
useVt = false;
sendDiscordWebhook(env, '**VirusTotal Daily Quota Reached** — Switching to local scans for remaining providers.');
}
await saveScanQuota(env, quota);
await new Promise(r => setTimeout(r, 16000));
}
} catch (e) {
errors.push(`${data.org}: VT error ${e.message}, falling back to local scan`);
result = await localScanISO(env, data);
}
} else {
result = await localScanISO(env, data);
}
// Update last_seen for clean scans or local scans that passed
if (result.clean || result.scan_method === 'local_quick') {
data.last_seen = new Date().toISOString();
// Auto-reactivation logic — if status is 'reactivating', track uptime
if (data.status === 'reactivating') {
if (!data.reactivation_online_since) {
data.reactivation_online_since = new Date().toISOString();
}
const onlineSince = new Date(data.reactivation_online_since).getTime();
const hoursOnline = (Date.now() - onlineSince) / (1000 * 60 * 60);
if (hoursOnline >= 24) {
data.status = 'active';
data.reactivation_requested = false;
data.reactivation_online_since = undefined;
data.reactivation_requested_at = undefined;
sendDiscordWebhook(env,
`**✅ Provider Auto-Reactivated**\n**Provider:** ${data.org}\n**Email:** ${data.email}\n**ISO:** ${data.mirror_url}\n**Online for:** ${hoursOnline.toFixed(1)} hours\n\nProvider has been reactivated after 24+ hours of uptime.`
);
triggerRedeploy(env);
}
}
await putR2(env, 'acreetionos-hosting', obj.key, data);
}
if (!result.clean) {
const entry = {
id: data.id, org: data.org, email: data.email,
mirror_url: data.mirror_url,
scan_method: result.scan_method,
issues: result.issues || [],
};
if (result.malicious !== undefined) {
entry.malicious = result.malicious;
entry.suspicious = result.suspicious;
entry.total = result.total;
}
flagged.push(entry);
}
}
return { flagged, errors, vt_disabled: quota.vt_disabled, vt_quarantined: vtDisabled };
}
async function checkStaleProviders(env) {
const objects = await listR2(env, 'acreetionos-hosting', 'provider-');
const expired = [];
const now = Date.now();
const twoWeeks = 14 * 24 * 60 * 60 * 1000;
for (const obj of objects) {
const data = await getR2(env, 'acreetionos-hosting', obj.key);
if (!data || data.status !== 'active') continue;
const lastSeen = data.last_seen ? new Date(data.last_seen).getTime() : 0;
const age = now - lastSeen;
if (age > twoWeeks) {
// Send expiry warning if not already sent (send once at 14 days)
if (!data.expiry_warning_sent) {
data.expiry_warning_sent = true;
await putR2(env, 'acreetionos-hosting', obj.key, data);
// Store email notification job
const emailBody = `Hi ${data.org},\n\nYour AcreetionOS hosting provider listing has been flagged as inactive.\n\nYour ISO mirror (${data.mirror_url}) has not been reachable for 14 days. Per our requirements, providers must maintain an active mirror.\n\nIf you believe this is an error, please contact us at developers@acreetionos.org or re-register at https://acreetionos.org/hosting.html\n\nIf we don't hear from you within 7 days, your listing will be automatically removed.\n\n- AcreetionOS Team`;
await sendHostingEmail(env, data.email, 'AcreetionOS Hosting — Inactivity Warning', emailBody);
sendDiscordWebhook(env,
`**⚠️ Provider Inactivity Warning**\n**Provider:** ${data.org}\n**Email:** ${data.email}\n**ISO:** ${data.mirror_url}\n**Last seen:** ${data.last_seen || 'Never'}\n**Grace period:** 7 days before removal\n\nWarning email sent to provider.`
);
}
// Remove after 21 days (14 days + 7 day grace)
if (age > twoWeeks + (7 * 24 * 60 * 60 * 1000)) {
await deleteR2(env, 'acreetionos-hosting', obj.key);
const removalBody = `Hi ${data.org},\n\nYour AcreetionOS hosting provider listing has been removed.\n\nReason: Your ISO mirror (${data.mirror_url}) was unreachable for more than 21 days. This violates our hosting requirements.\n\nIf you'd like to re-register, please visit https://acreetionos.org/hosting.html and ensure your mirror is online before submitting.\n\nIf you believe this is an error, contact us at developers@acreetionos.org\n\n- AcreetionOS Team`;
await sendHostingEmail(env, data.email, 'AcreetionOS Hosting — Listing Removed (Inactivity)', removalBody);
expired.push({ org: data.org, email: data.email, last_seen: data.last_seen, reason: 'inactive_21_days' });
}
}
// Also update last_seen if ISO is reachable during scan (handled in scanISOSuspicious)
// This is a safety net for providers not scanned recently
}
return expired;
}
async function handleHostingScan(request, env) {
// POST /api/hosting/scan — triggers full scan of all provider ISOs
// Requires admin_key
const body = await request.json().catch(() => ({}));
if (body.admin_key !== env.ADMIN_KEY) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 403, headers: getCors() });
}
const result = await scanISOSuspicious(env);
let needsClamav = false;
// Auto-deregister flagged providers (VT-confirmed only)
for (const flagged of result.flagged) {
if (flagged.scan_method === 'virustotal' || (flagged.scan_method === 'local_quick' && flagged.malicious)) {
await deleteR2(env, 'acreetionos-hosting', 'provider-' + flagged.id);
sendDiscordWebhook(env,
`**🚨 MALWARE DETECTED — Provider Auto-Deregistered**\n**Provider:** ${flagged.org}\n**Email:** ${flagged.email}\n**ISO:** ${flagged.mirror_url}\n**Method:** ${flagged.scan_method}\n**Malicious detections:** ${flagged.malicious || 0}\n**Issues:** ${(flagged.issues || []).join(', ')}\n\nProvider has been immediately removed from the website.`
);
}
if (flagged.needs_clamav || flagged.scan_method === 'local_quick') {
needsClamav = true;
}
}
if (result.vt_disabled) {
sendDiscordWebhook(env,