Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1676 lines (1548 loc) · 77.9 KB
/
Copy pathserver.js
File metadata and controls
1676 lines (1548 loc) · 77.9 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
#!/usr/bin/env node
/**
* Family Panel — Server with Home Assistant Integration
* Node.js 18+, zero external dependencies.
*
* Usage:
* node server.js
* node server.js --port 8080
*
* Configuration:
* Edit config.json — set ha_token, ha_url, port, etc.
* Environment variables override config.json values:
* FP_HA_TOKEN, FP_HA_URL, FP_PORT
*
* Diagnostic endpoint (open in browser to test HA connection):
* http://localhost:8080/api/ha/test
*/
'use strict';
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
// SHA-256 hash for admin password storage
function sha256(str) { return crypto.createHash('sha256').update(str).digest('hex'); }
// In-memory admin session tokens (cleared on server restart)
const ADMIN_SESSIONS = new Set();
// ─────────────────────────────────────────────────────────
// FP_DATA_DIR lets the data directory be moved (e.g. to a Docker named volume).
// Falls back to the app directory so existing non-Docker installs are unaffected.
const DATA_DIR = process.env.FP_DATA_DIR ? path.resolve(process.env.FP_DATA_DIR) : __dirname;
const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
let cfg = {};
try {
cfg = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
} catch (e) {
// If no config.json exists but env vars supply the essentials, continue with defaults
if (process.env.FP_HA_URL && process.env.FP_HA_TOKEN) {
console.warn(' ⚠ No config.json found — using FP_HA_URL / FP_HA_TOKEN env vars');
} else {
console.error(` ✗ Could not read config.json: ${e.message}`);
console.error(' Either create config.json or set FP_HA_URL and FP_HA_TOKEN env vars.');
process.exit(1);
}
}
// CLI --port flag overrides everything
const PORT = (() => {
const i = process.argv.indexOf('--port');
if (i !== -1) return parseInt(process.argv[i + 1], 10);
return parseInt(process.env.FP_PORT || cfg.port || '8080', 10);
})();
// Environment variables override config.json (useful for secrets in production)
const HA_URL = (process.env.FP_HA_URL || cfg.ha_url || '').replace(/\/$/, '');
const HA_TOKEN = process.env.FP_HA_TOKEN || cfg.ha_token || '';
// True only when a real token is set (not the example placeholder, not empty)
const HA_TOKEN_SET = HA_TOKEN.length > 20 && HA_TOKEN !== 'PASTE_YOUR_LONG_LIVED_TOKEN_HERE';
const CALENDARS_STATIC = cfg.calendars || [];
const STATE_ENTITIES_STATIC = cfg.state_entities || [];
// Resolve the real client IP, honouring X-Real-IP / X-Forwarded-For ONLY when
// the TCP connection arrives from a trusted proxy IP configured in Admin →
// Settings → Trusted Proxies. Loopback (127.0.0.1 / ::1) is always trusted.
// Headers are never trusted from unknown sources — external clients cannot spoof.
function getClientIP(req) {
const raw = req.socket.remoteAddress || '';
const socketIP = raw.startsWith('::ffff:') ? raw.slice(7) : raw;
const isLoopback = socketIP === '127.0.0.1' || socketIP === '::1' || socketIP === 'localhost';
const configured = getLiveData()?.settings?.trustedProxies || [];
if (isLoopback || configured.includes(socketIP)) {
const realIP = req.headers['x-real-ip'];
if (realIP) return realIP.trim();
const forwarded = req.headers['x-forwarded-for'];
if (forwarded) return forwarded.split(',')[0].trim();
}
return socketIP;
}
// Read live config from data.json (so admin changes take effect without restart)
function getLiveData() {
try { return JSON.parse(fs.readFileSync(DATA_FILE, 'utf8')); }
catch { return {}; }
}
function recordBlockedIP(clientIP) {
try {
const data = getLiveData();
data.settings = data.settings || {};
const log = data.settings.blockedIPLog || [];
const now = new Date().toISOString();
const cutoff = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
// Prune entries older than 7 days
const pruned = log.filter(e => (e.lastSeen || e.firstSeen || '') >= cutoff);
const existing = pruned.find(e => e.ip === clientIP);
if (existing) {
existing.lastSeen = now;
existing.count = (existing.count || 1) + 1;
} else {
pruned.push({ ip: clientIP, firstSeen: now, lastSeen: now, count: 1 });
}
data.settings.blockedIPLog = pruned;
fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2), 'utf8');
} catch { /* non-fatal */ }
}
function getCalendars() { const d = getLiveData(); return d.calendars || CALENDARS_STATIC; }
function getStateEntities() {
const d = getLiveData();
// Prefer the new structured fields; fall back to legacy state_entities array
const ids = new Set();
(d.topbar_buttons || []).forEach(b => { if (b.entity) ids.add(b.entity); });
(d.control_buttons || []).forEach(b => { if (b.entity) ids.add(b.entity); });
(d.sensors || []).forEach(s => { if (s.entity) ids.add(s.entity); });
((d.custom_dashboard || {}).widgets || []).forEach(w => { if (w.entity) ids.add(w.entity); });
if (ids.size) return [...ids];
return (d.state_entities || STATE_ENTITIES_STATIC).map(e => typeof e === 'string' ? e : e.id);
}
// ─────────────────────────────────────────────────────────
// PATHS & MIME
// ─────────────────────────────────────────────────────────
const ROOT = __dirname;
const DATA_FILE = path.join(DATA_DIR, 'data.json');
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.svg': 'image/svg+xml',
};
// ─────────────────────────────────────────────────────────
// HELPERS
// ─────────────────────────────────────────────────────────
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on('data', chunk => {
size += chunk.length;
if (size > 2_000_000) { req.destroy(); reject(new Error('Request body too large')); return; }
chunks.push(chunk);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function sendJSON(res, status, obj) {
const body = JSON.stringify(obj, null, 2);
const buf = Buffer.from(body, 'utf8');
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': buf.length,
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-store',
});
res.end(buf);
}
function sendFile(res, filePath) {
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found: ' + path.basename(filePath));
return;
}
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, {
'Content-Type': MIME[ext] || 'application/octet-stream',
'Content-Length': data.length,
'Cache-Control': 'no-store',
});
res.end(data);
});
}
// Extract path from request URL without using url.parse()
function getPathname(reqUrl) {
// reqUrl is like "/api/ha/states?foo=bar" — we only want the path part
const q = reqUrl.indexOf('?');
const raw = q === -1 ? reqUrl : reqUrl.slice(0, q);
return raw.replace(/\/+$/, '') || '/';
}
// ─────────────────────────────────────────────────────────
// HOME ASSISTANT HTTP CLIENT
// Uses Node's built-in http/https — no url.parse()
// ─────────────────────────────────────────────────────────
function haRequest(method, haPath, bodyObj) {
return new Promise((resolve, reject) => {
// Parse HA_URL once using WHATWG URL (no url.parse)
let base;
try {
base = new URL(HA_URL);
} catch (e) {
return reject(new Error(`HA_URL "${HA_URL}" is not a valid URL: ${e.message}`));
}
const isHttps = base.protocol === 'https:';
const lib = isHttps ? https : http;
const port = base.port ? parseInt(base.port, 10) : (isHttps ? 443 : 80);
const bodyStr = bodyObj != null ? JSON.stringify(bodyObj) : null;
const bodyBuf = bodyStr ? Buffer.from(bodyStr, 'utf8') : null;
const options = {
hostname: base.hostname,
port,
path: haPath, // already includes query string when needed
method,
headers: {
'Authorization': `Bearer ${HA_TOKEN}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
...(bodyBuf ? { 'Content-Length': bodyBuf.length } : {}),
},
};
const req = lib.request(options, res => {
const chunks = [];
res.on('data', c => chunks.push(c));
res.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
if (res.statusCode >= 400) {
console.error(` ✗ HA ${method} ${haPath} → HTTP ${res.statusCode}`);
console.error(` Raw body: ${raw.slice(0, 500)}`);
}
let parsed;
try { parsed = JSON.parse(raw); }
catch { parsed = raw; }
resolve({ status: res.statusCode, body: parsed, raw });
});
});
req.setTimeout(10000, () => {
req.destroy();
reject(new Error(`HA request timed out after 10s: ${method} ${haPath}`));
});
req.on('error', err => {
reject(new Error(`HA connection error (${method} ${haPath}): ${err.message}`));
});
if (bodyBuf) req.write(bodyBuf);
req.end();
});
}
// Simple HTTPS GET → parsed JSON (for Open-Meteo proxy)
function httpsGetJSON(url) {
return new Promise((resolve, reject) => {
https.get(url, { headers: { 'User-Agent': 'family-panel/1.0' } }, res => {
let buf = '';
res.on('data', d => buf += d);
res.on('end', () => {
try { resolve(JSON.parse(buf)); }
catch (e) { reject(new Error(`JSON parse failed: ${buf.slice(0, 80)}`)); }
});
}).on('error', reject);
});
}
// Convenience: GET a single HA state
async function haGetState(entityId) {
const r = await haRequest('GET', `/api/states/${entityId}`);
if (r.status === 404) return { state: 'unknown', attributes: {} };
if (r.status >= 400) return { state: 'unavailable', attributes: {} };
return { state: r.body.state ?? 'unknown', attributes: r.body.attributes ?? {} };
}
// Convenience: GET calendar events for a date range
async function haGetCalendar(entityId, startISO, endISO) {
const qs = `start=${encodeURIComponent(startISO)}&end=${encodeURIComponent(endISO)}`;
const r = await haRequest('GET', `/api/calendars/${entityId}?${qs}`);
if (!Array.isArray(r.body)) {
console.warn(` ⚠ Calendar ${entityId}: unexpected response`, JSON.stringify(r.body).slice(0, 100));
return [];
}
return r.body;
}
// ─────────────────────────────────────────────────────────
// IMMICH HTTP CLIENT
// ─────────────────────────────────────────────────────────
function immichRequest(immichUrl, apiKey, immichPath, asBuffer, postBody) {
return new Promise((resolve, reject) => {
let base;
try { base = new URL(immichUrl); }
catch (e) { return reject(new Error(`Immich URL "${immichUrl}" is invalid: ${e.message}`)); }
const isHttps = base.protocol === 'https:';
const lib = isHttps ? https : http;
const port = base.port ? parseInt(base.port, 10) : (isHttps ? 443 : 80);
const bodyStr = postBody ? JSON.stringify(postBody) : null;
const options = {
hostname: base.hostname,
port,
path: immichPath,
method: bodyStr ? 'POST' : 'GET',
headers: {
'x-api-key': apiKey,
'Accept': asBuffer ? 'image/*' : 'application/json',
...(bodyStr ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(bodyStr) } : {}),
},
};
const req = lib.request(options, res => {
const chunks = [];
res.on('data', c => chunks.push(c));
res.on('end', () => {
const buf = Buffer.concat(chunks);
if (asBuffer) { resolve({ status: res.statusCode, buf, contentType: res.headers['content-type'] || 'image/jpeg' }); return; }
let parsed;
try { parsed = JSON.parse(buf.toString('utf8')); }
catch { parsed = buf.toString('utf8'); }
resolve({ status: res.statusCode, body: parsed });
});
});
req.setTimeout(15000, () => { req.destroy(); reject(new Error('Immich request timed out')); });
req.on('error', err => reject(new Error(`Immich connection error: ${err.message}`)));
if (bodyStr) req.write(bodyStr);
req.end();
});
}
// Immich v3 removed assets from GET /api/albums/{id}. Fetch via POST /api/search/metadata with pagination.
async function immichGetAlbumAssets(url, apiKey, albumId) {
const assets = [];
let page = 1;
while (true) {
const r = await immichRequest(url, apiKey, '/api/search/metadata', false, {
albumIds: [albumId],
type: 'IMAGE',
withExif: true,
page,
size: 1000,
});
if (r.status !== 200) throw new Error(`Immich search returned ${r.status}: ${JSON.stringify(r.body)}`);
const items = r.body?.assets?.items || [];
assets.push(...items);
if (!r.body?.assets?.nextPage || items.length === 0) break;
page++;
}
return assets;
}
// Fetches assets across multiple albums, deduping photos that belong to more than one.
async function immichGetAlbumsAssets(url, apiKey, albumIds) {
const assets = [];
const seen = new Set();
for (const albumId of albumIds) {
const items = await immichGetAlbumAssets(url, apiKey, albumId);
for (const item of items) {
if (!seen.has(item.id)) { seen.add(item.id); assets.push(item); }
}
}
return assets;
}
function getImmichCfg() {
const d = getLiveData();
const s = d.settings || {};
let albums = Array.isArray(s.immichAlbumIds) ? s.immichAlbumIds.filter(Boolean) : [];
if (!albums.length && s.immichAlbumId) albums = [s.immichAlbumId]; // legacy single-album setting
return {
url: (s.immichUrl || '').replace(/\/$/, ''),
apiKey: s.immichApiKey || '',
albums,
};
}
const server = http.createServer(async (req, res) => {
const method = req.method.toUpperCase();
const pathname = getPathname(req.url);
// ── CORS preflight ──────────────────────────────────────
if (method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
});
res.end();
return;
}
// ── IP ALLOWLIST ─────────────────────────────────────────
// Only enforced when settings.allowedIPs is a non-empty array.
// Localhost is always allowed so the host machine can reach admin.
// /admin/login POST is always allowed so you can log in to manage the list.
const isAdminLogin = pathname === '/admin/login' && method === 'POST';
if (!isAdminLogin) {
let allowedIPs = [];
try { allowedIPs = getLiveData()?.settings?.allowedIPs || []; } catch {}
if (Array.isArray(allowedIPs) && allowedIPs.length > 0) {
// Normalise IPv6-mapped IPv4 (::ffff:192.168.1.5 → 192.168.1.5)
const clientIP = getClientIP(req);
const isLocal = clientIP === '127.0.0.1' || clientIP === '::1' || clientIP === 'localhost';
const allowedIPStrings = allowedIPs.map(e => (typeof e === 'string' ? e : e.ip));
if (!isLocal && !allowedIPStrings.includes(clientIP)) {
console.warn(` ✗ IP blocked: ${clientIP} — not in allowlist`);
recordBlockedIP(clientIP);
const isPage = !pathname.startsWith('/api/');
if (isPage) {
res.writeHead(403, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Access Restricted</title>
<style>*{box-sizing:border-box;margin:0;padding:0}body{min-height:100vh;display:flex;align-items:center;justify-content:center;background:#f4f1eb;font-family:system-ui,sans-serif}
.card{background:#fff;border:1px solid #e5e0d5;border-radius:16px;padding:40px;width:360px;text-align:center;box-shadow:0 4px 24px rgba(0,0,0,.07)}
h1{font-size:20px;font-weight:600;margin-bottom:8px;color:#1a1815}p{font-size:13px;color:#7a746a;line-height:1.6}
code{background:#f4f1eb;padding:2px 7px;border-radius:4px;font-size:12px;}</style></head>
<body><div class="card"><div style="font-size:40px;margin-bottom:16px">🔒</div>
<h1>Access Restricted</h1>
<p>You do not have permission to access this page.<br><br>Please check with your Administrator.</p></div></body></html>`);
} else {
sendJSON(res, 403, { error: 'IP not in allowlist', ip: clientIP });
}
return;
}
}
}
// ── /api/version ────────────────────────────────────────
if (pathname === '/api/version' && method === 'GET') {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
sendJSON(res, 200, { version: pkg.version || 'unknown' });
} catch { sendJSON(res, 200, { version: 'unknown' }); }
return;
}
// ── /api/data GET ──────────────────────────────────────
if (pathname === '/api/data' && method === 'GET') {
fs.readFile(DATA_FILE, 'utf8', (err, raw) => {
if (err) { sendJSON(res, 500, { error: 'Cannot read data.json', detail: err.message }); return; }
try { sendJSON(res, 200, JSON.parse(raw)); }
catch { sendJSON(res, 500, { error: 'data.json contains invalid JSON' }); }
});
return;
}
// ── /api/data POST ─────────────────────────────────────
if (pathname === '/api/data' && method === 'POST') {
try {
const raw = await readBody(req);
const obj = JSON.parse(raw); // validate
const out = JSON.stringify(obj, null, 2);
fs.writeFile(DATA_FILE, out, 'utf8', err => {
if (err) { sendJSON(res, 500, { error: 'Cannot write data.json', detail: err.message }); return; }
sendJSON(res, 200, { ok: true });
});
} catch (e) {
sendJSON(res, 400, { error: 'Invalid JSON body', detail: e.message });
}
return;
}
// ── /api/myip GET ───────────────────────────────────────
// Returns the caller's IP as seen by the server — used by admin to detect
// the current device's IP for easy allowlist entry
if (pathname === '/api/myip' && method === 'GET') {
const ip = getClientIP(req);
sendJSON(res, 200, { ip });
return;
}
// Returns the parts of config.json that are safe to expose to the admin UI
// (never exposes ha_token)
if (pathname === '/api/config' && method === 'GET') {
sendJSON(res, 200, {
ha_url: HA_URL,
port: PORT,
token_set: HA_TOKEN_SET,
url_from_env: !!process.env.FP_HA_URL,
token_from_env: !!process.env.FP_HA_TOKEN,
});
return;
}
// ── /api/config POST ───────────────────────────────────
// Saves ha_url and optionally ha_token back to config.json
// Body: { ha_url?, ha_token? }
if (pathname === '/api/config' && method === 'POST') {
try {
const raw = await readBody(req);
const body = JSON.parse(raw);
// Re-read current config so we don't clobber other fields
let current = {};
try { current = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); } catch {}
if (body.ha_url) current.ha_url = body.ha_url.replace(/\/$/, '');
if (body.ha_token) current.ha_token = body.ha_token.trim();
fs.writeFileSync(CONFIG_FILE, JSON.stringify(current, null, 2), 'utf8');
sendJSON(res, 200, { ok: true, note: 'Restart server for ha_url / ha_token changes to take effect.' });
} catch (e) {
sendJSON(res, 500, { error: e.message });
}
return;
}
// ── /api/ha/ping GET ────────────────────────────────────
// Quick HA connectivity check surfaced in admin UI
if (pathname === '/api/ha/ping' && method === 'GET') {
try {
const r = await haRequest('GET', '/api/');
sendJSON(res, 200, {
ok: r.status === 200,
status: r.status,
message: r.body?.message ?? String(r.body).slice(0, 80),
ha_url: HA_URL,
token_set: HA_TOKEN_SET,
});
} catch (e) {
sendJSON(res, 200, { ok: false, error: e.message, ha_url: HA_URL });
}
return;
}
if (pathname === '/api/ha/test' && method === 'GET') {
const result = {
config: { ha_url: HA_URL, token_set: HA_TOKEN_SET, token_length: HA_TOKEN.length },
api_ping: null,
sample_entity: null,
errors: [],
};
try {
const ping = await haRequest('GET', '/api/');
result.api_ping = { status: ping.status, message: ping.body?.message ?? ping.body };
} catch (e) {
result.errors.push({ step: 'api_ping', error: e.message });
}
try {
const sample = await haGetState('alarm_control_panel.master');
result.sample_entity = sample;
} catch (e) {
result.errors.push({ step: 'sample_entity', error: e.message });
}
const ok = result.errors.length === 0 && result.api_ping?.status === 200;
sendJSON(res, ok ? 200 : 502, result);
return;
}
// ── /api/ha/services GET ─── SERVICE SCHEMA DIAGNOSTIC ─
// Visit http://localhost:8080/api/ha/services?domain=ms365_calendar
// Returns the full schema for every service in that domain — shows exact field names HA expects.
if (pathname === '/api/ha/services' && method === 'GET') {
try {
const qIdx = req.url.indexOf('?');
const qs = qIdx !== -1 ? req.url.slice(qIdx + 1) : '';
const domain = qs.split('&').find(p => p.startsWith('domain='))?.split('=')[1] || '';
const r = await haRequest('GET', '/api/services');
if (r.status !== 200) { sendJSON(res, r.status, { error: 'HA returned ' + r.status }); return; }
const all = Array.isArray(r.body) ? r.body : [];
const filtered = domain
? all.filter(s => s.domain === domain)
: all.filter(s => s.domain.includes('calendar'));
sendJSON(res, 200, filtered);
} catch (e) {
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/ha/states GET ─────────────────────────────────
if (pathname === '/api/ha/states' && method === 'GET') {
try {
// Poll both configured state_entities AND any user haEntity fields
const data = getLiveData();
const entityIds = new Set([
...getStateEntities(),
...(data.users || []).filter(u => u.haEntity).map(u => u.haEntity),
]);
const pairs = await Promise.all(
[...entityIds].map(id =>
haGetState(id)
.then(s => [id, s])
.catch(e => { console.error(` ✗ State ${id}: ${e.message}`); return [id, { state: 'unavailable', attributes: {} }]; })
)
);
sendJSON(res, 200, Object.fromEntries(pairs));
} catch (e) {
console.error(' ✗ /api/ha/states error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/weather GET ───────────────────────────────────
// Returns current weather. Uses HA weather entity if configured,
// otherwise geocodes weatherLocation and hits Open-Meteo.
if (pathname === '/api/weather' && method === 'GET') {
try {
const liveData = getLiveData();
const haEntity = liveData?.settings?.weatherEntity?.trim() || '';
const locationStr = liveData?.settings?.weatherLocation?.trim() || 'Hamilton, NZ';
// ── Source 1: HA weather entity ──────────────────────
if (haEntity) {
const s = await haGetState(haEntity);
if (s.state && s.state !== 'unavailable' && s.state !== 'unknown') {
const attr = s.attributes || {};
// HA condition → WMO-style emoji mapping
const HA_ICONS = {
'sunny': '☀️', 'clear-night': '🌙', 'partlycloudy': '⛅',
'cloudy': '☁️', 'fog': '🌫️', 'rainy': '🌧️', 'pouring': '🌧️',
'snowy': '❄️', 'snowy-rainy': '🌨️', 'windy': '🌬️',
'windy-variant': '🌬️', 'hail': '🌨️', 'lightning': '⛈️',
'lightning-rainy': '⛈️', 'exceptional': '🌡️',
};
const icon = HA_ICONS[s.state] || '🌡️';
const desc = s.state.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
const temp = attr.temperature != null ? Math.round(attr.temperature) : null;
const feels = attr.apparent_temperature != null ? Math.round(attr.apparent_temperature) : null;
console.log(` ✓ Weather (HA ${haEntity}): ${desc}, ${temp}°`);
sendJSON(res, 200, { source: 'ha', icon, desc, temp, feels, entity: haEntity });
return;
}
console.warn(` ⚠ Weather: HA entity "${haEntity}" returned state "${s.state}", falling back to Open-Meteo`);
}
// ── Source 2: Open-Meteo (proxied through server) ────
const WMO_ICONS = {
0:'☀️', 1:'🌤️', 2:'⛅', 3:'☁️', 45:'🌫️', 48:'🌫️',
51:'🌦️', 53:'🌦️', 55:'🌧️', 61:'🌦️', 63:'🌧️', 65:'🌧️',
71:'🌨️', 73:'❄️', 75:'❄️', 80:'🌦️', 81:'🌧️', 82:'⛈️', 95:'⛈️', 99:'⛈️',
};
const WMO_CODES = {
0:'Clear sky', 1:'Mainly clear', 2:'Partly cloudy', 3:'Overcast',
45:'Fog', 48:'Icy fog', 51:'Light drizzle', 53:'Drizzle', 55:'Heavy drizzle',
61:'Light rain', 63:'Rain', 65:'Heavy rain', 71:'Light snow', 73:'Snow', 75:'Heavy snow',
80:'Light showers', 81:'Showers', 82:'Heavy showers', 95:'Thunderstorm', 99:'Thunderstorm + hail',
};
// Geocode — split "Hamilton, NZ" → name=Hamilton&countryCode=NZ
const [geoCity, geoCountry] = locationStr.split(',').map(s => s.trim());
const geoCCParam = geoCountry ? `&countryCode=${encodeURIComponent(geoCountry)}` : '';
const geoUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(geoCity)}&count=1&language=en&format=json${geoCCParam}`;
const geoData = await httpsGetJSON(geoUrl);
const loc = geoData?.results?.[0];
if (!loc) {
sendJSON(res, 404, { error: `No geocoding result for "${locationStr}"` });
return;
}
const tz = (loc.timezone && loc.timezone !== 'null') ? encodeURIComponent(loc.timezone) : 'auto';
const wxUrl = `https://api.open-meteo.com/v1/forecast?latitude=${loc.latitude}&longitude=${loc.longitude}¤t=temperature_2m,apparent_temperature,weather_code,relative_humidity_2m&wind_speed_unit=kmh&timezone=${tz}`;
const wxData = await httpsGetJSON(wxUrl);
const c = wxData?.current;
if (!c) { sendJSON(res, 502, { error: 'No current weather data from Open-Meteo' }); return; }
const code = c.weather_code;
const temp = Math.round(c.temperature_2m);
const feels = Math.round(c.apparent_temperature);
console.log(` ✓ Weather (Open-Meteo, ${locationStr}): ${WMO_CODES[code] || code}, ${temp}°`);
sendJSON(res, 200, {
source: 'open-meteo',
icon: WMO_ICONS[code] || '🌡️',
desc: WMO_CODES[code] || '',
temp, feels,
location: locationStr,
});
} catch (e) {
console.error(' ✗ /api/weather error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/ha/calendar GET ───────────────────────────────
if (pathname === '/api/ha/calendar' && method === 'GET') {
try {
// Read dedup setting live from data.json so admin changes take effect immediately
let dedupEnabled = true;
try {
const raw = fs.readFileSync(DATA_FILE, 'utf8');
dedupEnabled = JSON.parse(raw)?.settings?.calendarDedup !== false;
} catch { /* use default true if file unreadable */ }
const now = new Date();
// Use client-supplied range if provided (allows fetching future months on demand)
// Otherwise fall back to default: 7 days back, 90 days forward
const calQS = new URLSearchParams(req.url.includes('?') ? req.url.slice(req.url.indexOf('?') + 1) : '');
const qStart = calQS.get('start');
const qEnd = calQS.get('end');
const start = qStart ? new Date(qStart) : new Date(now.getTime() - 7 * 86400000);
const end = qEnd ? new Date(qEnd) : new Date(now.getTime() + 90 * 86400000);
const sISO = start.toISOString().replace(/\.\d{3}Z$/, 'Z');
const eISO = end.toISOString().replace(/\.\d{3}Z$/, 'Z');
console.log(` → Calendar range: ${sISO.slice(0,10)} → ${eISO.slice(0,10)}${qStart ? ' (client-requested)' : ' (default)'}`);
// Calendar priority order — first calendar to claim a UID wins display
// This deduplicates events that appear in multiple calendars (e.g. shared
// events accepted by both Bob and Laura).
const seenUids = new Set();
const allEvents = [];
for (const cal of getCalendars()) {
let raw = [];
try { raw = await haGetCalendar(cal.entity, sISO, eISO); }
catch (e) { console.warn(` ⚠ Calendar ${cal.entity}: ${e.message}`); }
for (const ev of raw) {
const uid = ev.uid || ev.iCalUID || null;
const allDay = !ev.start?.dateTime;
const rawStart = ev.start?.dateTime || ev.start?.date || '';
const rawEnd = ev.end?.dateTime || ev.end?.date || '';
// Normalise datetime for dedup: strip timezone offset (+12:00, Z, etc.)
// so the same event from two calendars (in different tz representations) still matches.
// Format: "YYYY-MM-DD" for all-day, "YYYY-MM-DDTHH:MM" for timed.
const normStart = allDay
? rawStart.slice(0, 10)
: rawStart.slice(0, 16).replace('T', ' ');
// Deduplicate strategy:
// 1. Same UID → definitive match (same Outlook object)
// 2. Same title (case-insensitive) + same normalised start → invited event duplicate
const titleKey = (ev.summary || '').toLowerCase().trim();
const uidKey = uid || null;
const titleDateKey = `${titleKey}|${normStart}`;
if (dedupEnabled) {
if (uidKey && seenUids.has(uidKey)) {
console.log(` ↩ Dedup[uid]: "${ev.summary}"`);
continue;
}
if (seenUids.has(titleDateKey)) {
console.log(` ↩ Dedup[title]: "${ev.summary}" at ${normStart}`);
continue;
}
}
if (uidKey) seenUids.add(uidKey);
seenUids.add(titleDateKey);
allEvents.push({
id: `ha_${cal.entity}_${rawStart}_${titleKey.slice(0, 16)}`.replace(/[^\w-]/g, '_'),
uid, // Outlook event_id — used for ms365_calendar modify/remove services
title: ev.summary || '(no title)',
loc: ev.location || '',
desc: ev.description || '',
cal: cal.entity,
calName: cal.name,
color: cal.color,
date: rawStart.slice(0, 10),
time: allDay ? '' : rawStart.slice(11, 16),
endDate: rawEnd.slice(0, 10),
endTime: allDay ? '' : rawEnd.slice(11, 16),
allDay,
editable: !!uid, // only editable if we have an event_id
});
}
}
allEvents.sort((a, b) =>
(a.date + (a.time || '00:00')).localeCompare(b.date + (b.time || '00:00'))
);
console.log(` ✓ Calendar: ${allEvents.length} events (dedup: ${dedupEnabled ? 'on' : 'OFF'}, seenUids: ${seenUids.size})`);
sendJSON(res, 200, { calendars: getCalendars(), events: allEvents });
} catch (e) {
console.error(' ✗ /api/ha/calendar error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/ha/service POST ───────────────────────────────
// General-purpose HA service proxy (used by controls/lights/lock/gate etc.)
// Body: { domain, service, data }
if (pathname === '/api/ha/service' && method === 'POST') {
try {
const raw = await readBody(req);
const { domain, service, data: svcData } = JSON.parse(raw);
if (!domain || !service) {
sendJSON(res, 400, { error: 'Request body must include "domain" and "service"' });
return;
}
console.log(` → HA service: ${domain}.${service}`, JSON.stringify(svcData || {}));
const r = await haRequest('POST', `/api/services/${domain}/${service}`, svcData ?? {});
if (r.status >= 400) {
sendJSON(res, r.status, { error: `HA returned ${r.status}`, detail: r.body });
return;
}
sendJSON(res, 200, { ok: true });
} catch (e) {
console.error(' ✗ /api/ha/service error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/ha/todo GET ───────────────────────────────────
if (pathname === '/api/ha/todo' && method === 'GET') {
try {
const qs = req.url.includes('?') ? req.url.slice(req.url.indexOf('?') + 1) : '';
const params = new URLSearchParams(qs);
const entity = params.get('entity');
if (!entity) { sendJSON(res, 400, { error: 'entity param required' }); return; }
const r = await haRequest('POST', '/api/services/todo/get_items?return_response=true', { entity_id: entity });
if (r.status >= 400) {
console.error(` ✗ todo/get_items failed: ${r.status}`);
sendJSON(res, r.status, { error: `HA returned ${r.status}` }); return;
}
const items = r.body?.service_response?.[entity]?.items || r.body?.[entity]?.items || [];
sendJSON(res, 200, { items });
} catch (e) {
console.error(' ✗ /api/ha/todo error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/ha/todo POST ──────────────────────────────────
// Update a todo item status. Body: { entity, uid, status }
// status: "needs_action" | "completed"
if (pathname === '/api/ha/todo' && method === 'POST') {
try {
const raw = await readBody(req);
const { entity, uid, status } = JSON.parse(raw);
if (!entity || !uid || !status) { sendJSON(res, 400, { error: 'entity, uid, status required' }); return; }
const svcData = { entity_id: entity, item: uid, status };
const r = await haRequest('POST', '/api/services/todo/update_item', svcData);
if (r.status >= 400) { sendJSON(res, r.status, { error: `HA returned ${r.status}`, detail: r.body }); return; }
sendJSON(res, 200, { ok: true });
} catch (e) {
console.error(' ✗ /api/ha/todo POST error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/ha/calendar/create POST ───────────────────────
// Body: { entity_id, summary, start, end, location?, description?, all_day? }
// start/end: "YYYY-MM-DDTHH:MM:SS" for timed, "YYYY-MM-DD" for all-day
if (pathname === '/api/ha/calendar/create' && method === 'POST') {
try {
const raw = await readBody(req);
const body = JSON.parse(raw);
const { entity_id, summary, start, end, location, description, all_day } = body;
if (!entity_id || !summary || !start || !end) {
sendJSON(res, 400, { error: 'entity_id, summary, start, and end are required' });
return;
}
const svcData = all_day
? { entity_id, summary, start_date: start, end_date: end }
: { entity_id, summary, start_date_time: start, end_date_time: end };
if (location) svcData.location = location;
if (description) svcData.description = description;
console.log(` → calendar.create_event on ${entity_id}: "${summary}" ${start} → ${end}`);
console.log(` payload: ${JSON.stringify(svcData)}`);
const r = await haRequest('POST', '/api/services/calendar/create_event', svcData);
if (r.status >= 400) {
console.error(` ✗ HA rejected create: ${r.raw || JSON.stringify(r.body)}`);
sendJSON(res, r.status, { error: `HA returned ${r.status}`, detail: r.body });
return;
}
sendJSON(res, 200, { ok: true });
} catch (e) {
console.error(' ✗ /api/ha/calendar/create error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/ha/calendar/update POST ───────────────────────
// Body: { entity_id, uid, summary, start, end, location?, description?, all_day? }
if (pathname === '/api/ha/calendar/update' && method === 'POST') {
try {
const raw = await readBody(req);
const body = JSON.parse(raw);
const { entity_id, uid, summary, start, end, location, description, all_day } = body;
if (!entity_id || !uid || !summary || !start || !end) {
sendJSON(res, 400, { error: 'entity_id, uid, summary, start, and end are required' });
return;
}
// ms365_calendar.modify_calendar_event: entity_id flat alongside service fields
const svcData = {
entity_id,
event_id: uid,
subject: summary,
start: start,
end: end,
is_all_day: !!all_day,
};
if (location) svcData.location = location;
if (description) svcData.body = description;
console.log(` → ms365_calendar.modify_calendar_event: event_id=${uid.slice(0,30)}… "${summary}"`);
console.log(` payload: ${JSON.stringify(svcData)}`);
const r = await haRequest('POST', '/api/services/ms365_calendar/modify_calendar_event', svcData);
if (r.status >= 400) {
console.error(` ✗ HA rejected modify: ${r.raw || JSON.stringify(r.body)}`);
sendJSON(res, r.status, { error: `HA returned ${r.status}`, detail: r.body });
return;
}
sendJSON(res, 200, { ok: true });
} catch (e) {
console.error(' ✗ /api/ha/calendar/update error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// ── /api/ha/calendar/delete POST ───────────────────────
// Body: { entity_id, uid }
// Entity services need entity_id flat in the body alongside the service fields
if (pathname === '/api/ha/calendar/delete' && method === 'POST') {
try {
const raw = await readBody(req);
const body = JSON.parse(raw);
const { entity_id, uid } = body;
if (!entity_id || !uid) {
sendJSON(res, 400, { error: 'entity_id and uid are required' });
return;
}
const payload = { entity_id, event_id: uid };
console.log(` → ms365_calendar.remove_calendar_event: event_id=${uid.slice(0,30)}…`);
console.log(` payload: ${JSON.stringify(payload)}`);
const r = await haRequest('POST', '/api/services/ms365_calendar/remove_calendar_event', payload);
if (r.status >= 400) {
console.error(` ✗ HA rejected remove: ${r.raw || JSON.stringify(r.body)}`);
sendJSON(res, r.status, { error: `HA returned ${r.status}`, detail: r.body });
return;
}
sendJSON(res, 200, { ok: true });
} catch (e) {
console.error(' ✗ /api/ha/calendar/delete error:', e.message);
sendJSON(res, 502, { error: e.message });
}
return;
}
// Diagnostic: tests connection → auth → album → photo proxy in sequence
if (pathname === '/api/immich/test' && method === 'GET') {
const { url, apiKey, albums } = getImmichCfg();
const result = { url, album_ids: albums, steps: [] };
const step = (name, ok, detail) => result.steps.push({ name, ok, detail });
if (!url) { step('config', false, 'immichUrl not set'); sendJSON(res, 200, result); return; }
if (!apiKey) { step('config', false, 'immichApiKey not set'); sendJSON(res, 200, result); return; }
step('config', true, 'URL and API key are set');
// Step 1: ping server
try {
const r = await immichRequest(url, apiKey, '/api/server/ping', false);
step('ping', r.status === 200, `HTTP ${r.status}`);
if (r.status !== 200) { sendJSON(res, 200, result); return; }
} catch(e) { step('ping', false, e.message); sendJSON(res, 200, result); return; }
// Step 2: validate API key (use /api/users/me — works across all Immich versions)
try {
const r = await immichRequest(url, apiKey, '/api/users/me', false);
step('auth', r.status === 200, `HTTP ${r.status}${r.body?.email ? ' — ' + r.body.email : r.body?.message ? ' — ' + r.body.message : ''}`);
if (r.status !== 200) { sendJSON(res, 200, result); return; }
} catch(e) { step('auth', false, e.message); sendJSON(res, 200, result); return; }
// Step 3: fetch album assets via search/metadata (Immich v3 removed assets from GET /albums/{id})
if (!albums.length) { step('album', false, 'No album selected — pick one in Admin → Photo Frame'); sendJSON(res, 200, result); return; }
let assetId;
try {
const images = await immichGetAlbumsAssets(url, apiKey, albums);
const livePhotos = images.filter(a => a.livePhotoVideoId);
step('album', true, `${images.length} images across ${albums.length} album${albums.length !== 1 ? 's' : ''} (${livePhotos.length} Live Photos)`);
if (!images.length) { sendJSON(res, 200, result); return; }
assetId = images[0].id;
} catch(e) { step('album', false, e.message); sendJSON(res, 200, result); return; }
// Step 4: fetch one thumbnail
try {
const r = await immichRequest(url, apiKey, `/api/assets/${encodeURIComponent(assetId)}/thumbnail?size=preview`, true);
step('photo', r.status === 200, `HTTP ${r.status} — ${r.status === 200 ? r.buf.length + ' bytes, ' + r.contentType : 'failed'}`);
} catch(e) { step('photo', false, e.message); }
sendJSON(res, 200, result);
return;
}
// Returns list of all Immich albums — used by admin to pick one
if (pathname === '/api/immich/albums' && method === 'GET') {
try {
const { url, apiKey } = getImmichCfg();
if (!url || !apiKey) { sendJSON(res, 400, { error: 'Immich URL and API key are not configured' }); return; }
const r = await immichRequest(url, apiKey, '/api/albums', false);
if (r.status !== 200) { sendJSON(res, r.status, { error: `Immich returned ${r.status}`, detail: r.body }); return; }
const albums = (Array.isArray(r.body) ? r.body : []).map(a => ({
id: a.id,