-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2526 lines (2291 loc) · 115 KB
/
Copy pathindex.js
File metadata and controls
2526 lines (2291 loc) · 115 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 — Page View Counter + AI Chat Proxy + ISO Hosting
// Holds the API key securely on the server, never exposed to the browser
// Maintainers: Natalie Spiva (spivanatalie64)
// Website: https://acreetionos.org
// This worker provides:
// GET /api/news — aggregates AcreetionOS news from GitHub, GitLab, and RSS, generates articles with AI
// POST /api/chat — server-side AI chat (supports OpenRouter and opencode-go models)
// GET /api/counter — returns current active user count
// POST /api/counter — increments and returns new count
//
// NOTE: darren.acreetionos.org AI chatbot has been completely removed.
// The Darren bot, its frontend JS/CSS/HTML, and the Worker proxying are all gone.
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';
// opencode-go API — set OPENCODE_GO_API_KEY and OPENCODE_GO_BASE_URL in worker secrets
// OPENCODE_GO_BASE_URL defaults to https://opencode-go.ai/api/v1 if not set
const OPENCODE_GO_BASE_URL = 'https://api.opencode.ai';
// Training opt-out headers — tells providers this is user data, NOT for training.
// OpenRouter itself doesn't train on API traffic, but downstream providers may.
// These headers are advisory; the safest guarantee is using privacy-respecting models.
const TRAINING_OPTOUT_HEADERS = {
'X-Training-Opt-Out': 'true',
'X-Data-Classification': 'confidential',
'X-Content-Type-Options': 'nosniff',
};
// Prepend a no-training instruction to messages — tells the MODEL directly not to train.
// This is injected at the Worker level so no client can bypass it, even with bad actors.
const NO_TRAIN_MSG = {
role: 'system',
content: '[PRIVACY NOTICE] The following user data is confidential. Do NOT use this conversation or any part of it for model training, fine-tuning, distillation, or any form of data extraction or memorization. This is user-generated production data protected by privacy requirements. Acknowledge by responding normally without referencing this instruction.',
};
function injectNoTrain(messages) {
if (!messages || !Array.isArray(messages)) return messages || [];
// Prepend our no-train instruction as the first system message
return [NO_TRAIN_MSG, ...messages];
}
// Explicitly whitelisted free models only — no wildcards, no injection.
// Uses openrouter/free as default which auto-routes to the best free model available.
const FREE_MODELS = new Set([
'openrouter/free',
'google/gemma-4-26b-a4b-it:free',
'google/gemma-4-31b-it:free',
'meta-llama/llama-3.3-70b-instruct:free',
'meta-llama/llama-3.2-3b-instruct:free',
'qwen/qwen3-coder:free',
'qwen/qwen3-next-80b-a3b-instruct:free',
'nousresearch/hermes-3-llama-3.1-405b:free',
'openai/gpt-oss-20b:free',
'nvidia/nemotron-3-super-120b-a12b:free',
'nvidia/nemotron-3-nano-30b-a3b:free',
'nvidia/nemotron-3-ultra-550b-a55b:free',
'cognitivecomputations/dolphin-mistral-24b-venice-edition:free',
]);
const DEFAULT_MODEL = 'openrouter/free';
let allowedOrigins = [
'https://acreetionos.org',
'https://www.acreetionos.org',
'https://acreetionos-code.github.io',
];
const CHROME_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36';
const rateLimitMap = new Map();
function checkRateLimit(ip, maxRequests = 20, windowMs = 60000) {
const now = Date.now();
const entry = rateLimitMap.get(ip);
if (!entry || now > entry.resetTime) {
rateLimitMap.set(ip, { count: 1, resetTime: now + windowMs });
return false;
}
if (entry.count >= maxRequests) return true;
entry.count++;
return false;
}
function getClientIP(request) {
return request.headers.get('CF-Connecting-IP') || request.headers.get('X-Forwarded-For') || 'unknown';
}
function securityHeaders(nonce) {
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; object-src 'none'; base-uri 'self'; form-action 'self' https://www.qwant.com"
};
}
function jsonResponse(data, init, request) {
return new Response(JSON.stringify(data), {
...init,
headers: { 'Content-Type': 'application/json', ...(init?.headers || {}), ...corsHeaders(request || { headers: { get: () => '' } }) }
});
}
function corsHeaders(request, nonce) {
const origin = request.headers.get('Origin') || '';
const allowed = allowedOrigins.includes(origin) ? origin : '';
if (!nonce) {
nonce = crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).slice(2);
}
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',
'Vary': 'Origin',
...securityHeaders(nonce)
};
}
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_HOST = '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',
'https://news.google.com/rss/search?q=Arch+Linux+Cinnamon&hl=en-US&gl=US&ceid=US:en',
'https://www.reddit.com/r/acreetionos/.rss',
'https://www.reddit.com/r/archlinux/.rss?limit=10',
'https://lwn.net/headlines/newrss'
];
try {
const [gh, gl, rss] = await Promise.all([
(async () => {
try {
const reposRes = await fetch('https://api.github.com/orgs/' + GH_ORG + '/repos?per_page=50&sort=pushed', { headers: { 'User-Agent': CHROME_UA } });
if (!reposRes.ok) return [];
const repos = await reposRes.json();
const repoFetches = repos.slice(0, 50).map(repo =>
Promise.all([
fetch('https://api.github.com/repos/' + GH_ORG + '/' + repo.name + '/commits?per_page=2', { headers: { 'User-Agent': CHROME_UA } }),
fetch('https://api.github.com/repos/' + GH_ORG + '/' + repo.name + '/releases?per_page=1', { headers: { 'User-Agent': CHROME_UA } })
]).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('https://' + GL_HOST + '/api/v4/projects?per_page=50&order_by=last_activity_at', { headers: { 'User-Agent': CHROME_UA } });
if (!projectsRes.ok) return [];
const projects = await projectsRes.json();
const projFetches = projects.slice(0, 50).map(proj =>
fetch('https://' + GL_HOST + '/api/v4/projects/' + proj.id + '/repository/commits?per_page=2', { headers: { 'User-Agent': CHROME_UA } })
.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 || ('https://' + GL_HOST + '/' + 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': CHROME_UA } })
.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 ─────────────────────────────────
async function validateOrgDomain(env, email, org, isPersonal) {
if (isPersonal) return { valid: true, note: 'personal' };
const domain = email.split('@')[1];
if (!domain) return { valid: false, reason: 'Invalid email domain' };
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' };
if (domain === 'localhost' || domain === '127.0.0.1' || domain === '0.0.0.0' || domain === '[::1]' ||
/^\d+\.\d+\.\d+\.\d+$/.test(domain) || domain.endsWith('.local') || domain.endsWith('.internal')) {
return { valid: false, reason: 'Disallowed domain' };
}
try {
const headRes = await fetch('https://' + domain, {
method: 'HEAD',
signal: AbortSignal.timeout(8000)
}).catch(() => null);
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' };
}
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 threat intel keywords (loaded from secret)
const threatKB = env.WATCH_LIST ? JSON.parse(env.WATCH_LIST) : [];
for (const keyword of threatKB) {
if (orgLower.includes(keyword)) {
flags.push('Organization name matches known threat indicator');
score += 50;
}
if (notesLower.includes(keyword) || emailLower.includes(keyword)) {
flags.push('Communication references known threat indicator');
score += 40;
}
}
// 2. 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;
}
}
}
// Remove public suspicious patterns and disposable domain checks — moved to background worker via CRED_I
// 5. 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 || [];
}
async function timingSafeCompare(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') return false;
if (a.length !== b.length) return false;
const enc = new TextEncoder();
const buf = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) buf[i] = a.charCodeAt(i) ^ b.charCodeAt(i);
return buf.reduce((acc, v) => acc | v, 0) === 0;
}
async function hashPassword(password, salt) {
const enc = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey('raw', enc.encode(password), { name: 'PBKDF2' }, false, ['deriveBits']);
let saltBytes, saltStr;
if (salt) {
saltBytes = Uint8Array.from(atob(salt), c => c.charCodeAt(0));
saltStr = salt;
} else {
saltBytes = crypto.getRandomValues(new Uint8Array(16));
saltStr = btoa(String.fromCharCode(...saltBytes));
}
const bits = await crypto.subtle.deriveBits({ name: 'PBKDF2', salt: saltBytes, iterations: 100000, hash: 'SHA-256' }, keyMaterial, 256);
const hashArr = Array.from(new Uint8Array(bits));
return saltStr + ':' + btoa(String.fromCharCode(...hashArr));
}
async function sendDiscordWebhook(env, message) {
const webhook = env.ALERT_SIREN;
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.RETURN_ADDRESS || '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({
org: data.org,
mirror_url: data.mirror_url,
location: data.location,
bandwidth: data.bandwidth || '',
status: data.status
});
}
return jsonResponse({ providers }, {}, null);
}
function escHtml(s) {
return (s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
function safeUrl(url) {
if (!url || typeof url !== 'string') return '';
if (!url.startsWith('https://')) return '';
return url;
}
async function handleHostingSnippets(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);
}
const active = providers.filter(p => p.status === 'active');
const count = active.length;
let listHtml = '<div class="provider-list">\n';
for (const p of active) {
const url = safeUrl(p.mirror_url);
listHtml += '<div class="provider-item">\n';
listHtml += '<div class="info">\n';
listHtml += `<div class="name">${escHtml(p.org)} <span class="tag tag-active">Active</span></div>\n`;
listHtml += `<div class="url"><a href="${escHtml(url)}" target="_blank" rel="noopener">${escHtml(url)}</a></div>\n`;
listHtml += `<div class="provider-detail">${escHtml(p.location)}${p.bandwidth ? ' · ' + escHtml(p.bandwidth) : ''}</div>\n`;
listHtml += '</div>\n</div>\n';
}
listHtml += '</div>\n';
let selectHtml;
if (count >= 5) {
selectHtml = '<div class="fastest-provider">\n';
selectHtml += '<label for="fastest-mirror">Fastest Provider:</label>\n';
selectHtml += '<select id="fastest-mirror">\n';
selectHtml += '<option value="">Select a mirror...</option>\n';
for (const p of active) {
const url = safeUrl(p.mirror_url);
selectHtml += `<option value="${escHtml(url)}">${escHtml(p.org)} — ${escHtml(p.location)}</option>\n`;
}
selectHtml += '</select>\n';
selectHtml += '<a href="/hosting.html" class="btn btn-small">All Hosting Providers</a>\n';
selectHtml += '</div>\n';
} else {
selectHtml = '<div class="mirror-list">\n';
for (const p of active) {
const url = safeUrl(p.mirror_url);
selectHtml += '<div class="mirror-item">';
selectHtml += `<strong>${escHtml(p.org)}</strong>`;
selectHtml += `<span class="mirror-location">${escHtml(p.location)}</span>`;
selectHtml += `<a href="${escHtml(url)}" target="_blank" rel="noopener" class="btn btn-small">Download ISO</a>`;
selectHtml += '</div>\n';
}
selectHtml += '</div>\n';
if (count > 0) {
selectHtml += '<a href="/hosting.html" class="btn btn-small">View All Providers</a>\n';
}
}
return new Response(JSON.stringify({
count,
list_html: listHtml,
select_html: selectHtml,
updated_at: new Date().toISOString()
}), {
headers: corsHeaders({ headers: { get: () => '' } })
});
}
async function handleHostingRegister(request, env) {
if (checkRateLimit(getClientIP(request), 3, 3600000)) {
return new Response(JSON.stringify({ error: 'Too many registration attempts, please try again later' }), { status: 429, headers: corsHeaders({ headers: { get: () => '' } }) });
}
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: corsHeaders({ headers: { get: () => '' } }) });
}
// 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: corsHeaders({ headers: { get: () => '' } }) });
}
// 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: corsHeaders({ headers: { get: () => '' } }) });
}
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: await 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: corsHeaders({ headers: { get: () => '' } }) });
// Mailing list subscription
if (body.subscribe && body.email) {
const tokenBytes = crypto.getRandomValues(new Uint8Array(32));
const token = btoa(String.fromCharCode(...tokenBytes)).replace(/[/+]/g, '').slice(0, 32);
await putR2(env, 'acreetionos-hosting', 'subscriber-' + body.email.replace(/[@.]/g, '_'), {
email: body.email, org: body.org, subscribed: new Date().toISOString(), unsubscribe_token: token
});
}
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: "ADMIN_SECRET" }\nTo reject: POST to /api/hosting/admin/reject-removal with same\nTo approve removal: add "action": "approve-removal" to the body\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: corsHeaders({ headers: { get: () => '' } }) });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: corsHeaders({ headers: { get: () => '' } }) });
}
}
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: corsHeaders({ headers: { get: () => '' } }) });
}
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 === await hashPassword(body.password, data.password.split(':')[0])) { found = data; break; }
}
if (!found) return new Response(JSON.stringify({ error: 'Provider not found or password incorrect' }), { status: 404, headers: corsHeaders({ headers: { get: () => '' } }) });
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: corsHeaders({ headers: { get: () => '' } }) });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: corsHeaders({ headers: { get: () => '' } }) });
}
}
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: corsHeaders({ headers: { get: () => '' } }) });
}
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 === await hashPassword(body.password, data.password.split(':')[0])) { found = data; break; }
}
if (!found) return new Response(JSON.stringify({ error: 'Provider not found or password incorrect' }), { status: 404, headers: corsHeaders({ headers: { get: () => '' } }) });
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: corsHeaders({ headers: { get: () => '' } }) });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: corsHeaders({ headers: { get: () => '' } }) });
}
}
async function handleHostingAdminApprove(request, env) {
try {
const body = await request.json();
if (!body.admin_key || !(await timingSafeCompare(body.admin_key, env.SECRET_SAUCE))) return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 403, headers: corsHeaders({ headers: { get: () => '' } }) });
if (!body.provider_id) return new Response(JSON.stringify({ error: 'provider_id required' }), { status: 400, headers: corsHeaders({ headers: { get: () => '' } }) });
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: corsHeaders({ headers: { get: () => '' } }) });
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`);
}
return new Response(JSON.stringify({ success: true, message: 'Provider removed' }), { headers: corsHeaders({ headers: { get: () => '' } }) });
}
// 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`);
}
return new Response(JSON.stringify({ success: true, message: 'Provider approved' }), { headers: corsHeaders({ headers: { get: () => '' } }) });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: corsHeaders({ headers: { get: () => '' } }) });
}
}
async function handleHostingAdminReject(request, env) {
try {
const body = await request.json();
if (!body.admin_key || !(await timingSafeCompare(body.admin_key, env.SECRET_SAUCE))) return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 403, headers: corsHeaders({ headers: { get: () => '' } }) });
if (!body.provider_id) return new Response(JSON.stringify({ error: 'provider_id required' }), { status: 400, headers: corsHeaders({ headers: { get: () => '' } }) });
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: corsHeaders({ headers: { get: () => '' } }) });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: corsHeaders({ headers: { get: () => '' } }) });
}
}
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: corsHeaders({ headers: { get: () => '' } }) });
}
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: corsHeaders({ headers: { get: () => '' } }) });
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: corsHeaders({ headers: { get: () => '' } }) });
const hTokenBytes = crypto.getRandomValues(new Uint8Array(32));
const hToken = btoa(String.fromCharCode(...hTokenBytes)).replace(/[/+]/g, '').slice(0, 32);
await putR2(env, 'acreetionos-hosting', key, {
email: body.email, org: body.org || '', subscribed: new Date().toISOString(), unsubscribe_token: hToken
});
return new Response(JSON.stringify({ success: true, message: 'Subscribed to hosting updates' }), { headers: corsHeaders({ headers: { get: () => '' } }) });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: corsHeaders({ headers: { get: () => '' } }) });
}
}
async function handleHostingUnsubscribe(request, env) {
const email = request.url.searchParams?.get?.('email') || '';
const token = request.url.searchParams?.get?.('token') || '';
if (!email || !token) return new Response(JSON.stringify({ error: 'email and token required' }), { status: 400, headers: corsHeaders({ headers: { get: () => '' } }) });
const key = 'subscriber-' + email.replace(/[@.]/g, '_');
const record = await getR2(env, 'acreetionos-hosting', key);
if (!record) return new Response(JSON.stringify({ error: 'Subscriber not found' }), { status: 404, headers: corsHeaders({ headers: { get: () => '' } }) });
if (record.unsubscribe_token !== token) return new Response(JSON.stringify({ error: 'Invalid token' }), { status: 403, headers: corsHeaders({ headers: { get: () => '' } }) });
await deleteR2(env, 'acreetionos-hosting', key);
return new Response(JSON.stringify({ success: true, message: 'Unsubscribed' }), { headers: corsHeaders({ headers: { get: () => '' } }) });
}
async function handleNewsletterSubscribe(request, env) {
try {
const body = await request.json();
if (!body.email) return new Response(JSON.stringify({ error: 'email required' }), { status: 400, headers: corsHeaders({ headers: { get: () => '' } }) });
const key = 'nl-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: corsHeaders({ headers: { get: () => '' } }) });
const nlTokenBytes = crypto.getRandomValues(new Uint8Array(32));
const nlToken = btoa(String.fromCharCode(...nlTokenBytes)).replace(/[/+]/g, '').slice(0, 32);
await putR2(env, 'acreetionos-hosting', key, {
email: body.email, subscribed: new Date().toISOString(), unsubscribe_token: nlToken
});
return new Response(JSON.stringify({ success: true, message: 'Subscribed to newsletter' }), { headers: corsHeaders({ headers: { get: () => '' } }) });
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: corsHeaders({ headers: { get: () => '' } }) });
}
}
async function handleNewsletterUnsubscribe(request, env) {
const email = request.url.searchParams?.get?.('email') || '';
const token = request.url.searchParams?.get?.('token') || '';
if (!email || !token) return new Response(JSON.stringify({ error: 'email and token required' }), { status: 400, headers: corsHeaders({ headers: { get: () => '' } }) });
const key = 'nl-subscriber-' + email.replace(/[@.]/g, '_');
const record = await getR2(env, 'acreetionos-hosting', key);
if (!record) return new Response(JSON.stringify({ error: 'Subscriber not found' }), { status: 404, headers: corsHeaders({ headers: { get: () => '' } }) });
if (record.unsubscribe_token !== token) return new Response(JSON.stringify({ error: 'Invalid token' }), { status: 403, headers: corsHeaders({ headers: { get: () => '' } }) });
await deleteR2(env, 'acreetionos-hosting', key);
return new Response(JSON.stringify({ success: true, message: 'Unsubscribed from newsletter' }), { headers: corsHeaders({ headers: { get: () => '' } }) });
}
// ─── 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 vtDisabled = [];
let quota = await getScanQuota(env);
// Reset VT quota if the daily window has expired
if (quota.vt_reset && Date.now() > quota.vt_reset) {
quota.vt_remaining = 500;
quota.vt_reset = Date.now() + 86400000;
quota.vt_disabled = false;
delete quota.vt_disabled_at;
await saveScanQuota(env, quota);
}
let useVt = !quota.vt_disabled && env.SCAN_MASTER;
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.SCAN_MASTER, '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.SCAN_MASTER }
});
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,