-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
964 lines (877 loc) · 37.9 KB
/
Copy pathserver.js
File metadata and controls
964 lines (877 loc) · 37.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
// server.js
require("dotenv").config();
const express = require("express");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const rateLimit = require("express-rate-limit");
const crypto = require("crypto");
const path = require("path");
const store = require("./store");
const {
DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET, DISCORD_REDIRECT_URI,
SESSION_SECRET, ALLOWED_DISCORD_IDS, BOT_TOKEN, ADMIN_DISCORD_ID, PORT
} = process.env;
if (!DISCORD_CLIENT_ID || !DISCORD_CLIENT_SECRET || !DISCORD_REDIRECT_URI || !SESSION_SECRET) {
console.error("Missing required env vars.");
process.exit(1);
}
const envAllowlist = (ALLOWED_DISCORD_IDS || "").split(",").map((s) => s.trim()).filter(Boolean);
function isAllowedDiscordId(id) {
if (id === ADMIN_DISCORD_ID) return true;
const dynamicIds = store.listAllowlist().map((e) => e.id);
const effective = envAllowlist.concat(dynamicIds);
return !effective.length || effective.includes(id);
}
const app = express();
app.set("trust proxy", 1);
// The default 100kb is comfortably under the size of a real export file, which
// import posts back in full, so the ceiling is raised for that path's sake.
app.use(express.json({ limit: "10mb" }));
app.use(session({
store: new FileStore({
path: path.join(__dirname, "data", "sessions"),
ttl: 60 * 60 * 24 * 30,
retries: 1,
logFn: function() {}
}),
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", maxAge: 1000 * 60 * 60 * 24 * 30 }
}));
// Security headers. The CSP is deliberately not locked all the way down:
// the app uses inline styles heavily (style="..." attributes plus one big
// inline <style> block), so style-src has to allow 'unsafe-inline'. Scripts,
// though, are all self-hosted now (app.js + the vendored marked/DOMPurify),
// so script-src stays strict. Note bodies can embed images from any https
// host, so img-src is intentionally broad.
app.use((req, res, next) => {
res.setHeader("Content-Security-Policy", [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src 'self' https://fonts.gstatic.com",
"img-src 'self' data: https:",
"connect-src 'self'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"object-src 'none'"
].join("; "));
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
res.setHeader("X-Frame-Options", "DENY");
next();
});
function renderErrorPage(title, message) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${title} — Ledger</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&display=swap" rel="stylesheet">
<style>
:root { --bg:#14181c; --surface:#1b2126; --border:#2b333a; --ink:#ece8e1; --ink-mid:#a8b4be; --accent:#e8a33d; }
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
font-family: 'IBM Plex Sans', sans-serif; background: var(--bg); color: var(--ink);
display: flex; align-items: center; justify-content: center;
}
.card {
text-align: center; padding: 44px 40px; border: 1px solid var(--border);
border-radius: 10px; background: var(--surface); max-width: 360px; width: 90%;
}
.mark { font-size: 32px; color: var(--accent); font-family: 'IBM Plex Mono', monospace; display: block; margin-bottom: 8px; }
h1 { font-family: 'IBM Plex Mono', monospace; letter-spacing: 0.1em; font-size: 17px; margin: 0 0 12px; }
p { color: var(--ink-mid); font-size: 13.5px; line-height: 1.6; margin: 0 0 26px; }
a.back {
display: inline-block; background: var(--accent); color: #1b130a;
padding: 11px 20px; border-radius: 7px; font-weight: 600; font-size: 14px; text-decoration: none;
}
a.back:hover { filter: brightness(1.08); }
</style>
</head>
<body>
<div class="card">
<span class="mark">¶</span>
<h1>${title}</h1>
<p>${message}</p>
<a class="back" href="/">Back to Ledger</a>
</div>
</body>
</html>`;
}
// The route tests sign in as many accounts in quick succession, which would
// otherwise trip the login limiter. Opt-in via env so real deployments are
// never accidentally left unthrottled.
const rateLimitsDisabled = process.env.LEDGER_DISABLE_RATE_LIMIT === "1";
const authLimiter = rateLimit({
windowMs: 60 * 1000,
limit: 10,
standardHeaders: true,
legacyHeaders: false,
skip: () => rateLimitsDisabled,
handler: (req, res) => {
res.status(429).send(renderErrorPage(
"Slow down",
"Too many login attempts from here. Give it a minute, then try signing in again."
));
}
});
const apiLimiter = rateLimit({
windowMs: 60 * 1000,
limit: 120,
standardHeaders: true,
legacyHeaders: false,
skip: () => rateLimitsDisabled,
// Key by logged-in user when possible, so people sharing an IP/network
// (e.g. two housemates both using Bills) don't throttle each other.
keyGenerator: (req) => (req.session && req.session.user) ? `user:${req.session.user.id}` : req.ip,
message: { error: "Too many requests. Slow down and try again in a minute." }
});
function requireAuth(req, res, next) {
if (!req.session.user) return res.status(401).json({ error: "Not logged in" });
next();
}
function requireAdmin(req, res, next) {
if (!req.session.user) return res.status(401).json({ error: "Not logged in" });
if (!ADMIN_DISCORD_ID || req.session.user.id !== ADMIN_DISCORD_ID) {
return res.status(403).json({ error: "Admin only" });
}
next();
}
function requireBillsAccess(req, res, next) {
if (!req.session.user) return res.status(401).json({ error: "Not logged in" });
const id = req.session.user.id;
if (id === ADMIN_DISCORD_ID || store.hasBillsAccess(id)) return next();
return res.status(403).json({ error: "You don't have access to Bills" });
}
// ---------- Discord bot helpers ----------
const DISCORD_API = "https://discord.com/api/v10";
async function botFetch(path, opts = {}) {
if (!BOT_TOKEN) throw new Error("BOT_TOKEN not configured");
const res = await fetch(`${DISCORD_API}${path}`, {
...opts,
headers: { "Authorization": `Bot ${BOT_TOKEN}`, "Content-Type": "application/json", ...(opts.headers || {}) }
});
if (!res.ok) {
const body = await res.text();
throw new Error(`Discord API error ${res.status}: ${body}`);
}
return res.status === 204 ? null : res.json();
}
async function getDMChannel(discordUserId) {
return botFetch("/users/@me/channels", {
method: "POST",
body: JSON.stringify({ recipient_id: discordUserId })
});
}
function splitMessage(text, max = 1900) {
if (text.length <= max) return [text];
const chunks = [];
let remaining = text;
while (remaining.length > max) {
let split = remaining.lastIndexOf("\n", max);
if (split < max / 2) split = max;
chunks.push(remaining.slice(0, split));
remaining = remaining.slice(split).replace(/^\n+/, "");
}
if (remaining.trim()) chunks.push(remaining);
return chunks;
}
function getAppUrl() {
return "https://notes.awucard.me";
}
function buildReminderBlurb(note) {
const title = note.title?.trim() || "Untitled note";
const body = (note.body || "").replace(/\s+/g, " ").trim();
const blurb = body
? body.length > 180
? `${body.slice(0, 180)}...\n\n[See more on Ledger]`
: body
: "No note body yet.";
return `Hey, wake up. You asked me to remind you about this note.\n\n**${title}**\n\n${blurb}`;
}
async function sendDM(discordUserId, content, options = {}) {
const channel = await getDMChannel(discordUserId);
const chunks = splitMessage(content, options.maxLength || 3800);
const label = options.label || "Ledger";
for (const chunk of chunks) {
const payload = {
content: "",
embeds: [{
title: label,
description: chunk,
color: 0xE8A33D,
footer: { text: "Sent from Ledger" }
}]
};
if (options.buttonUrl) {
payload.components = [{
type: 1,
components: [{
type: 2,
style: 5,
label: options.buttonLabel || "Head to Ledger",
url: options.buttonUrl
}]
}];
}
await botFetch(`/channels/${channel.id}/messages`, {
method: "POST",
body: JSON.stringify(payload)
});
}
}
function formatNoteForDiscord(note, label = null) {
let msg = label ? `${label}\n` : "";
if (note.title) msg += `**${note.title}**\n`;
if (note.body) msg += `\n${note.body}`;
if (note.tags && note.tags.length) msg += `\n\n🏷️ ${note.tags.map((t) => `#${t}`).join(" ")}`;
return msg.trim();
}
// ---------- iCal (.ics) feed ----------
// Recurring bills use RRULE rather than enumerating every occurrence -- the
// idiomatic iCal approach. Known limitation: RRULE has no "clamp to end of
// month" concept, so a bill due on the 29th-31st will simply be skipped by
// Google/Apple Calendar in shorter months, unlike this app's own due-date
// rollover handling.
const BILL_RRULE_FREQ = {
weekly: "FREQ=WEEKLY",
biweekly: "FREQ=WEEKLY;INTERVAL=2",
monthly: "FREQ=MONTHLY",
quarterly: "FREQ=MONTHLY;INTERVAL=3",
yearly: "FREQ=YEARLY"
};
function icsEscape(text) {
return String(text || "").replace(/[\\;,]/g, (c) => "\\" + c).replace(/\n/g, "\\n");
}
function icsDate(dateStr) {
return dateStr.replace(/-/g, "");
}
function buildICSFeed(bills, notes) {
const stamp = new Date().toISOString().replace(/[-:]/g, "").split(".")[0] + "Z";
const lines = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Ledger//Bill and Note Due Dates//EN", "CALSCALE:GREGORIAN"];
bills.forEach((b) => {
if (b.paid || !b.dueDate) return;
lines.push("BEGIN:VEVENT");
lines.push(`UID:bill-${b.id}@ledger`);
lines.push(`DTSTAMP:${stamp}`);
lines.push(`DTSTART;VALUE=DATE:${icsDate(b.dueDate)}`);
const rrule = BILL_RRULE_FREQ[b.frequency];
if (rrule) lines.push(`RRULE:${rrule}`);
lines.push(`SUMMARY:${icsEscape(`${b.name} due (${b.currency} $${Number(b.amount).toFixed(2)})`)}`);
lines.push("END:VEVENT");
});
notes.forEach((n) => {
if (!n.dueDate) return;
lines.push("BEGIN:VEVENT");
lines.push(`UID:note-${n.id}@ledger`);
lines.push(`DTSTAMP:${stamp}`);
lines.push(`DTSTART;VALUE=DATE:${icsDate(n.dueDate)}`);
lines.push(`SUMMARY:${icsEscape(n.title || "Untitled note")}`);
lines.push("END:VEVENT");
});
lines.push("END:VCALENDAR");
return lines.join("\r\n") + "\r\n";
}
app.get("/calendar/:token.ics", (req, res) => {
const user = store.getUserByIcalToken(req.params.token);
if (!user) return res.status(404).send("Not found");
const bills = store.listBills(user.id);
const notes = store.listNotes(user.id, "__all__").filter((n) => n.dueDate);
res.setHeader("Content-Type", "text/calendar; charset=utf-8");
res.send(buildICSFeed(bills, notes));
});
// ---------- Reminder job ----------
function startReminderJob() {
setInterval(async () => {
const due = store.getDueReminders();
for (const reminder of due) {
try {
const user = store.getUser(reminder.ownerId);
const note = store.getNote(reminder.ownerId, reminder.noteId);
const title = note ? note.title : reminder.noteTitle;
const body = note ? note.body : "(Note no longer exists)";
const tags = note ? note.tags : [];
const fakeNote = { title, body, tags };
const content = buildReminderBlurb(fakeNote);
if (user) await sendDM(user.id, content, {
label: "Hey, wake up",
buttonUrl: getAppUrl()
});
} catch (err) {
console.error("Reminder DM failed:", err.message);
}
if (reminder.repeat && reminder.repeatInterval) {
await store.rescheduleReminder(reminder.id, reminder.repeatInterval);
} else {
await store.deleteReminder(reminder.ownerId, reminder.id);
}
}
}, 30000);
}
// ---------- Bill due-date reminder job ----------
function dateToStr(d) {
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
}
function startBillReminderJob() {
setInterval(async () => {
const todayStr = dateToStr(new Date());
const todayMidnight = new Date(); todayMidnight.setHours(0, 0, 0, 0);
for (const bill of store.getAllBills()) {
if (bill.paid || !bill.dueDate || bill.reminderDays == null) continue;
if (bill.lastReminderSent === todayStr) continue;
const due = new Date(bill.dueDate + "T00:00:00");
const daysUntilDue = Math.round((due - todayMidnight) / 86400000);
if (daysUntilDue !== Number(bill.reminderDays)) continue;
try {
const dayWord = daysUntilDue === 1 ? "day" : "days";
await sendDM(
bill.ownerId,
`💳 **${bill.name}** is due in ${daysUntilDue} ${dayWord} (${bill.dueDate}) — ${bill.currency} $${Number(bill.amount).toFixed(2)}`,
{ label: "Bill reminder", buttonUrl: getAppUrl(), buttonLabel: "View in Ledger" }
);
} catch (err) {
console.error("Bill reminder DM failed:", err.message);
}
await store.markBillReminderSent(bill.id, todayStr);
}
}, 15 * 60 * 1000);
}
// ---------- Digest DM job (opt-in daily/weekly/monthly summary) ----------
const DIGEST_INTERVALS = { daily: 24 * 60 * 60 * 1000, weekly: 7 * 24 * 60 * 60 * 1000, monthly: 30 * 24 * 60 * 60 * 1000 };
function buildDigestMessage(overdue, dueSoon, reminders, timezone) {
const tz = timezone || "UTC";
// Spelled-out month (e.g. "Jul 16, 2026") sidesteps the MM/DD vs DD/MM
// ambiguity entirely, and the reminder time is shown in the user's own
// stored timezone rather than a fixed UTC.
const fmt = (ts) => new Date(ts).toLocaleString("en-US", { timeZone: tz, month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" });
const lines = [];
if (overdue.length) {
lines.push("**Overdue:**");
overdue.forEach((b) => lines.push(`- ${b.name} — ${b.currency} $${Number(b.amount).toFixed(2)} (was due ${b.dueDate})`));
}
if (dueSoon.length) {
lines.push(overdue.length ? "\n**Due soon:**" : "**Due soon:**");
dueSoon.forEach((b) => lines.push(`- ${b.name} — ${b.currency} $${Number(b.amount).toFixed(2)} (due ${b.dueDate})`));
}
if (reminders.length) {
lines.push((overdue.length || dueSoon.length) ? "\n**Upcoming reminders:**" : "**Upcoming reminders:**");
reminders.forEach((r) => lines.push(`- ${r.noteTitle || "Untitled note"} — ${fmt(r.fireAt)}`));
}
return lines.join("\n");
}
function startDigestJob() {
setInterval(async () => {
const now = Date.now();
const todayStr = dateToStr(new Date());
for (const user of store.listUsersWithDigestEnabled()) {
const interval = DIGEST_INTERVALS[user.digestFrequency];
if (!interval) continue;
const last = user.lastDigestSentAt || 0;
if (now - last < interval) continue;
try {
const bills = store.listBills(user.id);
const overdue = bills.filter((b) => !b.paid && b.dueDate && b.dueDate < todayStr);
const cutoffStr = dateToStr(new Date(now + interval));
const dueSoon = bills.filter((b) => !b.paid && b.dueDate && b.dueDate >= todayStr && b.dueDate <= cutoffStr);
const reminders = store.listReminders(user.id).filter((r) => r.fireAt <= now + interval);
if (overdue.length || dueSoon.length || reminders.length) {
const content = buildDigestMessage(overdue, dueSoon, reminders, user.timezone);
await sendDM(user.id, content, { label: "Ledger digest", buttonUrl: getAppUrl() });
}
} catch (err) {
console.error("Digest DM failed:", err.message);
}
await store.markDigestSent(user.id);
}
}, 30 * 60 * 1000);
}
// ---------- Discord OAuth2 ----------
app.get("/auth/discord", authLimiter, (req, res) => {
const state = crypto.randomBytes(16).toString("hex");
req.session.oauthState = state;
const params = new URLSearchParams({
client_id: DISCORD_CLIENT_ID, redirect_uri: DISCORD_REDIRECT_URI,
response_type: "code", scope: "identify", state, prompt: "consent"
});
res.redirect(`https://discord.com/oauth2/authorize?${params.toString()}`);
});
app.get("/auth/discord/callback", authLimiter, async (req, res) => {
const { code, state } = req.query;
if (!code || !state || state !== req.session.oauthState) {
return res.status(400).send("Login failed: invalid or expired state. Go back and try again.");
}
delete req.session.oauthState;
try {
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ client_id: DISCORD_CLIENT_ID, client_secret: DISCORD_CLIENT_SECRET, grant_type: "authorization_code", code, redirect_uri: DISCORD_REDIRECT_URI })
});
if (!tokenRes.ok) throw new Error("Token exchange failed");
const tokenData = await tokenRes.json();
const profileRes = await fetch("https://discord.com/api/users/@me", { headers: { Authorization: `Bearer ${tokenData.access_token}` } });
if (!profileRes.ok) throw new Error("Could not fetch Discord profile");
const profile = await profileRes.json();
if (!isAllowedDiscordId(profile.id)) {
return res.status(403).send("Your Discord account isn't on the guest list for this Ledger.");
}
const user = await store.upsertUser(profile);
await store.recordLogin(user.id);
req.session.user = {
id: user.id, username: user.username, avatar: user.avatar, timezone: user.timezone || "UTC",
incomeEstimate: user.incomeEstimate != null ? user.incomeEstimate : null,
incomeCurrency: user.incomeCurrency || user.defaultCurrency,
authType: "discord", mustChangePassword: false, digestFrequency: user.digestFrequency,
defaultCurrency: user.defaultCurrency, billCategories: user.billCategories
};
res.redirect("/");
} catch (err) {
console.error(err);
res.status(500).send("Login failed. Check the server logs.");
}
});
app.post("/auth/local-login", authLimiter, async (req, res) => {
const { username, password } = req.body || {};
if (!username || !password) return res.status(400).json({ error: "Username and password are required." });
const user = store.verifyLocalLogin(username, password);
if (!user) return res.status(401).json({ error: "Invalid username or password." });
await store.recordLogin(user.id);
req.session.user = {
id: user.id, username: user.username, avatar: null, timezone: user.timezone || "UTC",
incomeEstimate: user.incomeEstimate != null ? user.incomeEstimate : null,
incomeCurrency: user.incomeCurrency || user.defaultCurrency,
authType: "local", mustChangePassword: user.mustChangePassword, digestFrequency: user.digestFrequency,
defaultCurrency: user.defaultCurrency, billCategories: user.billCategories
};
res.json({ ok: true });
});
app.post("/auth/logout", (req, res) => {
req.session.destroy(() => res.json({ ok: true }));
});
app.get("/api/me", (req, res) => {
if (!req.session.user) return res.status(401).json({ error: "Not logged in" });
const isAdmin = req.session.user.id === ADMIN_DISCORD_ID;
const canAccessBills = isAdmin || store.hasBillsAccess(req.session.user.id);
res.json({ ...req.session.user, isAdmin, canAccessBills });
});
app.put("/api/me/timezone", requireAuth, async (req, res) => {
const { timezone } = req.body || {};
if (!timezone) return res.status(400).json({ error: "timezone required" });
const user = await store.updateUserTimezone(req.session.user.id, timezone);
req.session.user.timezone = timezone;
res.json(user);
});
app.put("/api/me/income", requireAuth, async (req, res) => {
const { amount, currency } = req.body || {};
const parsed = amount === null || amount === "" || amount === undefined ? null : Number(amount);
if (parsed != null && !Number.isFinite(parsed)) {
return res.status(400).json({ error: "amount must be a number" });
}
const user = await store.updateUserIncome(req.session.user.id, parsed, currency);
req.session.user.incomeEstimate = user.incomeEstimate;
req.session.user.incomeCurrency = user.incomeCurrency;
res.json(user);
});
app.get("/api/me/export", requireAuth, (req, res) => {
const id = req.session.user.id;
const canAccessBills = id === ADMIN_DISCORD_ID || store.hasBillsAccess(id);
const data = {
exportedAt: new Date().toISOString(),
user: { id, username: req.session.user.username },
characters: store.listCharacters(id),
notes: store.listNotes(id, "__all__"),
reminders: store.listReminders(id),
bills: canAccessBills ? store.listBills(id) : []
};
res.setHeader("Content-Disposition", `attachment; filename="ledger-export-${id}.json"`);
res.json(data);
});
app.post("/api/me/delete-data", requireAuth, async (req, res) => {
await store.deleteAllUserData(req.session.user.id);
req.session.destroy(() => res.json({ ok: true }));
});
app.put("/api/me/password", requireAuth, async (req, res) => {
if (req.session.user.authType !== "local") {
return res.status(400).json({ error: "Discord accounts don't have a Ledger password." });
}
const { currentPassword, newPassword } = req.body || {};
if (!newPassword || newPassword.length < 8) {
return res.status(400).json({ error: "New password must be at least 8 characters." });
}
const ok = await store.changeOwnPassword(req.session.user.id, currentPassword || "", newPassword);
if (!ok) return res.status(400).json({ error: "Current password is incorrect." });
req.session.user.mustChangePassword = false;
res.json({ ok: true });
});
app.get("/api/me/ical-token", requireAuth, async (req, res) => {
const token = await store.getOrCreateIcalToken(req.session.user.id);
res.json({ token, url: `${getAppUrl()}/calendar/${token}.ics` });
});
app.post("/api/me/ical-token/regenerate", requireAuth, async (req, res) => {
const token = await store.regenerateIcalToken(req.session.user.id);
res.json({ token, url: `${getAppUrl()}/calendar/${token}.ics` });
});
app.put("/api/me/digest", requireAuth, async (req, res) => {
const { frequency } = req.body || {};
try {
const user = await store.updateDigestFrequency(req.session.user.id, frequency);
req.session.user.digestFrequency = user.digestFrequency;
res.json({ ok: true });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.put("/api/me/default-currency", requireAuth, async (req, res) => {
const { currency, applyToBills } = req.body || {};
try {
const user = await store.updateDefaultCurrency(req.session.user.id, currency);
req.session.user.defaultCurrency = user.defaultCurrency;
let billsUpdated = 0;
if (applyToBills) {
billsUpdated = await store.updateAllBillsCurrency(req.session.user.id, user.defaultCurrency);
}
res.json({ ok: true, billsUpdated });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.put("/api/me/bill-categories", requireAuth, async (req, res) => {
const { categories } = req.body || {};
try {
const user = await store.updateBillCategories(req.session.user.id, categories);
req.session.user.billCategories = user.billCategories;
res.json({ ok: true, billCategories: user.billCategories });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.use("/api", apiLimiter);
// ---------- Characters ----------
app.get("/api/characters", requireAuth, (req, res) => res.json(store.listCharacters(req.session.user.id)));
app.post("/api/characters", requireAuth, async (req, res) => {
const { name, color } = req.body || {};
if (!name || !name.trim()) return res.status(400).json({ error: "Name is required" });
res.status(201).json(await store.createCharacter(req.session.user.id, { name: name.trim(), color }));
});
app.put("/api/characters/:id", requireAuth, async (req, res) => {
const c = await store.updateCharacter(req.session.user.id, req.params.id, req.body || {});
if (!c) return res.status(404).json({ error: "Not found" });
res.json(c);
});
app.delete("/api/characters/:id", requireAuth, async (req, res) => {
const ok = await store.deleteCharacter(req.session.user.id, req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
// ---------- Notes ----------
app.get("/api/notes", requireAuth, (req, res) => {
res.json(store.listNotes(req.session.user.id, req.query.characterId || "__all__"));
});
app.post("/api/notes", requireAuth, async (req, res) => {
res.status(201).json(await store.createNote(req.session.user.id, req.body || {}));
});
app.put("/api/notes/:id", requireAuth, async (req, res) => {
const note = await store.updateNote(req.session.user.id, req.params.id, req.body || {});
if (!note) return res.status(404).json({ error: "Not found" });
res.json(note);
});
app.delete("/api/notes/:id", requireAuth, async (req, res) => {
const ok = await store.deleteNote(req.session.user.id, req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
app.post("/api/notes/:id/restore-previous", requireAuth, async (req, res) => {
const note = await store.restorePreviousVersion(req.session.user.id, req.params.id);
if (!note) return res.status(404).json({ error: "No previous version to restore" });
res.json(note);
});
app.delete("/api/notes", requireAuth, async (req, res) => {
await store.clearNotes(req.session.user.id, req.query.characterId || "__all__");
res.json({ ok: true });
});
// ---------- Send note to DM ----------
app.post("/api/notes/:id/send-dm", requireAuth, async (req, res) => {
if (!BOT_TOKEN) return res.status(503).json({ error: "Bot not configured — add BOT_TOKEN to your environment variables." });
const note = store.getNote(req.session.user.id, req.params.id);
if (!note) return res.status(404).json({ error: "Not found" });
try {
await sendDM(req.session.user.id, formatNoteForDiscord(note), { label: "Note from Ledger" });
res.json({ ok: true });
} catch (err) {
console.error("Send DM failed:", err.message);
res.status(500).json({ error: err.message });
}
});
// ---------- Reminders ----------
app.get("/api/reminders", requireAuth, (req, res) => {
res.json(store.listReminders(req.session.user.id));
});
app.get("/api/notes/:id/reminders", requireAuth, (req, res) => {
res.json(store.listRemindersForNote(req.session.user.id, req.params.id));
});
app.post("/api/reminders", requireAuth, async (req, res) => {
if (!BOT_TOKEN) return res.status(503).json({ error: "Bot not configured — add BOT_TOKEN to your environment variables." });
const { noteId, fireAt, repeat, repeatInterval, noteTitle } = req.body || {};
if (!noteId || !fireAt) return res.status(400).json({ error: "noteId and fireAt required" });
const reminder = await store.createReminder(req.session.user.id, { noteId, fireAt, repeat, repeatInterval, noteTitle });
res.status(201).json(reminder);
});
app.delete("/api/reminders/:id", requireAuth, async (req, res) => {
const ok = await store.deleteReminder(req.session.user.id, req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
// ---------- Bills (per-user, gated by bills access) ----------
app.get("/api/bills", requireBillsAccess, (req, res) => res.json(store.listBills(req.session.user.id)));
app.post("/api/bills", requireBillsAccess, async (req, res) => {
const bill = await store.createBill(req.session.user.id, req.body || {});
res.status(201).json(bill);
});
app.put("/api/bills/:id", requireBillsAccess, async (req, res) => {
const bill = await store.updateBill(req.session.user.id, req.params.id, req.body || {});
if (!bill) return res.status(404).json({ error: "Not found" });
res.json(bill);
});
app.post("/api/bills/:id/pay", requireBillsAccess, async (req, res) => {
const bill = await store.markBillPaid(req.session.user.id, req.params.id);
if (!bill) return res.status(404).json({ error: "Not found" });
if (BOT_TOKEN) {
sendDM(req.session.user.id, `✅ **${bill.name}** marked as paid. Next due: ${bill.dueDate || "—"}`, { label: "Bill paid" })
.catch(e => console.error("Bill paid DM:", e.message));
}
res.json(bill);
});
app.post("/api/bills/:id/unpay", requireBillsAccess, async (req, res) => {
const bill = await store.markBillUnpaid(req.session.user.id, req.params.id);
if (!bill) return res.status(404).json({ error: "Not found" });
res.json(bill);
});
app.post("/api/bills/:id/send-dm", requireBillsAccess, async (req, res) => {
if (!BOT_TOKEN) return res.status(503).json({ error: "Bot not configured" });
const bill = store.getBill(req.session.user.id, req.params.id);
if (!bill) return res.status(404).json({ error: "Not found" });
const today = dateToStr(new Date());
const isOverdue = bill.dueDate && bill.dueDate < today && !bill.paid;
const status = bill.paid ? "✅ Paid" : isOverdue ? "⚠️ Overdue" : "Upcoming";
const msg = `💳 **${bill.name}**\n\n**Amount:** ${bill.currency} $${Number(bill.amount).toFixed(2)}\n**Due:** ${bill.dueDate || "—"}\n**Status:** ${status}\n**Frequency:** ${bill.frequency}\n**Category:** ${bill.category}${bill.notes ? `\n**Notes:** ${bill.notes}` : ""}`;
try {
await sendDM(req.session.user.id, msg, { label: "Bill from Ledger", buttonUrl: getAppUrl(), buttonLabel: "View in Ledger" });
res.json({ ok: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.delete("/api/bills/:id", requireBillsAccess, async (req, res) => {
const ok = await store.deleteBill(req.session.user.id, req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
// ---------- Access allowlist (admin only) ----------
async function resolveDiscordUsername(id) {
const cached = store.getUser(id);
if (cached && cached.username) return cached.username;
if (!BOT_TOKEN) return null;
try {
const user = await botFetch(`/users/${id}`);
return (user && (user.global_name || user.username)) || null;
} catch (err) {
return null;
}
}
app.get("/api/admin/allowlist", requireAdmin, async (req, res) => {
const seen = new Set();
const result = [];
if (ADMIN_DISCORD_ID) {
result.push({ id: ADMIN_DISCORD_ID, label: "You (admin)", source: "admin" });
seen.add(ADMIN_DISCORD_ID);
}
store.listAllowlist().forEach((e) => {
if (seen.has(e.id)) return;
seen.add(e.id);
result.push({ id: e.id, label: e.label, source: "dynamic", addedAt: e.addedAt });
});
envAllowlist.forEach((id) => {
if (seen.has(id)) return;
seen.add(id);
result.push({ id, label: "", source: "env" });
});
await Promise.all(result.map(async (entry) => {
entry.username = await resolveDiscordUsername(entry.id);
entry.billsAccess = entry.source === "admin" || store.hasBillsAccess(entry.id);
entry.lastLoginAt = (store.getUser(entry.id) || {}).lastLoginAt || null;
}));
res.json(result);
});
app.post("/api/admin/allowlist", requireAdmin, async (req, res) => {
const { id, label } = req.body || {};
const trimmed = String(id || "").trim();
if (!/^\d{15,20}$/.test(trimmed)) {
return res.status(400).json({ error: "Enter a valid Discord user ID (numbers only)." });
}
const entry = await store.addAllowlistEntry(trimmed, label);
res.status(201).json(entry);
});
app.delete("/api/admin/allowlist/:id", requireAdmin, async (req, res) => {
const ok = await store.removeAllowlistEntry(req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
// ---------- Local (non-Discord) accounts (admin only) ----------
const LOCAL_USERNAME_RE = /^[a-zA-Z0-9_.-]{3,32}$/;
app.get("/api/admin/local-accounts", requireAdmin, (req, res) => {
const result = store.listLocalAccounts().map((u) => ({
id: u.id, username: u.username, createdAt: u.updatedAt,
mustChangePassword: u.mustChangePassword, billsAccess: store.hasBillsAccess(u.id),
lastLoginAt: u.lastLoginAt
}));
res.json(result);
});
app.post("/api/admin/local-accounts", requireAdmin, async (req, res) => {
const { username, password } = req.body || {};
const trimmed = String(username || "").trim();
if (!LOCAL_USERNAME_RE.test(trimmed)) {
return res.status(400).json({ error: "Username must be 3-32 characters (letters, numbers, _ . -)." });
}
if (!password || password.length < 8) {
return res.status(400).json({ error: "Password must be at least 8 characters." });
}
try {
const account = await store.createLocalAccount(trimmed, password);
res.status(201).json({ id: account.id, username: account.username, mustChangePassword: account.mustChangePassword });
} catch (err) {
res.status(409).json({ error: err.message });
}
});
app.put("/api/admin/local-accounts/:id/password", requireAdmin, async (req, res) => {
const { newPassword } = req.body || {};
if (!newPassword || newPassword.length < 8) {
return res.status(400).json({ error: "Password must be at least 8 characters." });
}
const account = await store.adminResetPassword(req.params.id, newPassword);
if (!account) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
app.delete("/api/admin/local-accounts/:id", requireAdmin, async (req, res) => {
const ok = await store.deleteLocalAccount(req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
// ---------- Bills access grants (admin only) ----------
app.post("/api/admin/bills-access", requireAdmin, async (req, res) => {
const { id } = req.body || {};
const trimmed = String(id || "").trim();
const isDiscordId = /^\d{15,20}$/.test(trimmed);
const isLocalAccountId = trimmed.startsWith("local_");
if (!isDiscordId && !isLocalAccountId) {
return res.status(400).json({ error: "Enter a valid Discord user ID (numbers only)." });
}
const entry = await store.grantBillsAccess(trimmed);
res.status(201).json(entry);
});
app.delete("/api/admin/bills-access/:id", requireAdmin, async (req, res) => {
const ok = await store.revokeBillsAccess(req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
// ---------- Budget ----------
app.get("/api/budget/:month", requireBillsAccess, (req, res) => {
res.json(store.getBudgetMonth(req.session.user.id, req.params.month));
});
app.put("/api/budget/target", requireBillsAccess, async (req, res) => {
const { month, category, amount } = req.body || {};
try {
res.json(await store.setBudgetTarget(req.session.user.id, month, category, amount));
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.post("/api/budget/expenses", requireBillsAccess, async (req, res) => {
try {
res.status(201).json(await store.createExpense(req.session.user.id, req.body || {}));
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.delete("/api/budget/expenses/:id", requireBillsAccess, async (req, res) => {
const ok = await store.deleteExpense(req.session.user.id, req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
// ---------- Import ----------
app.post("/api/import/preview", requireAuth, (req, res) => {
const { data } = req.body || {};
if (!data || typeof data !== "object") return res.status(400).json({ error: "That doesn't look like a Ledger export file." });
res.json(store.analyzeImport(req.session.user.id, data));
});
app.post("/api/import", requireAuth, async (req, res) => {
const { data, skip } = req.body || {};
if (!data || typeof data !== "object") return res.status(400).json({ error: "That doesn't look like a Ledger export file." });
try {
res.json(await store.importData(req.session.user.id, data, skip));
} catch (err) {
console.error("Import failed:", err.message);
res.status(400).json({ error: "Import failed. The file may be malformed." });
}
});
// ---------- Trash ----------
app.get("/api/trash", requireAuth, (req, res) => {
res.json(store.listTrash(req.session.user.id));
});
app.post("/api/trash/:type/:id/restore", requireAuth, async (req, res) => {
const ok = await store.restoreFromTrash(req.session.user.id, req.params.type, req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
app.delete("/api/trash/:type/:id", requireAuth, async (req, res) => {
const ok = await store.deleteFromTrashPermanently(req.session.user.id, req.params.type, req.params.id);
if (!ok) return res.status(404).json({ error: "Not found" });
res.json({ ok: true });
});
app.delete("/api/trash", requireAuth, async (req, res) => {
res.json(await store.emptyTrash(req.session.user.id));
});
// ---------- Trash purge job ----------
// Unlike the DM jobs this doesn't depend on Discord, so it runs regardless of
// whether a bot token is configured.
function startTrashPurgeJob() {
const runPurge = async () => {
try {
const purged = await store.purgeExpiredTrash();
if (purged.notes || purged.bills) {
console.log(`Trash purge: removed ${purged.notes} note(s), ${purged.bills} bill(s).`);
}
} catch (err) {
console.error("Trash purge failed:", err.message);
}
};
runPurge();
setInterval(runPurge, 24 * 60 * 60 * 1000);
}
app.get("/healthz", (req, res) => res.send("ok"));
app.use(express.static(path.join(__dirname, "public")));
// Only start listening / spin up the cron jobs when run directly
// (`node server.js`). When required by a test, the app is exported instead so
// it can be mounted on an ephemeral port without side effects.
if (require.main === module) {
const port = PORT || 3000;
app.listen(port, () => {
console.log(`Ledger running on http://localhost:${port}`);
startTrashPurgeJob();
if (BOT_TOKEN) {
startReminderJob();
startBillReminderJob();
startDigestJob();
console.log("Reminder jobs started.");
} else {
console.log("No BOT_TOKEN — DM and reminder features disabled.");
}
});
}
module.exports = app;