Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
4292 lines (3925 loc) · 199 KB
/
Copy pathserver.js
File metadata and controls
4292 lines (3925 loc) · 199 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
// hyadeOS builder note: This file is part of the runtime that powers the OS. It defines how the desktop, login flow, or app behavior is built for contributors.
// hyadeOS Backend (kernel/server.js) - (C) 2026 mariowstech and the hyadeOS team
// Licensed under the Apache License, Version 2.0; you can use this file if you give credits to the original creators and you may not use this file except in compliance with the License.
// Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
const { envVar } = require("./lib/env");
const express = require("express");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const fs = require("fs");
const path = require("path");
const os = require("os");
const crypto = require("crypto");
const multer = require("multer");
const cron = require('node-cron');
const childProcess = require('child_process');
// Never flash a console window on Windows for helper commands (netsh, git, powershell...).
const exec = (command, options, callback) => {
if (typeof options === 'function') { callback = options; options = {}; }
return childProcess.exec(command, { windowsHide: true, ...(options || {}) }, callback);
};
const spawn = (command, args, options) => {
if (!Array.isArray(args)) { options = args; args = []; }
return childProcess.spawn(command, args, { windowsHide: true, ...(options || {}) });
};
// Load local overrides (e.g. HYADEOS_MAIL_RELAY_URL) from system/.env without overriding real env vars.
(function loadEnvFile() {
const envPath = path.join(__dirname, ".env");
if (!fs.existsSync(envPath)) return;
fs.readFileSync(envPath, "utf8").split(/\r?\n/).forEach(line => {
const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);
if (!match || process.env[match[1]] !== undefined) return;
process.env[match[1]] = match[2].replace(/^(["'])(.*)\1$/, "$2");
});
})();
// This is the brain of hyadeOS when it is running in development mode.
// The backend owns the config file, login flow, desktop routes, and the app store.
// If you are building on top of the OS, this is the file to understand first.
const app = express();
// SECURITY (D-01): defence-in-depth Content-Security-Policy + hardening headers.
// The desktop and every app are served from this origin and loaded as same-origin
// iframes, so one policy set here covers them all. This is LAYER 1: it does NOT yet
// forbid inline scripts/handlers ('unsafe-inline' stays, because the whole UI is
// built on inline code — removing it is a separate, larger refactor together with
// sanitising the innerHTML sinks). What it DOES buy right now:
// - connect-src 'self' -> a successful XSS cannot exfiltrate data to a remote
// server or beacon out; every app already talks only to
// same-origin /api/* routes (the backend proxies outward).
// - script-src pinned -> no stage-2 payload can be pulled from an attacker CDN;
// only self + the CDN the OS genuinely uses are allowed.
// - object-src 'none', base-uri 'self', frame-ancestors 'self' -> kill <object>/
// <embed>, <base> hijacking and clickjacking/re-framing.
// The in-OS browser runs in a <webview> (its own browsing context), so external
// sites it visits are unaffected by this header.
//
// Third-party Store apps are the exception: they are served from a SEPARATE origin
// (APPS_ORIGIN, see "THIRD-PARTY APP ISOLATION" below) so they cannot reach this one.
const APPS_HOST = envVar("BIND_HOST") || "127.0.0.1";
const APPS_PORT = Number(envVar("APPS_PORT") || Number(envVar("PORT") || 3000) + 1);
const APPS_ORIGIN = `http://${APPS_HOST}:${APPS_PORT}`;
const CONTENT_SECURITY_POLICY = [
"default-src 'self'",
// 'unsafe-eval' is required by the Monaco editor (ACode); 'unsafe-inline' by the
// OS's inline handlers/scripts. cdnjs serves Monaco + JSZip.
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com",
"font-src 'self' data: https://fonts.gstatic.com https://cdnjs.cloudflare.com",
"img-src 'self' data: blob: https:",
"media-src 'self' data: blob:",
"connect-src 'self'",
// External iframes the shell embeds (homepage, chat widgets) are https only; the
// browser app itself uses a <webview>, not an iframe, so it is not constrained here.
`frame-src 'self' https: ${APPS_ORIGIN}`,
// Monaco (ACode) spins up its language worker from a data: URL. 'blob:' covers the
// common pattern; 'data:' is needed for this Monaco build. (Hosting Monaco from the
// bundled local copy in desktop/assets/vendor/monaco would let this drop to 'self'.)
"worker-src 'self' blob: data:",
"object-src 'none'",
"base-uri 'self'",
"frame-ancestors 'self'"
].join("; ");
app.use((req, res, next) => {
res.setHeader("Content-Security-Policy", CONTENT_SECURITY_POLICY);
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "no-referrer");
res.setHeader("X-Frame-Options", "SAMEORIGIN");
next();
});
const PORT = Number(envVar("PORT") || 3000);
if (!Number.isInteger(PORT) || PORT < 1 || PORT > 65535) {
throw new Error('HYADEOS_PORT must be a valid TCP port');
}
const currentOS = process.platform;
const SERVER_EXIT_CODES = Object.freeze({ SHUTDOWN: 20, UPDATE_RESTART: 21, KERNEL_REBOOT: 22 });
const BACKEND_INSTANCE_ID = envVar("BACKEND_INSTANCE_ID") || null;
let httpServer = null;
let serverExitStarted = false;
const SOTA_VERSION_URL = envVar("SOTA_VERSION_URL") ||
"https://api.github.com/repos/hyadeOSS/SOTA/contents/version.json?ref=main";
const SOTA_COMPONENTS = new Set([
"calculator", "explorer", "feedback", "help", "music", "notes", "settings",
"store", "terminal", "desktop"
]);
// Pure version & URL-validation helpers live in ./lib/validation.js so they can be
// unit-tested without booting the server (see system/test/validation.test.js).
// Semantics unchanged:
// - isNewerVersion: the updater only ever offers a strictly NEWER build (no silent
// downgrade); unparseable versions fall back to "different means newer".
// - isAllowedRepoUrl (SECURITY A-07 adjacent): store apps clone/pull/update ONLY from
// https github.com / raw.githubusercontent.com repo URLs — never a local path, a
// non-https transport, or an "ext::"/option-injection URL.
const {
parseVersion,
comparePrerelease,
compareVersions,
isNewerVersion,
updateOffer,
rolloutBucket,
getRawGithubUrl,
isAllowedRepoUrl,
getRepoRawUrls
} = require("./lib/validation");
// A random id for this install, kept in config.json. Only used to place the install in a
// staged rollout (see updateOffer); it never leaves the computer.
function getInstallId() {
if (typeof config.installId !== "string" || !/^[0-9a-f]{32}$/.test(config.installId)) {
config.installId = crypto.randomBytes(16).toString("hex");
saveConfig();
}
return config.installId;
}
const { createRollbackPoint, readRollbackPoint } = require("./lib/rollback");
const { createMailClient } = require("./lib/mail");
const { createSessions, createPasswordGuard } = require("./lib/session");
const { createUsers, OWNER_ID, withinHours } = require("./lib/users");
const { createZip, readZip, extractZip } = require("./lib/zip");
const platformLayer = require("./lib/platform");
const { LEGACY_TWM_FILE, isListedDesktop } = require("./lib/legacy-names");
const { releaseZipUrl, downloadReleaseZip, stageReleaseZip } = require("./lib/release-zip");
function readStagedVersion(stagePath) {
try { return JSON.parse(fs.readFileSync(path.join(stagePath, "version.json"), "utf8")).version || null; }
catch (e) { return null; }
}
// Read a repo's declared version from its version.json (the app author's own file).
async function fetchRepoVersion(repoUrl) {
for (const url of getRepoRawUrls(repoUrl, "version.json")) {
try {
const r = await fetch(url);
if (!r.ok) continue;
const data = JSON.parse(await r.text());
if (data && typeof data.version === "string") return data.version;
} catch (e) { /* try next branch */ }
}
return null;
}
// Read the version.json an installed app shipped with (local copy).
function readInstalledAppVersion(appId) {
try {
const p = path.join(__dirname, "desktop", "apps", appId, "version.json");
const data = JSON.parse(fs.readFileSync(p, "utf8"));
return (data && typeof data.version === "string") ? data.version : null;
} catch (e) { return null; }
}
// --- UPDATE AUTHENTICITY (A-07) ---
// The system updater clones the official repo over HTTPS. That protects the download in
// transit but not against a compromised source: whoever controls the repository controls
// both the code and any plain hash list. Real authenticity needs a signature checked
// against a key that ships with the device.
//
// Opt-in by presence of update-pubkey.pem (created by tools/release-keys.js). When it is
// present, the updater REFUSES any release whose release-manifest.json is not signed by
// the matching private key or whose files do not match it (lib/update-checks.js).
// When it is absent, updates proceed unsigned and a warning is logged.
const updatePubKeyFile = path.join(__dirname, "update-pubkey.pem");
function getUpdatePublicKey() {
try { return fs.readFileSync(updatePubKeyFile, "utf8"); } catch (e) { return null; }
}
// --- FILESYSTEM INTEGRITY / VERIFIED BOOT (tamper detection) ---
// The recovery screen offers "verify filesystem integrity". This backs it with a real
// check: a signed manifest (system/integrity-manifest.json, map of path -> sha256)
// records the hashes of the files that make up a stock build. We re-hash those files
// and report any that were modified, replaced or removed. This is the hyadeOS analog
// of Android verified boot: if a locked system (flashing NOT unlocked) has been
// tampered with, the UI should refuse and prompt the user to reflash clean stock.
//
// Opt-in by presence of the manifest; its own signature is verified against
// update-pubkey.pem so a tamperer cannot simply rewrite the manifest to match.
const integrityManifestFile = path.join(__dirname, "integrity-manifest.json");
function sha256File(absPath) {
return crypto.createHash("sha256").update(fs.readFileSync(absPath)).digest("hex");
}
function verifyFilesystemIntegrity() {
let raw;
try { raw = fs.readFileSync(integrityManifestFile); }
catch (e) { return { available: false, reason: "No integrity manifest on this build." }; }
// The manifest must itself be authentic, or tamper detection is pointless.
const pubKey = getUpdatePublicKey();
let signatureVerified = false;
if (pubKey) {
try {
const sig = Buffer.from(fs.readFileSync(integrityManifestFile + ".sig", "utf8").trim(), "base64");
signatureVerified = crypto.verify(null, raw, pubKey, sig);
} catch (e) { signatureVerified = false; }
if (!signatureVerified) {
return { available: true, signed: true, signatureVerified: false, tampered: true,
reason: "The integrity manifest itself is missing a valid signature.", modified: [], missing: [] };
}
}
let manifest;
try { manifest = JSON.parse(raw.toString()); } catch (e) { return { available: false, reason: "Manifest is not valid JSON." }; }
const files = (manifest && manifest.files) || {};
const modified = [], missing = [];
for (const [rel, expected] of Object.entries(files)) {
// Keep the manifest inside the install tree; never let it point elsewhere.
const abs = path.resolve(__dirname, rel);
if (abs !== __dirname && !abs.startsWith(__dirname + path.sep)) { modified.push(rel); continue; }
try {
if (sha256File(abs) !== expected) modified.push(rel);
} catch (e) { missing.push(rel); }
}
const tampered = modified.length > 0 || missing.length > 0;
return {
available: true,
signed: !!pubKey,
signatureVerified: pubKey ? signatureVerified : undefined,
tampered,
modified,
missing,
// Verified-boot behaviour: a tampered, still-locked system should be sent to recovery.
locked: !config.allowFlashing,
recommendReflash: tampered && !config.allowFlashing
};
}
function exitAfterServerClose(exitCode) {
if (serverExitStarted) return;
serverExitStarted = true;
if (!httpServer) {
process.exit(exitCode);
return;
}
const forceExitTimer = setTimeout(() => process.exit(exitCode), 1500);
httpServer.close(() => {
clearTimeout(forceExitTimer);
process.exit(exitCode);
});
setTimeout(() => httpServer.closeAllConnections(), 250);
}
function hasValidShutdownToken(req) {
const expected = envVar("SHUTDOWN_TOKEN");
if (!expected) return false;
const supplied = req.get('authorization') || '';
const expectedBuffer = Buffer.from(`Bearer ${expected}`);
const suppliedBuffer = Buffer.from(supplied);
return suppliedBuffer.length === expectedBuffer.length &&
crypto.timingSafeEqual(suppliedBuffer, expectedBuffer);
}
function getRawGithubEulaUrls(repoUrl) {
if (!repoUrl) return [];
const cleanUrl = repoUrl.replace(/\.git$/, '');
const match = cleanUrl.match(/github\.com\/([^/]+\/[^/]+)/);
if (!match) return [];
const files = ['EULA.txt', 'LICENSE', 'LICENSE.txt', 'EULA', 'eula.txt', 'license.txt'];
const branches = ['main', 'master'];
let urls = [];
for (let b of branches) {
for (let f of files) {
urls.push(`https://raw.githubusercontent.com/${match[1]}/${b}/${f}`);
}
}
return urls;
}
// --- CONFIGURATION & MAILER ---
// This config object is the OS state file in a nutshell.
// It stores the current user, password hash, quick controls, and a few recovery flags.
// Everything that needs to survive a restart is written back into config.json here.
let config = {
passwordHash: null,
updateChannel: "stable",
quickSettings: {
wifi: true,
bluetooth: true,
dnd: false,
powerMode: "Balanced",
connectedWifi: "Wi-Fi",
connectedBt: "Bluetooth",
volume: 50,
isEthernet: false
}
};
const configFile = path.join(__dirname, "config.json");
if (fs.existsSync(configFile)) {
const loadedConfig = JSON.parse(fs.readFileSync(configFile, "utf8"));
config = { ...config, ...loadedConfig };
if (!config.updateChannel) config.updateChannel = "stable";
config.quickSettings = {
wifi: true,
bluetooth: true,
dnd: false,
powerMode: "Balanced",
connectedWifi: "Wi-Fi",
connectedBt: "Bluetooth",
isEthernet: false,
...(loadedConfig.quickSettings || {})
};
}
// Emails go through the hyadeOS mail relay (lib/mail.js): no mail password on the device.
const mail = createMailClient({
relayUrl: envVar("MAIL_RELAY_URL") || "https://mariowos-mail.mariowos.workers.dev",
errorLogFile: path.join(__dirname, "mail-error.log")
});
function saveConfig() {
fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
}
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
function isValidEmail(email) {
return typeof email === "string" && email.length <= 254 && EMAIL_RE.test(email.trim());
}
// One-time codes are generated, stored and checked by the mail relay.
const sendCodeEmail = (purpose, email) => mail.sendCode(purpose, email, config.username);
const checkCode = (purpose, email, code) => mail.checkCode(purpose, email, code);
// --- SESSION AUTHENTICATION (A-02) --- see lib/session.js
// SHA-256 of session keys that were once published in the GitHub repositories. Anyone
// could sign a session with them, so a device still using one gets a fresh key (its
// user simply logs in again).
const LEAKED_SESSION_KEY_HASHES = new Set([
"2feed71c3d843835e71c2a9963de5c671cd0ed0ab4da984466210bf7e2f0b9b2"
]);
const { issueSession, clearSession, hasValidSession, readSession, signAppToken, verifyAppToken } = createSessions({
keyFile: path.join(__dirname, "session.key"),
leakedKeyHashes: LEAKED_SESSION_KEY_HASHES,
secureCookie: envVar("SECURE_COOKIE") === "1"
});
const { comparePassword, lockSeconds: passwordLockSeconds } = createPasswordGuard((candidate, hash) => bcrypt.compare(candidate, hash));
const users = createUsers({ baseDir: __dirname, getConfig: () => config, saveConfig });
// Standard (non-admin) accounts: whatever installs software, runs commands or changes the
// system for everyone belongs to administrators. Enforced here, whatever the UI shows.
const ADMIN_ONLY_ROUTES = [
/^\/api\/store\/(install|uninstall|do-upgrade|publish|eula|auto-update|app-permissions)\b/,
/^\/api\/remote\/exec\b/, /^\/api\/sandbox\//, /^\/api\/recovery\//,
/^\/api\/system\/(factory-reset|reset-settings|reset-desktop|restore|backup|boot-logo|update-channel|keyring|ota-update|sota-update|health-report)\b/,
/^\/api\/users\/(create|update|delete|reset-password|guest|limits)\b/,
/^\/api\/rules\/(save|enabled)\b/,
/^\/(save-settings|clear-settings|set-password|clear-password|upload-wallpaper|upload-live-wallpaper)$/,
/^\/api\/wallpaper\/live\/remove$/, /^\/api\/preferences$/
];
// Reading is fine, except where the read itself acts or hands out secrets.
const ADMIN_ONLY_READS = /^\/api\/system\/(backup|keyring|ota-update|sota-update|health-report)\b/;
function requireAdminFor(req, res, next) {
if (req.user?.admin || !ADMIN_ONLY_ROUTES.some(route => route.test(req.path))) return next();
if ((req.method === "GET" || req.method === "HEAD") && !ADMIN_ONLY_READS.test(req.path)) return next();
res.status(403).json({ success: false, code: "ADMIN_ONLY", error: "Only an administrator can do this." });
}
// Routes that must stay reachable WITHOUT a session: the login/recovery flow itself,
// health checks, and the Electron shell's own token-authenticated power controls.
const PREAUTH_POST = new Set([
"/login", "/set-password", "/forgot-password", "/reset-password",
"/api/email/send-code", "/api/email/verify-code", "/api/system/frp-unlock",
"/api/system/shutdown", "/api/system/reboot"
]);
function requireSession(req, res, next) {
// Reads are left to the route-level checks already in place; this gate covers every
// state-changing method, which is where the dangerous routes live.
if (req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return next();
if (PREAUTH_POST.has(req.path)) return next();
// Fresh install / no password yet: nothing to protect, let setup proceed.
if (!config.passwordHash) return next();
if (hasValidSession(req)) return next();
return res.status(401).json({ success: false, error: "Authentication required. Please log in again." });
}
// --- PER-APP ENDPOINT PERMISSIONS (transparent capability model) ---
// Goal: let only the app that owns an endpoint call it (e.g. only the Terminal app
// may call the terminal/exec routes). This is the HONEST version of that idea:
// - The rules live in a plain, readable file (system/app-permissions.json), not an
// obfuscated blob. Obscurity is not a security boundary; hiding the rules would
// only make auditing harder without stopping anyone.
// - It is OFF by default (`enforced: false`) so it never breaks apps until the
// desktop shell is wired to mint and send per-app tokens (see /api/app/token).
// - HONEST LIMITATION: apps run as same-origin iframes, so this gives
// least-privilege-by-convention and accountability, NOT hard isolation against a
// malicious same-origin app. Real isolation would require per-app origins
// (separate partitions / cross-origin frames) — a larger frontend change.
const appPermissionsFile = path.join(__dirname, "app-permissions.json");
function loadAppPermissions() {
try {
const data = JSON.parse(fs.readFileSync(appPermissionsFile, "utf8"));
return { enforced: !!data.enforced, rules: Array.isArray(data.rules) ? data.rules : [] };
} catch (e) { return { enforced: false, rules: [] }; }
}
function enforceAppPermissions(req, res, next) {
const perms = loadAppPermissions();
if (!perms.enforced) return next();
const rule = perms.rules.find(r => typeof r.prefix === "string" && req.path.startsWith(r.prefix));
if (!rule) return next(); // endpoint not restricted to a specific app
const payload = verifyAppToken(req.get("x-app-token"));
if (!payload || !Array.isArray(rule.apps) || !rule.apps.includes(payload.appId)) {
return res.status(403).json({ success: false, error: "This app is not allowed to use this endpoint." });
}
next();
}
// --- THIRD-PARTY APP ISOLATION ---
// Store apps from developers other than the hyadeOS team run on their own origin
// (APPS_ORIGIN, a second port), not as same-origin iframes of the shell. The browser
// then keeps them away from the shell's DOM, cookies and storage, and:
// - they cannot READ this API: no CORS headers are ever sent to them;
// - they cannot WRITE to it: every state-changing request carrying a foreign Origin
// is refused below (this also stops any other web page from posting here);
// - they cannot sneak back onto this origin: their files are not served here.
// "hyadeoss" is the account name before the rename: apps installed back then still point at it.
const TRUSTED_APP_OWNERS = new Set(["hyadeos", "hyadeoss", "mariowstech"]);
function isThirdPartyApp(installed) {
if (!installed || !installed.repoUrl) return false; // built into the OS
const owner = String(installed.repoUrl).match(/^https:\/\/(?:raw\.githubusercontent\.com|github\.com)\/([^/]+)\//i);
return !owner || !TRUSTED_APP_OWNERS.has(owner[1].toLowerCase());
}
const thirdPartyAppIds = () => new Set((config.installedApps || []).filter(isThirdPartyApp).map(installed => installed.appId));
const SHELL_ORIGINS = new Set([`http://127.0.0.1:${PORT}`, `http://localhost:${PORT}`, `http://${APPS_HOST}:${PORT}`]);
function rejectForeignWrites(req, res, next) {
if (req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return next();
const origin = req.get("origin");
// No Origin: a non-browser client on this machine (the launcher, curl). Same origin: the shell.
if (!origin || SHELL_ORIGINS.has(origin)) return next();
return res.status(403).json({ success: false, error: "Requests from other origins are not allowed." });
}
app.use(rejectForeignWrites);
app.use("/desktop/apps/:appId", (req, res, next) => thirdPartyAppIds().has(req.params.appId)
? res.status(403).send("This app runs in its own sandbox.") : next());
app.use(bodyParser.urlencoded({ extended: true }));
// Notes can hold pasted images, so their route gets its own larger body limit (below).
const jsonParser = express.json();
const OWN_BODY_PARSER = new Set(["/api/system/notes", "/api/system/files/upload", "/api/system/files/upload-raw", "/api/users/restore"]);
app.use((req, res, next) => OWN_BODY_PARSER.has(req.path) ? next() : jsonParser(req, res, next));
app.use(requireSession);
app.use(users.middleware(readSession, clearSession));
app.use(requireAdminFor);
app.use(enforceAppPermissions);
// Store SDK: app manifests (hyadeos.json) and the permissions granted to each installed app.
const { registerStoreSdkRoutes, resolveGrantedPermissions } = require("./lib/store-sdk-routes");
registerStoreSdkRoutes(app, { getConfig: () => config, saveConfig, appsDir: path.join(__dirname, "desktop/apps") });
require("./spotify").registerSpotifyRoutes(app, {
getConfig: () => config, saveConfig, hasValidSession, port: PORT
});
const requireAuthJson = (req, res, next) => (!config.passwordHash || hasValidSession(req))
? next() : res.status(401).json({ success: false, error: "Authentication required. Please log in again." });
require("./media-session").registerMediaSessionRoutes(app, { requireAuth: requireAuthJson });
require("./bluetooth-watch").registerBluetoothWatchRoutes(app, { requireAuth: requireAuthJson });
require("./online-services").registerOnlineServiceRoutes(app, { getConfig: () => config, saveConfig, requireAuth: requireAuthJson });
app.get('/api/system/health', (req, res) => {
res.set('Cache-Control', 'no-store');
// `updating`: the launcher must not restart the shell while an update is being applied.
res.json({ status: 'ok', instanceId: BACKEND_INSTANCE_ID, updating: systemUpdateInProgress });
});
// --- SYSTEM HEALTH (Settings › General › System health) ---
// One read-only report: version and update state, memory, disk, and the recent problems
// from the log, each tagged with a `kind` the page explains in plain words.
const HEALTH_LOG_FILE = path.join(__dirname, "hyadeos.log");
const HEALTH_PROBLEMS = [
["file-in-use", /\bEPERM\b|\bEBUSY\b|resource busy|operation not permitted/i],
["restart-needed", /No handler registered/i],
["offline", /ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|fetch failed|getaddrinfo/i],
["port-in-use", /EADDRINUSE/i],
["missing-file", /\bENOENT\b|Cannot find module/i],
["keys", /^\[keys\]/i],
["update", /update|rollback/i]
];
function recentLogProblems(limit = 12) {
let text = "";
try {
const stat = fs.statSync(HEALTH_LOG_FILE);
const start = Math.max(0, stat.size - 256 * 1024);
const fd = fs.openSync(HEALTH_LOG_FILE, "r");
const buffer = Buffer.alloc(stat.size - start);
fs.readSync(fd, buffer, 0, buffer.length, start);
fs.closeSync(fd);
text = buffer.toString("utf8");
} catch { return { available: false, problems: [] }; }
const problems = [];
for (const line of text.split(/\r?\n/)) {
const clean = line.trim();
if (!clean || !/error|fail|warn|EPERM|ENOENT|EADDRINUSE|ECONN|ETIMEDOUT|No handler/i.test(clean) || /^\s*at\s/.test(clean)) continue;
const kind = (HEALTH_PROBLEMS.find(([, pattern]) => pattern.test(clean)) || ["other"])[0];
const last = problems[problems.length - 1];
if (last && last.text === clean.slice(0, 300)) { last.count++; continue; }
problems.push({ kind, text: clean.slice(0, 300), count: 1 });
}
return { available: true, problems: problems.slice(-limit).reverse() };
}
app.get("/api/system/health-report", (req, res) => {
let version = null;
try { version = JSON.parse(fs.readFileSync(path.join(__dirname, "version.json"), "utf8")).version; } catch {}
let disk = null;
try { const s = fs.statfsSync(__dirname); disk = { free: s.bavail * s.bsize, total: s.blocks * s.bsize }; } catch {}
const rollback = readRollbackPoint(__dirname);
res.set("Cache-Control", "no-store");
res.json({
version, channel: getUpdateChannel(), platform: `${os.type()} ${os.release()}`, node: process.version,
uptime: Math.round(process.uptime()), systemUptime: Math.round(os.uptime()),
memory: { kernel: process.memoryUsage().rss, free: os.freemem(), total: os.totalmem() },
disk,
lastUpdate: rollback ? { from: rollback.fromVersion || null, to: rollback.toVersion || null, at: rollback.createdAt || null, rolledBack: !!rollback.rolledBack } : null,
apps: Array.isArray(config.installedApps) ? config.installedApps.length : 0,
log: recentLogProblems()
});
});
// The installed version and its notes, for the desktop's "what's new" cards after an update.
app.get('/api/system/version', (req, res) => {
try {
const { version, changelog } = JSON.parse(fs.readFileSync(path.join(__dirname, 'version.json'), 'utf8'));
res.json({ version: String(version || ''), changelog: String(changelog || '') });
} catch { res.status(404).json({ version: null }); }
});
app.get('/api/system/boot-assets', (req, res) => {
const bootModeFile = path.join(__dirname, 'boot-mode.json');
const bootMode = fs.existsSync(bootModeFile)
? JSON.parse(fs.readFileSync(bootModeFile, 'utf8'))
: { verbose: false };
if (typeof bootMode.verbose !== 'boolean') throw new Error('Invalid verbose boot setting');
const iconDirectory = path.join(__dirname, 'desktop', 'assets', 'icons');
const icons = fs.readdirSync(iconDirectory, { withFileTypes: true })
.filter(entry => entry.isFile() && /\.(avif|gif|jpe?g|png|svg|webp)$/i.test(entry.name))
.map(entry => `/desktop/assets/icons/${encodeURIComponent(entry.name)}`);
const optionalAssets = [
'/desktop/assets/wallpaper.factory.png',
'/desktop/assets/wallpaper.user.png',
'/desktop/assets/avatar.png',
'/desktop/assets/avatar.user.png',
'/desktop/assets/login.png',
'/desktop/assets/next.png',
'/desktop/assets/back.png'
];
const customBootLogoPath = path.join(__dirname, 'desktop', 'assets', 'bootlogo.user.png');
const bootLogo = fs.existsSync(customBootLogoPath)
? '/desktop/assets/bootlogo.user.png'
: '/desktop/assets/icons/stars.png';
res.set('Cache-Control', 'no-store');
res.json({ requiredWallpaper: '/desktop/assets/wallpaper.factory.png', icons, optionalAssets, bootLogo, verbose: bootMode.verbose });
});
app.post('/api/system/shutdown', (req, res) => {
if (envVar("MANAGED_BACKEND") !== '1' || !hasValidShutdownToken(req)) {
return res.status(403).json({ success: false, error: 'Shutdown is only available to the trusted Electron shell' });
}
res.status(202).json({ success: true });
setTimeout(() => exitAfterServerClose(SERVER_EXIT_CODES.SHUTDOWN), 100);
});
app.post('/api/system/reboot', (req, res) => {
if (envVar("MANAGED_BACKEND") !== '1' || !hasValidShutdownToken(req)) {
return res.status(403).json({ success: false, error: 'Kernel reboot is only available to the trusted Electron shell' });
}
res.status(202).json({ success: true });
setTimeout(() => exitAfterServerClose(SERVER_EXIT_CODES.KERNEL_REBOOT), 100);
});
app.get('/boot', (req, res) => {
res.sendFile(path.join(__dirname, 'boot.html'));
});
function serveUploadedImage(filePath, imageName) {
return (req, res, next) => {
let descriptor;
let signature;
try {
descriptor = fs.openSync(filePath, 'r');
signature = Buffer.alloc(8);
fs.readSync(descriptor, signature, 0, signature.length, 0);
} catch (error) {
if (error.code === 'ENOENT') return next();
return next(error);
} finally {
if (descriptor !== undefined) fs.closeSync(descriptor);
}
const isPng = signature.equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
const isJpeg = signature[0] === 0xff && signature[1] === 0xd8 && signature[2] === 0xff;
if (!isPng && !isJpeg) return res.status(415).send(`The saved ${imageName} is not a supported PNG or JPEG image.`);
res.sendFile(filePath, {
headers: {
'Cache-Control': 'no-store',
'Content-Type': isJpeg ? 'image/jpeg' : 'image/png'
}
}, error => {
if (error) next(error);
});
};
}
app.get('/desktop/assets/avatar.user.png', serveUploadedImage(
path.join(__dirname, 'desktop', 'assets', 'avatar.user.png'),
'profile picture'
));
app.get('/desktop/assets/bootlogo.user.png', serveUploadedImage(
path.join(__dirname, 'desktop', 'assets', 'bootlogo.user.png'),
'boot logo'
));
// A language is available when it is listed in locales/languages.json and has its
// locales/<code>.json (English is built into the pages and needs no file).
const LOCALES_DIR = path.join(__dirname, "desktop", "assets", "locales");
function isAvailableLanguage(code) {
if (code === "auto" || code === "en") return true;
if (typeof code !== "string" || !/^[a-z]{2,3}(-[a-z0-9]{2,4})?$/.test(code)) return false;
return Object.hasOwn(readLanguages(), code) && fs.existsSync(path.join(LOCALES_DIR, `${code}.json`));
}
function readLanguages() {
try { return { en: "English", ...JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, "languages.json"), "utf8")) }; }
catch { return { en: "English" }; }
}
// "auto" follows the computer: Electron sends its language as Accept-Language.
function resolveLanguage(preference, acceptLanguage) {
if (preference !== "auto") return preference && preference !== "en" && isAvailableLanguage(preference) ? preference : "en";
for (const part of String(acceptLanguage || "").toLowerCase().split(",")) {
const tag = part.split(";")[0].trim();
for (const code of [tag, tag.split("-")[0]]) if (code && code !== "auto" && isAvailableLanguage(code)) return code;
}
return "en";
}
// The page's language and translations as a script, so they are ready before the
// page's own scripts run (see desktop/assets/i18n.js).
app.get("/desktop/assets/i18n-data.js", (req, res) => {
const preference = config.language || "en";
const language = resolveLanguage(preference, req.get("accept-language"));
let dictionary = {};
if (language !== "en") {
try { dictionary = JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${language}.json`), "utf8")); } catch {}
}
const data = JSON.stringify({ preference, language, languages: readLanguages(), dictionary }).replace(/</g, "\\u003c");
res.set({ "Content-Type": "application/javascript; charset=utf-8", "Cache-Control": "no-store" });
res.send(`window.__hyadeOSI18nData = ${data};\n`);
});
// Static files are the actual desktop shell. The login screen, settings pages, and app folders
// are served as normal web assets from the filesystem, which keeps the OS feel web-based and easy to tweak.
// The notes database lives under desktop/ for historical reasons: never serve it as a static file.
app.get("/desktop/notes-db.json", (req, res) => res.status(404).end());
// Home folders are read through the file API, as their owner: never as plain static files.
app.use("/desktop/home", (req, res) => res.status(404).end());
app.use("/desktop", express.static(path.join(__dirname, "desktop")));
app.use("/loginui", express.static(path.join(__dirname, "loginui")));
app.use("/lockscreen", express.static(path.join(__dirname, "lockscreen")));
app.get('/desktop/apps/settings/assets/you.html', (req, res, next) => {
next();
});
// SECURITY (M-04): every upload caps its file size so a client cannot exhaust disk or
// memory. Image uploads also restrict the MIME type. Shared cap for images:
const IMAGE_UPLOAD_LIMIT = { fileSize: 8 * 1024 * 1024 };
const avatarUpload = multer({
limits: IMAGE_UPLOAD_LIMIT,
storage: multer.diskStorage({
// Each account has its own picture (the owner's is desktop/assets/avatar.user.png).
destination: (req, file, cb) => { const target = users.avatarOf(users.find(req.user?.id)); fs.mkdirSync(path.dirname(target), { recursive: true }); cb(null, path.dirname(target)); },
filename: (req, file, cb) => cb(null, path.basename(users.avatarOf(users.find(req.user?.id))))
}),
fileFilter: (req, file, cb) => cb(null, ["image/png", "image/jpeg"].includes(file.mimetype))
});
app.post("/upload-avatar", avatarUpload.single("avatar"), (req, res) => {
if (!req.file) return res.status(400).json({ success: false, error: "No file uploaded" });
res.json({ success: true, message: "Avatar uploaded successfully!" });
});
app.post("/reset-avatar", (req, res) => {
const avatarPath = users.avatarOf(users.find(req.user?.id));
if (fs.existsSync(avatarPath)) { fs.unlinkSync(avatarPath); }
res.json({ success: true, message: "Avatar reset!" });
});
const wallpaperUpload = multer({
limits: IMAGE_UPLOAD_LIMIT,
storage: multer.diskStorage({
destination: (req, file, cb) => cb(null, path.join(__dirname,"desktop/assets")),
filename: (req, file, cb) => cb(null, "wallpaper.user.png")
}),
fileFilter: (req, file, cb) => cb(null, ["image/png", "image/jpeg"].includes(file.mimetype))
});
// Live wallpaper (Settings › Wallpaper & Style › Live): one video or animated GIF, kept as
// desktop/assets/wallpaper.live.user.<ext>. Saved under a temporary name first, so a
// failed upload never removes the wallpaper already in use.
const LIVE_WALLPAPER_TYPES = { "video/mp4": "mp4", "video/webm": "webm", "image/gif": "gif" };
const LIVE_WALLPAPER_PATTERN = /^wallpaper\.live\.user\.(mp4|webm|gif)$/;
const liveWallpaperUpload = multer({
limits: { fileSize: 200 * 1024 * 1024 },
storage: multer.diskStorage({
destination: (req, file, cb) => cb(null, path.join(__dirname, "desktop/assets")),
filename: (req, file, cb) => cb(null, `wallpaper.live.upload-${process.pid}.${LIVE_WALLPAPER_TYPES[file.mimetype]}`)
}),
fileFilter: (req, file, cb) => cb(null, Object.hasOwn(LIVE_WALLPAPER_TYPES, file.mimetype))
});
function liveWallpaperFiles() {
try { return fs.readdirSync(path.join(__dirname, "desktop/assets")).filter(file => LIVE_WALLPAPER_PATTERN.test(file)); }
catch { return []; }
}
function removeLiveWallpaper() {
for (const file of liveWallpaperFiles()) fs.rmSync(path.join(__dirname, "desktop/assets", file), { force: true });
}
const bootLogoUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (req, file, cb) => cb(null, ["image/png", "image/jpeg"].includes(file.mimetype))
});
app.post("/api/system/set-volume", (req, res) => {
const { volume } = req.body;
if (volume === undefined) return res.status(400).json({ success: false, error: "Missing volume" });
const volNum = Math.max(0, Math.min(100, parseInt(volume, 10)));
let cmd = "";
if (currentOS === "linux") {
cmd = `amixer -D pulse sset Master ${volNum}% || amixer sset Master ${volNum}%`;
} else if (currentOS === "darwin") {
cmd = `osascript -e "set volume output volume ${volNum}"`;
} else if (currentOS === "win32") {
cmd = `echo Windows volume set to ${volNum}%`;
}
exec(cmd, (err) => {
if (err) console.error("Volume sync error:", err.message);
config.quickSettings.volume = volNum;
fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
res.json({ success: true, volume: volNum });
});
});
const appIconUpload = multer({
limits: IMAGE_UPLOAD_LIMIT,
storage: multer.diskStorage({
destination: (req, file, cb) => cb(null, path.join(__dirname, "desktop/assets")),
filename: (req, file, cb) => {
const safeId = req.body.id ? req.body.id.replace(/[^a-zA-Z0-9_-]/g, '') : "app";
cb(null, `icon_${safeId}_${Date.now()}.png`);
}
}),
fileFilter: (req, file, cb) => cb(null, ["image/png", "image/jpeg"].includes(file.mimetype))
});
app.get("/api/system/desktops", (req, res) => {
try {
const desktopDir = path.join(__dirname, "desktop");
const files = fs.readdirSync(desktopDir);
// A secondary desktop installed before the rename (com.hyadeoss.twm.html) is still listed (lib/legacy-names.js).
const desktops = files.filter(isListedDesktop);
res.json({ success: true, desktops });
} catch (err) {
res.json({ success: false, desktops: ["com.hyadeos.desktop.html"] });
}
});
let dailyEmailTask = null;
async function sendDiscordFlagsEmail() {
if (!config.email || !config.verified || !mail.configured) return;
if (!config.mailToken) {
console.warn("[mail] daily report skipped: verify your email again in Settings to enable it.");
return;
}
const result = await mail.sendDailyReport({ email: config.email, token: config.mailToken, username: config.username });
if (result.ok) {
config.lastSent = Date.now();
saveConfig();
} else {
console.error("Failed to send daily email:", result.error);
}
}
function scheduleDailyEmail() {
if (dailyEmailTask) dailyEmailTask.stop();
if (config.email && config.sendReports) {
dailyEmailTask = cron.schedule('0 9 * * *', async () => await sendDiscordFlagsEmail(), { timezone: "Europe/Rome" });
}
}
scheduleDailyEmail();
// --- QUICK SETTINGS & HARDWARE TOGGLES ---
// This is the Control Center layer. The desktop asks the backend what the system is doing
// with Wi‑Fi, Bluetooth, volume, Ethernet, and power mode, then renders that state to the user.
app.get("/api/system/quick-settings", (req, res) => {
const interfaces = os.networkInterfaces();
let isEthernet = false;
for (const [name, nets] of Object.entries(interfaces)) {
const lowerName = name.toLowerCase();
// Ignore wireless and virtual adapters
if (
lowerName.includes('wi-fi') ||
lowerName.includes('wlan') ||
lowerName.includes('wireless') ||
lowerName.includes('virtual') ||
lowerName.includes('vbox') ||
lowerName.includes('vmware') ||
lowerName.includes('vethernet') ||
lowerName.includes('wsl') ||
lowerName.includes('hyper-v') ||
lowerName.includes('tailscale') ||
lowerName.includes('zerotier') ||
lowerName.includes('vpn') ||
lowerName.includes('bluetooth')
) continue;
if (currentOS === 'darwin' && lowerName === 'en0') continue;
for (const net of nets) {
if (net.family === 'IPv4' && !net.internal) {
isEthernet = true;
break;
}
}
if (isEthernet) break;
}
config.quickSettings.isEthernet = isEthernet;
const finish = (realWifi) => {
config.quickSettings.connectedWifi = realWifi || "Disconnected";
if (config.quickSettings.connectedBt === "Wireless Headphones") {
config.quickSettings.connectedBt = "On";
}
res.json(config.quickSettings);
};
if (currentOS === "win32") {
exec('netsh wlan show interfaces', (err, stdout) => {
const match = !err && stdout ? stdout.match(/^\s*SSID\s*:\s*(.+)$/m) : null;
finish(match ? match[1].trim() : null);
});
} else {
// Linux (NetworkManager, then iwgetid) and macOS (networksetup): see lib/platform.js.
platformLayer.getWifiSsid(currentOS).then(finish, () => finish(null));
}
});
// Windows: Wi-Fi and Bluetooth go through lib/windows-radios.ps1, which needs no admin rights.
function runWindowsRadios(args, env = {}) {
const script = path.join(__dirname, "lib", "windows-radios.ps1");
return new Promise((resolve, reject) => {
childProcess.execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", script, ...args],
{ windowsHide: true, timeout: 30000, env: { ...process.env, ...env } }, (err, stdout) => {
if (err) return reject(err);
try {
const result = JSON.parse(stdout);
return result.success ? resolve(result) : reject(new Error(result.error || "Radio command failed"));
} catch (parseError) { reject(parseError); }
});
});
}
function setWifiPower(on) {
if (currentOS === "win32") return runWindowsRadios(["-Action", "set", "-Kind", "WiFi", "-On", on ? "1" : "0"]);
return platformLayer.setWifiPower(currentOS, on);
}
function setBluetoothPower(on) {
if (currentOS === "win32") return runWindowsRadios(["-Action", "set", "-Kind", "Bluetooth", "-On", on ? "1" : "0"]);
return platformLayer.setBluetoothPower(currentOS, on);
}
// Airplane mode turns every radio off and remembers how they were, to put them back after.
async function setAirplaneMode(on) {
const qs = config.quickSettings;
if (on) {
qs.radiosBeforeAirplane = { wifi: qs.wifi !== false, bluetooth: qs.bluetooth !== false };
await Promise.allSettled([setWifiPower(false), setBluetoothPower(false)]);
qs.wifi = false;
qs.bluetooth = false;
return;
}
const before = qs.radiosBeforeAirplane || { wifi: true, bluetooth: true };
await Promise.allSettled([setWifiPower(before.wifi), setBluetoothPower(before.bluetooth)]);
qs.wifi = before.wifi;
qs.bluetooth = before.bluetooth;
delete qs.radiosBeforeAirplane;
}
app.post("/api/system/quick-settings", async (req, res) => {
const { setting, value } = req.body;
if (!setting || value === undefined) {
return res.status(400).json({ success: false, error: "Dati mancanti" });
}
// --- HARDWARE POWER TOGGLES ---
// The saved state only changes once the hardware did, so the panel can't show a state it isn't in.
const hardware = { wifi: setWifiPower, bluetooth: setBluetoothPower, airplane: setAirplaneMode }[setting];
if (hardware) {
try {
await hardware(Boolean(value));
} catch (error) {
console.error(`${setting} toggle error:`, error.message);
return res.status(500).json({ success: false, error: error.message, quickSettings: config.quickSettings });
}
}
config.quickSettings[setting] = value;
fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
res.json({ success: true, quickSettings: config.quickSettings });
});
// Whether this machine has a battery at all: a plugged-in desktop and a fully charged laptop
// look the same to the page. The level and charging state then come live from the page.
let batteryPresence = null;
function detectBattery() {
return new Promise(resolve => {
if (currentOS === "linux") {
try { return resolve(fs.readdirSync("/sys/class/power_supply").some(name => name.startsWith("BAT"))); }
catch { return resolve(false); }
}
if (currentOS === "darwin") return exec("pmset -g batt", (err, stdout) => resolve(!err && stdout.includes("InternalBattery")));
if (currentOS === "win32") {
return childProcess.execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "(Get-CimInstance Win32_Battery | Measure-Object).Count"],
{ windowsHide: true, timeout: 15000 }, (err, stdout) => resolve(!err && parseInt(stdout, 10) > 0));
}
resolve(false);
});
}
app.get("/api/system/battery", async (req, res) => {
batteryPresence ??= detectBattery();
res.json({ present: await batteryPresence });
});
// --- CROSS-PLATFORM NETWORK & BLUETOOTH SCANNERS ---
// These routes are the OS compatibility layer. hyadeOS tries to detect what hardware is present
// on the host machine and then exposes a consistent Wi‑Fi/Bluetooth API to the desktop UI.
app.get("/api/system/ethernet-stats", (req, res) => {
const interfaces = os.networkInterfaces();
const ethIfaces = [];
for (const [name, nets] of Object.entries(interfaces)) {
const lowerName = name.toLowerCase();
// Ignore wireless and virtual adapters
if (
lowerName.includes('wi-fi') ||
lowerName.includes('wlan') ||
lowerName.includes('wireless') ||
lowerName.includes('virtual') ||
lowerName.includes('vbox') ||
lowerName.includes('vmware') ||
lowerName.includes('vethernet') ||
lowerName.includes('wsl') ||
lowerName.includes('hyper-v') ||
lowerName.includes('tailscale') ||
lowerName.includes('zerotier') ||
lowerName.includes('vpn') ||
lowerName.includes('bluetooth')