-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathindex.js
More file actions
6346 lines (5654 loc) · 247 KB
/
Copy pathindex.js
File metadata and controls
6346 lines (5654 loc) · 247 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
// File: server/index.js
require('dotenv').config();
const APP_TIMEZONE = process.env.TZ || 'America/New_York';
// Demo mode: a single opt-in flag for running a public, throwaway demo
// instance. It uses an in-memory database (wiped on container stop), disables
// the admin PIN, seeds sample data (re-seeded every DEMO_RESET_HOURS), and
// blocks routes that a public visitor could abuse (uploads, outbound fetch
// proxies, OAuth credential storage). Never enabled unless DEMO_MODE=true.
const DEMO_MODE = process.env.DEMO_MODE === 'true';
const DEMO_RESET_HOURS = 6;
// Guard for routes disabled in demo mode. Sends a 403 and returns true when
// the request should stop (send-reply-then-return convention).
const demoBlocked = (reply) => {
if (!DEMO_MODE) return false;
reply.status(403).send({ error: 'This feature is disabled in demo mode.' });
return true;
};
process.env.TZ = APP_TIMEZONE;
const fastify = require('fastify')({ logger: true });
const Database = require('better-sqlite3');
const ical = require('ical-generator');
const node_ical = require('node-ical');
const path = require('path');
const fs = require('fs').promises;
const fsSync = require('fs');
const serverPackageJson = require('./package.json');
const multipart = require('@fastify/multipart');
const crypto = require('crypto');
// NEW: Import axios for HTTP requests and ical.js for parsing
const axios = require('axios');
const ICAL = require('ical.js');
const { CronExpressionParser } = require('cron-parser');
const cron = require('node-cron');
// For widget upload and registry
const widgetRegistryPath = path.join(__dirname, 'widgets_registry.json');
// Chore notification sounds: bundled defaults (in the image) seeded into the
// persisted uploads volume, plus user uploads. Served via the /Uploads/ static root.
const DEFAULT_SOUNDS_DIR = path.join(__dirname, 'assets', 'sounds');
const SOUNDS_UPLOAD_DIR = path.join(__dirname, 'uploads', 'sounds');
const ALLOWED_SOUND_EXTENSIONS = new Set(['.mp3', '.wav', '.ogg', '.m4a', '.aac']);
function getDefaultSoundFilenames() {
try {
return new Set(fsSync.readdirSync(DEFAULT_SOUNDS_DIR));
} catch {
return new Set();
}
}
async function seedDefaultSounds() {
await fs.mkdir(SOUNDS_UPLOAD_DIR, { recursive: true });
let defaults = [];
try {
defaults = await fs.readdir(DEFAULT_SOUNDS_DIR);
} catch {
return; // No bundled defaults present; nothing to seed.
}
for (const filename of defaults) {
const target = path.join(SOUNDS_UPLOAD_DIR, filename);
try {
await fs.access(target);
} catch {
await fs.copyFile(path.join(DEFAULT_SOUNDS_DIR, filename), target);
console.log(`Seeded default sound: ${filename}`);
}
}
}
// Default profile avatars (issue #132): bundled flat SVG art seeded into the
// persisted uploads volume under users/defaults/, so a selected default is
// served by the exact same /Uploads/users/<profile_picture> path the client
// already uses for uploaded pictures.
const DEFAULT_AVATARS_DIR = path.join(__dirname, 'assets', 'avatars');
const AVATARS_UPLOAD_DIR = path.join(__dirname, 'uploads', 'users', 'defaults');
async function seedDefaultAvatars() {
await fs.mkdir(AVATARS_UPLOAD_DIR, { recursive: true });
let defaults = [];
try {
defaults = await fs.readdir(DEFAULT_AVATARS_DIR);
} catch {
return; // No bundled defaults present; nothing to seed.
}
for (const filename of defaults) {
const target = path.join(AVATARS_UPLOAD_DIR, filename);
try {
await fs.access(target);
} catch {
await fs.copyFile(path.join(DEFAULT_AVATARS_DIR, filename), target);
}
}
}
// Calendar sync service
const CalendarSyncService = require('./services/calendarSync');
const googleConnection = require('./services/googleConnection');
const googleCalendar = require('./services/googleCalendar');
const appleCalDAV = require('./services/appleCalDAV');
const googlePhotos = require('./services/googlePhotos');
const googlePhotosPicker = require('./services/googlePhotosPicker');
const homeAssistant = require('./services/homeAssistant');
const weatherService = require('./services/weather');
const { computeSunTimes } = require('./services/weather/sun');
const {
isEncryptionConfigured,
getEncryptionStatus,
encrypt,
decrypt,
isLegacyCiphertext,
decryptLegacy,
} = require('./utils/encryption');
const { httpsAgentFor, isCertificateVerificationSkipped } = require('./utils/outboundTls');
const {
DEVICE_NAME_RULE_MESSAGE,
isValidDeviceName,
normalizeDeviceName,
} = require('./utils/deviceName');
// Certificate policy for every outbound axios request, decided per URL from the
// target's address class (issue #139). Registered on the default axios instance,
// which is shared by every module that requires axios — the calendar sync
// service and the Apple CalDAV client included — so no call site has to remember
// this, and a new one cannot forget it.
//
// Public hosts are always verified. Private ones (RFC1918, loopback, .local and
// friends) accept a self-signed certificate, because that is the normal case for
// a NAS or a photo server on the household's own network and there is no public
// CA that would ever issue for 192.168.1.50.
axios.interceptors.request.use((config) => {
try {
const resolved = config.baseURL && !/^https?:\/\//i.test(config.url || '')
? new URL(config.url || '', config.baseURL)
: new URL(config.url);
const agent = httpsAgentFor(resolved);
if (agent) config.httpsAgent = agent;
} catch (_) {
// Not a URL we can classify; axios will fail on it anyway, and leaving the
// config untouched means Node's default (verify) applies.
}
return config;
});
let calendarSyncService = null;
const pluginEvents = require('./services/pluginEvents');
const initializeDatabase = require('./migrations/initializeDatabase');
const migrateChoresDatabase = require('./migrations/migrateChoresDatabase');
const migrateClamsToHistory = require('./migrations/migrateClamsToHistory');
const migrateChoreHistoryTitle = require('./migrations/migrateChoreHistoryTitle');
const migrateToDurationField = require('./migrations/migrateToDurationField');
const SYSTEM_SCHEMA_ID_KEY = 'SYSTEM_SCHEMA_ID';
const schemaMigrations = [
{ schemaId: 6, migrationPath: './migrations/migrateDeviceSchemaV6', },
{ schemaId: 7, migrationPath: './migrations/schema7-proveMigrations', },
{ schemaId: 8, migrationPath: './migrations/schema8-calendarCacheTables', },
{ schemaId: 9, migrationPath: './migrations/schema9-googleConnection', },
{ schemaId: 10, migrationPath: './migrations/schema10-googlePhotosPicker', },
{ schemaId: 11, migrationPath: './migrations/schema11-homeglowPhotos', },
{ schemaId: 12, migrationPath: './migrations/schema12-onceCompletedScheduling', },
{ schemaId: 13, migrationPath: './migrations/schema13-tabsByDefaultBackfill', },
{ schemaId: 14, migrationPath: './migrations/schema14-deviceAndTabJsonStorage', },
{ schemaId: 15, migrationPath: './migrations/schema15-choreDueTimeSound', },
{ schemaId: 16, migrationPath: './migrations/schema16-choreDueDate', },
{ schemaId: 17, migrationPath: './migrations/schema17-choreTransferSnooze', },
{ schemaId: 18, migrationPath: './migrations/schema18-pluginsTable', },
{ schemaId: 19, migrationPath: './migrations/schema19-pluginStorage', },
{ schemaId: 20, migrationPath: './migrations/schema20-choreHistoryKind', },
{ schemaId: 21, migrationPath: './migrations/schema21-prizeOffers', },
{ schemaId: 22, migrationPath: './migrations/schema22-prizeRepeatSplit', },
{ schemaId: 23, migrationPath: './migrations/schema23-userSortOrder', },
{ schemaId: 24, migrationPath: './migrations/schema24-choreIcon', },
{ schemaId: 25, migrationPath: './migrations/schema25-unifyCredentialEncryption', },
];
const ALLOWED_SCHEDULE_DURATIONS = new Set(['day-of', 'until-completed', 'once-completed']);
const SCHEDULE_INTERVAL_REGEX = /^([1-9]\d*)([dwmy])$/;
// Fisher-Yates in-place shuffle. Mutates and returns the array.
const shuffleInPlace = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
};
// GitHub API configuration
const GITHUB_REPO_OWNER = 'jherforth';
const GITHUB_REPO_NAME = 'HomeGlowPlugins';
const GITHUB_API_BASE = 'https://api.github.com';
const DEFAULT_HOMEGLOW_REPOSITORY = 'jherforth/HomeGlow';
const BACKEND_VERSION = (process.env.BACKEND_VERSION || process.env.APP_VERSION || serverPackageJson.version || 'dev').trim();
const BACKEND_GIT_COMMIT = (process.env.BACKEND_GIT_COMMIT || process.env.GIT_COMMIT || process.env.GITHUB_SHA || '').trim() || null;
const BACKEND_GITHUB_REPOSITORY = (process.env.BACKEND_GITHUB_REPOSITORY || process.env.GITHUB_REPOSITORY || DEFAULT_HOMEGLOW_REPOSITORY).trim();
function isValidRepositorySlug(repository) {
return typeof repository === 'string' && /^[^/\s]+\/[^/\s]+$/.test(repository);
}
function buildGitHubCommitUrl(repository, commitSha) {
if (!commitSha || !isValidRepositorySlug(repository)) {
return null;
}
return `https://github.com/${repository}/commit/${commitSha}`;
}
function getTodayLocalDateString() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function normalizeScheduleDuration(duration) {
if (duration === undefined || duration === null || duration === '') {
return 'day-of';
}
return String(duration);
}
function normalizeScheduleInterval(intervalValue) {
if (intervalValue === undefined || intervalValue === null) {
return null;
}
const normalized = String(intervalValue).trim().toLowerCase();
return normalized || null;
}
function isValidScheduleInterval(intervalValue) {
return typeof intervalValue === 'string' && SCHEDULE_INTERVAL_REGEX.test(intervalValue);
}
const DUE_TIME_REGEX = /^([01]\d|2[0-3]):[0-5]\d$/;
// Returns { valid, value } where value is a normalized 'HH:MM' string or null.
function normalizeDueTime(dueTime) {
if (dueTime === undefined || dueTime === null || dueTime === '') {
return { valid: true, value: null };
}
const normalized = String(dueTime).trim();
if (!DUE_TIME_REGEX.test(normalized)) {
return { valid: false, value: null };
}
return { valid: true, value: normalized };
}
// Returns { valid, value } where value is a positive integer of minutes or null.
function normalizeReminderInterval(minutes) {
if (minutes === undefined || minutes === null || minutes === '' || Number(minutes) === 0) {
return { valid: true, value: null };
}
const parsed = Number.parseInt(minutes, 10);
if (!Number.isInteger(parsed) || parsed < 0) {
return { valid: false, value: null };
}
return { valid: true, value: parsed > 0 ? parsed : null };
}
function parseDateOnlyToLocalDate(dateString) {
if (typeof dateString !== 'string') {
return null;
}
const parts = dateString.split('-').map(Number);
if (parts.length !== 3 || parts.some(Number.isNaN)) {
return null;
}
const [year, month, day] = parts;
if (!year || !month || !day) {
return null;
}
return new Date(year, month - 1, day, 0, 0, 0, 0);
}
const DUE_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
function formatDateOnlyLocal(dateObj) {
return `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')}`;
}
function extractDateOnlyString(value) {
if (typeof value === 'string') {
const normalized = value.trim();
if (DUE_DATE_REGEX.test(normalized)) {
return normalized;
}
const match = normalized.match(/^(\d{4}-\d{2}-\d{2})/);
if (match) {
return match[1];
}
return null;
}
if (value instanceof Date && !Number.isNaN(value.getTime())) {
return formatDateOnlyLocal(value);
}
return null;
}
function calculateDateOffsetDays(startDateValue, endDateValue) {
const startDateOnly = extractDateOnlyString(startDateValue);
const endDateOnly = extractDateOnlyString(endDateValue);
if (!startDateOnly || !endDateOnly) {
return null;
}
const startDate = parseDateOnlyToLocalDate(startDateOnly);
const endDate = parseDateOnlyToLocalDate(endDateOnly);
if (!startDate || !endDate) {
return null;
}
return Math.round((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
}
function addDaysToDateOnly(baseDateValue, dayOffset) {
if (!Number.isInteger(dayOffset)) {
return null;
}
const baseDateOnly = extractDateOnlyString(baseDateValue);
if (!baseDateOnly) {
return null;
}
const baseDate = parseDateOnlyToLocalDate(baseDateOnly);
if (!baseDate) {
return null;
}
const resultDate = new Date(baseDate);
resultDate.setDate(resultDate.getDate() + dayOffset);
return formatDateOnlyLocal(resultDate);
}
// Returns { valid, value } where value is a normalized 'YYYY-MM-DD' string or null.
// Rejects malformed strings and impossible calendar dates (e.g. 2026-02-30).
function normalizeDueDate(dueDate) {
if (dueDate === undefined || dueDate === null || dueDate === '') {
return { valid: true, value: null };
}
const normalized = String(dueDate).trim();
if (!DUE_DATE_REGEX.test(normalized)) {
return { valid: false, value: null };
}
const parsed = parseDateOnlyToLocalDate(normalized);
if (!parsed || Number.isNaN(parsed.getTime())) {
return { valid: false, value: null };
}
// Guard against roll-over (e.g. '2026-02-30' -> Mar 2): re-serialize and compare.
const roundTrip = `${parsed.getFullYear()}-${String(parsed.getMonth() + 1).padStart(2, '0')}-${String(parsed.getDate()).padStart(2, '0')}`;
if (roundTrip !== normalized) {
return { valid: false, value: null };
}
return { valid: true, value: normalized };
}
// Snoozed-until is stored as an ISO UTC datetime so server and client compare
// it against "now" without timezone drift. Empty/null clears the snooze.
function normalizeSnoozedUntil(snoozedUntil) {
if (snoozedUntil === undefined || snoozedUntil === null || snoozedUntil === '') {
return { valid: true, value: null };
}
const parsed = new Date(snoozedUntil);
if (Number.isNaN(parsed.getTime())) {
return { valid: false, value: null };
}
return { valid: true, value: parsed.toISOString() };
}
// Validates the shared schedule due_time / due_date / reminder fields. On the
// first failure it sends a 400 and returns null; otherwise it returns the three
// normalized results. Used by the create + bulk-create schedule handlers. The
// PATCH handler keeps its own guards because it only validates provided fields.
const validateScheduleDateFields = ({ due_time, due_date, reminder_interval_minutes }, reply) => {
const dueTimeResult = normalizeDueTime(due_time);
if (!dueTimeResult.valid) {
reply.status(400).send({ error: 'due_time must be in HH:MM 24-hour format' });
return null;
}
const dueDateResult = normalizeDueDate(due_date);
if (!dueDateResult.valid) {
reply.status(400).send({ error: 'due_date must be a valid YYYY-MM-DD date' });
return null;
}
const reminderResult = normalizeReminderInterval(reminder_interval_minutes);
if (!reminderResult.valid) {
reply.status(400).send({ error: 'reminder_interval_minutes must be a non-negative integer' });
return null;
}
return { dueTimeResult, dueDateResult, reminderResult };
};
function addMonthsCalendarAware(baseDate, monthCount) {
const result = new Date(baseDate);
const originalDay = result.getDate();
result.setDate(1);
result.setMonth(result.getMonth() + monthCount);
const lastDayOfTargetMonth = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate();
result.setDate(Math.min(originalDay, lastDayOfTargetMonth));
return result;
}
function addYearsCalendarAware(baseDate, yearCount) {
return addMonthsCalendarAware(baseDate, yearCount * 12);
}
function addIntervalToDate(baseDate, intervalValue) {
const normalizedInterval = normalizeScheduleInterval(intervalValue);
if (!normalizedInterval || !isValidScheduleInterval(normalizedInterval)) {
return null;
}
const [, countRaw, unit] = normalizedInterval.match(SCHEDULE_INTERVAL_REGEX);
const count = parseInt(countRaw, 10);
if (count <= 0) {
return null;
}
switch (unit) {
case 'd': {
const result = new Date(baseDate);
result.setDate(result.getDate() + count);
return result;
}
case 'w': {
const result = new Date(baseDate);
result.setDate(result.getDate() + (count * 7));
return result;
}
case 'm':
return addMonthsCalendarAware(baseDate, count);
case 'y':
return addYearsCalendarAware(baseDate, count);
default:
return null;
}
}
function buildDateCrontab(dateObj) {
if (!(dateObj instanceof Date) || Number.isNaN(dateObj.getTime())) {
return null;
}
const dayOfMonth = dateObj.getDate();
const month = dateObj.getMonth() + 1;
return `0 0 ${dayOfMonth} ${month} *`;
}
// Credential encryption for calendar and photo sources.
//
// These used to have their own AES-256-CBC scheme keyed on
// `ENCRYPTION_KEY || <a string hardcoded in this repository>`, which meant that
// on any install that did not set the variable — including every install using
// the stock docker-compose, which never forwarded it — Apple app passwords,
// Immich API keys and photo refresh tokens were encrypted with a published key.
//
// They now use the same auto-keyed AES-256-GCM store as the Google and Home
// Assistant credentials (utils/encryption.js), which generates and persists its
// own key and needs no configuration. Values written before that change are
// still read through the legacy path; migration 25 re-encrypts them in place.
function encryptPassword(password) {
if (!password) return null;
return encrypt(password);
}
function decryptPassword(encryptedPassword) {
if (!encryptedPassword) return null;
try {
return isLegacyCiphertext(encryptedPassword)
? decryptLegacy(encryptedPassword)
: decrypt(encryptedPassword);
} catch (error) {
console.error('Error decrypting password:', error);
return null;
}
}
// Initialize Fastify with CORS
fastify.register(require('@fastify/cors'), {
origin: '*', // Allow all origins for development. Consider restricting in production.
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], // Explicitly allow PATCH
allowedHeaders: ['Content-Type', 'Authorization'], // Add any other headers your client might send
});
fastify.register(multipart, {
limits: {
fileSize: 25 * 1024 * 1024, // 25MB per file
files: 50,
},
});
// Add a preHandler hook to log all incoming requests
fastify.addHook('preHandler', (request, reply, done) => {
console.log(`Incoming request: ${request.method} ${request.url}`);
done();
});
// Serve static files for uploads.
//
// maxAge alone emits `Cache-Control: public, max-age=86400`, so there is no
// setHeaders callback here on purpose: the one that used to live here only
// re-set that identical header. Keeping it bought nothing and cost an outage
// in #136, where v10 changed the callback's first argument from the Node
// response to a Fastify Reply and `res.setHeader` became an uncaught
// TypeError that killed the process on the first file request. Headers are
// deliberately kept minimal to avoid "Request Header Fields Too Large".
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'uploads'),
prefix: '/Uploads/',
decorateReply: false,
maxAge: 86400000, // 1 day cache
});
// Additional static route specifically for user uploads
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'uploads', 'users'),
prefix: '/Uploads/users/',
decorateReply: false,
maxAge: 86400000, // 1 day cache
});
// Serve static files for widgets
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'widgets'),
prefix: '/widgets/',
decorateReply: false
});
// Widget filenames are restricted to this charset at upload/install time; the
// serve route enforces the same rule so encoded ../ segments can never reach
// the disk-fallback path.join below (path traversal guard).
const WIDGET_FILENAME_REGEX = /^[a-zA-Z0-9-._]+$/;
// Serve widget HTML from the DB-backed plugin store (issue #105 Phase 0), with
// a read-only disk fallback for files that predate the plugins table.
fastify.get('/widgets/:filename', async (request, reply) => {
const { filename } = request.params;
if (!WIDGET_FILENAME_REGEX.test(filename) || filename.includes('..')) {
return reply.status(404).send(`Widget file not found: ${filename}`);
}
try {
let content;
let pluginId = null;
const row = db.prepare('SELECT content, plugin_id FROM plugins WHERE filename = ?').get(filename);
if (row) {
content = row.content;
pluginId = row.plugin_id;
} else {
const filePath = path.join(__dirname, 'widgets', filename);
content = await fs.readFile(filePath, 'utf-8');
}
content = content.replace(/window\.location\.origin\.replace\(['"`]:\d+['"`],\s*['"`]:\d+['"`]\)/g, 'window.location.origin');
content = content.replace(/\$\{window\.location\.protocol\}\/\/\$\{window\.location\.hostname\}:\d+/g, '${window.location.origin}');
content = content.replace(/window\.location\.protocol\s*\+\s*'\/\/'\s*\+\s*window\.location\.hostname\s*\+\s*':\d+'/g, 'window.location.origin');
let injection = `<style>html,body{max-width:100%!important;overflow-x:hidden!important;box-sizing:border-box;}*{box-sizing:border-box;}</style>`;
// Manifest plugins get their identity injected so /plugin-sdk/v1.js knows
// which storage/settings namespace to talk to. plugin_id is validated to
// [a-z0-9-] at install time, so it is safe to embed verbatim.
if (pluginId) {
injection += `<script>window.__HOMEGLOW_PLUGIN__={id:"${pluginId}",apiVersion:"v1"};</script>`;
}
// Inject at the START of <head> so the identity script runs before any
// plugin script — including an SDK <script src> placed early in head.
const headOpen = content.match(/<head\b[^>]*>/i);
if (headOpen) {
content = content.replace(headOpen[0], `${headOpen[0]}${injection}`);
} else if (content.includes('<body')) {
content = content.replace('<body', `${injection}<body`);
} else {
content = injection + content;
}
reply.header('Content-Type', 'text/html; charset=utf-8');
return content;
} catch (error) {
console.error(`Error serving widget ${filename}:`, error);
reply.status(404).send(`Widget file not found: ${filename}`);
}
});
// Serve the plugin SDK (issue #105). Cached after first read; versioned by
// path so a future v2 can coexist with v1.
let pluginSdkV1Cache = null;
fastify.get('/plugin-sdk/v1.js', async (request, reply) => {
try {
if (!pluginSdkV1Cache) {
pluginSdkV1Cache = await fs.readFile(path.join(__dirname, 'plugin-sdk', 'v1.js'), 'utf-8');
}
reply.header('Content-Type', 'application/javascript');
reply.header('Cache-Control', 'public, max-age=3600');
return pluginSdkV1Cache;
} catch (error) {
console.error('Error serving plugin SDK:', error);
reply.status(500).send('// plugin SDK unavailable');
}
});
// Add a simple test endpoint
fastify.get('/api/test', async (request, reply) => {
return {
message: 'Server is working!',
timestamp: new Date().toISOString(),
widgetsDir: path.join(__dirname, 'widgets')
};
});
fastify.get('/api/stats', async (request, reply) => {
const repository = isValidRepositorySlug(BACKEND_GITHUB_REPOSITORY)
? BACKEND_GITHUB_REPOSITORY
: DEFAULT_HOMEGLOW_REPOSITORY;
return {
backend: {
version: BACKEND_VERSION,
commit: BACKEND_GIT_COMMIT,
repository,
commitUrl: buildGitHubCommitUrl(repository, BACKEND_GIT_COMMIT),
},
};
});
// Serve the main CSS file for widgets
fastify.get('/index.css', async (request, reply) => {
try {
// Try multiple possible paths
const possiblePaths = [
path.join(__dirname, '..', 'client', 'src', 'index.css'),
path.join(__dirname, 'client', 'src', 'index.css'),
'/app/client/src/index.css',
path.join(process.cwd(), 'client', 'src', 'index.css')
];
console.log('Looking for CSS file in paths:', possiblePaths);
console.log('Current working directory:', process.cwd());
console.log('__dirname:', __dirname);
let cssContent = null;
let successPath = null;
for (const cssPath of possiblePaths) {
try {
cssContent = await fs.readFile(cssPath, 'utf-8');
successPath = cssPath;
console.log('Successfully found CSS at:', cssPath);
break;
} catch (pathError) {
console.log('Failed to read CSS from:', cssPath, pathError.message);
}
}
if (cssContent) {
reply.header('Content-Type', 'text/css');
reply.header('Access-Control-Allow-Origin', '*');
return cssContent;
}
throw new Error('CSS file not found in any expected location');
} catch (error) {
console.error('Error serving index.css:', error);
// Fallback: serve minimal CSS for widgets
const fallbackCSS = `
:root {
--background: #f4f4f9;
--card-bg: rgba(255, 255, 255, 0.8);
--card-border: rgba(255, 255, 255, 0.2);
--text-color: #1a1a2e;
--text-color-rgb: 26, 26, 46;
--accent: #6e44ff;
--accent-rgb: 110, 68, 255;
--shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
--backdrop-blur: blur(10px);
--dynamic-text-size: 16px;
--dynamic-card-width: 300px;
--dynamic-card-padding: 20px;
--error-color: #ff4444;
--light-gradient-start: #00ddeb;
--light-gradient-end: #ff6b6b;
--dark-gradient-start: #2e2767;
--dark-gradient-end: #620808;
--light-button-gradient-start: #00ddeb;
--light-button-gradient-end: #ff6b6b;
--dark-button-gradient-start: #2e2767;
--dark-button-gradient-end: #620808;
--gradient: linear-gradient(45deg, var(--light-gradient-start), var(--light-gradient-end));
}
[data-theme="dark"] {
--background: #0a0a1a;
--card-bg: rgba(30, 30, 50, 0.7);
--card-border: rgba(100, 100, 150, 0.3);
--text-color: #a6a6d1;
--text-color-rgb: 166, 166, 209;
--accent: #00ddeb;
--accent-rgb: 0, 221, 235;
--shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
--gradient: linear-gradient(45deg, var(--dark-gradient-start), var(--dark-gradient-end));
}
html, body {
margin: 0;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--background);
color: var(--text-color);
transition: background 0.3s ease, color 0.3s ease;
touch-action: manipulation;
width: 100%;
height: 100%;
overflow-x: hidden;
overflow-y: auto;
font-size: var(--dynamic-text-size);
}
.card {
background: var(--card-bg);
border: 1px solid var(--card-border);
border-radius: 12px;
padding: var(--dynamic-card-padding);
backdrop-filter: var(--backdrop-blur);
box-shadow: var(--shadow);
transition: transform 0.2s ease, box-shadow 0.2s ease;
width: 100%;
max-width: var(--dynamic-card-width);
touch-action: manipulation;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
}
h1, h2, h3, h4, h5, h6 {
font-weight: 700;
letter-spacing: 0.5px;
color: var(--text-color);
}
button {
background: linear-gradient(45deg, var(--light-button-gradient-start), var(--light-button-gradient-end));
color: var(--text-color);
border: none;
border-radius: 8px;
padding: 10px 20px;
cursor: pointer;
font-size: 1rem;
font-weight: 600;
transition: background 0.3s ease;
touch-action: manipulation;
}
[data-theme="dark"] button {
background: linear-gradient(45deg, var(--dark-button-gradient-start), var(--dark-button-gradient-end));
}
button:hover {
filter: brightness(1.1);
}
`;
console.log('Serving fallback CSS');
reply.header('Content-Type', 'text/css');
reply.header('Access-Control-Allow-Origin', '*');
return fallbackCSS;
}
});
// --- Widget Upload Endpoints and Plugin Store ---
// Plugins live in the `plugins` table (issue #105 Phase 0) so they survive image
// upgrades; the old widgets_registry.json is only read once by migration 18.
// A plugin may embed a manifest in its HTML to opt into platform capabilities
// (issue #105 Phase 1). Plain widgets simply omit the block and work as before.
// <script type="application/json" id="homeglow-manifest">{ ... }</script>
const PLUGIN_MANIFEST_REGEX = /<script[^>]*id=["']homeglow-manifest["'][^>]*>([\s\S]*?)<\/script>/i;
const PLUGIN_ID_REGEX = /^[a-z0-9][a-z0-9-]{0,63}$/;
const PLUGIN_SETTING_KEY_REGEX = /^[a-zA-Z][a-zA-Z0-9]{0,63}$/;
const PLUGIN_DESCRIPTION_MAX_LENGTH = 300;
const PLUGIN_SETTING_TYPES = new Set(['number', 'string', 'boolean', 'select']);
const PLUGIN_SETTING_SCOPES = new Set(['household', 'device']);
// Returns { manifest: object|null, errors: string[] }. A missing block is not
// an error (legacy widget); a present-but-invalid block is, so a typo'd
// manifest fails the upload loudly instead of silently installing as legacy.
function extractPluginManifest(htmlContent) {
const match = htmlContent.match(PLUGIN_MANIFEST_REGEX);
if (!match) {
return { manifest: null, errors: [] };
}
let manifest;
try {
manifest = JSON.parse(match[1]);
} catch (parseError) {
return { manifest: null, errors: [`Manifest is not valid JSON: ${parseError.message}`] };
}
const errors = [];
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
return { manifest: null, errors: ['Manifest must be a JSON object.'] };
}
if (manifest.manifestVersion !== 1) {
errors.push('manifestVersion must be 1.');
}
if (typeof manifest.id !== 'string' || !PLUGIN_ID_REGEX.test(manifest.id)) {
errors.push('id is required and must be a lowercase slug (a-z, 0-9, hyphens, max 64 chars).');
}
if (manifest.name !== undefined && typeof manifest.name !== 'string') {
errors.push('name must be a string.');
}
// A short human sentence for the plugin list and the browse view (issue
// #147). Optional: requiring it would invalidate every plugin already
// installed. Capped because it renders as a card subtitle, not a README.
if (manifest.description !== undefined) {
if (typeof manifest.description !== 'string') {
errors.push('description must be a string.');
} else if (manifest.description.trim().length > PLUGIN_DESCRIPTION_MAX_LENGTH) {
errors.push(`description must be ${PLUGIN_DESCRIPTION_MAX_LENGTH} characters or fewer.`);
}
}
if (manifest.apiVersion !== undefined && manifest.apiVersion !== 'v1') {
errors.push("apiVersion must be 'v1'.");
}
if (manifest.storage !== undefined && typeof manifest.storage !== 'boolean') {
errors.push('storage must be a boolean.');
}
if (manifest.events !== undefined) {
if (!Array.isArray(manifest.events) || manifest.events.some((event) => typeof event !== 'string')) {
errors.push('events must be an array of strings.');
} else {
for (const event of manifest.events) {
if (!pluginEvents.isKnownEvent(event)) {
errors.push(`events: "${event}" is not a known event (catalog: ${pluginEvents.PLUGIN_EVENT_CATALOG.join(', ')}).`);
}
}
}
}
if (manifest.reactions !== undefined) {
if (!Array.isArray(manifest.reactions)) {
errors.push('reactions must be an array.');
} else {
if (manifest.reactions.length > 0 && manifest.storage !== true) {
errors.push('reactions require "storage": true (they write to plugin storage).');
}
manifest.reactions.forEach((reaction, index) => {
if (!reaction || typeof reaction !== 'object') {
errors.push(`reactions[${index}] must be an object.`);
return;
}
if (typeof reaction.on !== 'string' || !pluginEvents.isKnownEvent(reaction.on)) {
errors.push(`reactions[${index}].on must be a known event (catalog: ${pluginEvents.PLUGIN_EVENT_CATALOG.join(', ')}).`);
}
if (reaction.action !== 'increment') {
errors.push(`reactions[${index}].action must be 'increment' (the only supported action).`);
}
if (typeof reaction.key !== 'string' || !PLUGIN_STORAGE_KEY_REGEX.test(reaction.key)) {
errors.push(`reactions[${index}].key must be a valid storage key.`);
}
if (typeof reaction.path !== 'string' || reaction.path.length === 0 ||
reaction.path.split('.').some((segment) => segment.length === 0)) {
errors.push(`reactions[${index}].path must be a non-empty dot-separated path.`);
}
// Optional multiplier applied to the resolved delta — factor: -1 lets a
// mirror reaction (e.g. on chore.uncompleted) compensate a setting- or
// payload-driven increment that cannot be negated in the manifest.
if (reaction.factor !== undefined && (typeof reaction.factor !== 'number' || !Number.isFinite(reaction.factor))) {
errors.push(`reactions[${index}].factor must be a finite number.`);
}
const delta = reaction.delta;
const deltaValid = (typeof delta === 'number' && Number.isFinite(delta)) ||
(delta && typeof delta === 'object' && !Array.isArray(delta) &&
(typeof delta.setting === 'string' || typeof delta.payload === 'string'));
if (!deltaValid) {
errors.push(`reactions[${index}].delta must be a number, { "setting": "<key>" }, or { "payload": "<field>" }.`);
} else if (delta && typeof delta === 'object' && typeof delta.setting === 'string') {
const declared = Array.isArray(manifest.settings)
? manifest.settings.find((setting) => setting && setting.key === delta.setting)
: null;
// Device-scoped settings are excluded: a server-side reaction has no
// device context to resolve them against.
if (!declared || declared.type !== 'number' || declared.scope === 'device') {
errors.push(`reactions[${index}].delta.setting must reference a declared household number setting.`);
}
}
});
}
}
if (manifest.settings !== undefined) {
if (!Array.isArray(manifest.settings)) {
errors.push('settings must be an array.');
} else {
manifest.settings.forEach((setting, index) => {
if (!setting || typeof setting !== 'object') {
errors.push(`settings[${index}] must be an object.`);
return;
}
if (typeof setting.key !== 'string' || !PLUGIN_SETTING_KEY_REGEX.test(setting.key)) {
errors.push(`settings[${index}].key must be an alphanumeric identifier.`);
}
if (!PLUGIN_SETTING_TYPES.has(setting.type)) {
errors.push(`settings[${index}].type must be one of: ${[...PLUGIN_SETTING_TYPES].join(', ')}.`);
}
if (setting.scope !== undefined && !PLUGIN_SETTING_SCOPES.has(setting.scope)) {
errors.push(`settings[${index}].scope must be 'household' or 'device'.`);
}
if (setting.type === 'select' && (
!Array.isArray(setting.options) || setting.options.length === 0 ||
setting.options.some((option) => typeof option !== 'string')
)) {
errors.push(`settings[${index}].options must be a non-empty array of strings for select settings.`);
}
if (setting.min !== undefined && typeof setting.min !== 'number') {
errors.push(`settings[${index}].min must be a number.`);
}
if (setting.max !== undefined && typeof setting.max !== 'number') {
errors.push(`settings[${index}].max must be a number.`);
}
});
}
}
return { manifest: errors.length === 0 ? manifest : null, errors };
}
// Shared by upload and GitHub install: validate any embedded manifest and
// upsert the plugin row. Returns an { error, status } object on rejection.
function installPluginRow({ filename, fallbackName, content, source, originalUrl = null }) {
const { manifest, errors } = extractPluginManifest(content);
if (errors.length > 0) {
return { error: `Invalid plugin manifest: ${errors.join(' ')}`, status: 400 };
}
const pluginId = manifest ? manifest.id : null;
if (pluginId) {
const conflict = db.prepare('SELECT filename FROM plugins WHERE plugin_id = ? AND filename != ?')
.get(pluginId, filename);
if (conflict) {
return {
error: `Plugin id "${pluginId}" is already used by ${conflict.filename}.`,
status: 409,
};
}
}
db.prepare(`
INSERT INTO plugins (filename, name, content, source, original_url, plugin_id, manifest_json)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(filename) DO UPDATE SET
content = excluded.content,
name = excluded.name,
source = excluded.source,
original_url = excluded.original_url,
plugin_id = excluded.plugin_id,
manifest_json = excluded.manifest_json,
updated_at = CURRENT_TIMESTAMP
`).run(
filename,
(manifest && manifest.name) || fallbackName,
content,
source,
originalUrl,
pluginId,
manifest ? JSON.stringify(manifest) : null
);
return { pluginId };
}
// Helper: Load legacy on-disk widget registry (kept for the debug endpoint)
async function loadWidgetRegistry() {
try {
const data = await fs.readFile(widgetRegistryPath, 'utf-8');
return JSON.parse(data);
} catch (err) {
return [];
}
}
// Helper: List installed plugins in the legacy registry response shape
function listInstalledPlugins() {
return db.prepare(
'SELECT filename, name, source, original_url, plugin_id, manifest_json, installed_at FROM plugins ORDER BY installed_at, filename'
).all().map((row) => ({