-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1770 lines (1603 loc) · 71.4 KB
/
Copy pathserver.js
File metadata and controls
1770 lines (1603 loc) · 71.4 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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const crypto = require('crypto');
const { auth, requiresAuth } = require('express-openid-connect');
const app = express();
app.use(cors());
app.use(express.json());
// Local mode detection: if the .env file is missing OR required Auth0 env vars are absent
const _envExists = fs.existsSync(path.join(__dirname, '.env'));
const _hasAuthVars = !!(process.env.AUTH0_CLIENT_ID && process.env.AUTH0_ISSUER_BASE_URL);
const LOCAL_MODE = (!_envExists) || (!_hasAuthVars);
// configure express-openid-connect using values from .env (if present)
// see .env for AUTH0_AUTH_REQUIRED, AUTH0_AUTH0LOGOUT, SECRET, AUTH0_BASEURL, AUTH0_CLIENT_ID, AUTH0_ISSUER_BASE_URL
const authConfig = {
authRequired: (process.env.AUTH0_AUTH_REQUIRED === 'true'),
auth0Logout: (process.env.AUTH0_AUTH0LOGOUT === 'true'),
secret: process.env.SECRET || 'replace-with-a-long-secret',
baseURL: process.env.AUTH0_BASEURL || `http://localhost:${process.env.PORT || 3000}`,
clientID: process.env.AUTH0_CLIENT_ID || '',
issuerBaseURL: process.env.AUTH0_ISSUER_BASE_URL || ''
};
// attach auth router (adds /login, /logout, /callback)
// In LOCAL_MODE we skip mounting the express-openid-connect auth router because
// it validates required config (clientID, issuer) at init and will throw when
// those values are empty. When running locally without a .env we simulate auth
// via /api/auth-status instead.
if (!LOCAL_MODE) {
app.use(auth(authConfig));
} else {
console.warn('[server] running in LOCAL_MODE: Auth0 integration disabled, simulating auth via /api/auth-status');
}
const STORIES_ROOT = path.join(__dirname, 'stories');
// ensure stories dir exists
if (!fs.existsSync(STORIES_ROOT)) {
fs.mkdirSync(STORIES_ROOT, { recursive: true });
}
// serve frontend under /write
app.use('/write', express.static(path.join(__dirname, 'public')));
// Public listing at / showing published stories (no authentication required).
// This scans each user's folder for a published/<story>.md file and lists available published stories.
app.get('/', (req, res) => {
try {
const published = [];
const users = fs.readdirSync(STORIES_ROOT, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name);
for (const u of users) {
const userPath = path.join(STORIES_ROOT, u);
// skip non-directories or special files
try {
const stories = fs.readdirSync(userPath, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name);
for (const s of stories) {
const pubPath = path.join(userPath, s, 'published', `${safeName(s)}.md`);
if (fs.existsSync(pubPath)) {
published.push({ user: u, story: s, url: `/published/${encodeURIComponent(u)}/${encodeURIComponent(s)}` });
}
}
} catch (e) {
// ignore user folder read errors and continue with others
}
}
let html = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Published stories</title><style>body{font-family:Arial,Helvetica,sans-serif;max-width:900px;margin:32px auto;padding:0 16px}h1{margin-top:0}ul{line-height:1.6}.write-btn{display:inline-block;margin:8px 0;padding:8px 12px;background:#2b7cff;color:#fff;border-radius:6px;text-decoration:none}</style></head><body>';
html += '<h1>Published stories</h1><p><a href="/write" class="write-btn">Write</a></p>';
if (published.length === 0) {
html += '<p>No published stories yet.</p>';
} else {
html += '<ul>';
for (const p of published) {
html += `<li><strong>${p.user}</strong> — <a href="${p.url}">${p.story}</a></li>`;
}
html += '</ul>';
}
// compute a small mobile-only footer (Local Mode or logout when authenticated)
let footerHtmlRoot = '';
try {
const isLocal = LOCAL_MODE;
const isAuth = !!(req && req.oidc && req.oidc.isAuthenticated && req.oidc.isAuthenticated());
if (isLocal) {
footerHtmlRoot = '<div id="mobileFooter" role="contentinfo" aria-hidden="false" style="color:#b71c1c;font-weight:700">Local Mode</div>';
} else if (isAuth) {
footerHtmlRoot = '<div id="mobileFooter" role="contentinfo" aria-hidden="false"><a href="/logout" style="color:inherit;text-decoration:none">Log out</a></div>';
}
} catch (e) {
footerHtmlRoot = '';
}
// minimal mobile-only styles (appears only on small viewports)
const mobileFooterStyles = '<style>@media (max-width:640px){#mobileFooter{position:fixed;left:0;right:0;bottom:0;z-index:99999;display:flex;justify-content:center;align-items:center;padding:10px;background:#fff;border-top:1px solid rgba(0,0,0,0.06);box-shadow:0 -6px 18px rgba(0,0,0,0.08);font-weight:700}#mobileFooter a{color:#111-decoration:none}}@media (min-width:641px){#mobileFooter{display:none !important}}</style>';
html += (mobileFooterStyles + (footerHtmlRoot || '')) + '</body></html>';
res.send(html);
} catch (err) {
res.status(500).send('failed to generate published list');
}
});
// requireAuth middleware: protect API routes server-side
// In LOCAL_MODE we allow requests and stub a minimal req.oidc so downstream code can
// rely on req.oidc.user / req.oidc.isAuthenticated() without additional checks.
function requireAuth(req, res, next) {
try {
if (LOCAL_MODE) {
// ensure a minimal req.oidc shape so resolveUserIdFromReq and other helpers work.
req.oidc = req.oidc || {};
req.oidc.isAuthenticated = () => true;
req.oidc.user = req.oidc.user || { name: 'localuser', nickname: 'localuser', email: null, email_verified: true };
return next();
}
if (req && req.oidc && req.oidc.isAuthenticated && req.oidc.isAuthenticated()) {
return next();
}
return res.status(401).json({ ok: false, error: 'Authentication required' });
} catch (e) {
return res.status(401).json({ ok: false, error: 'Authentication required' });
}
}
// public endpoint returning auth status for the current browser session
app.get('/api/auth-status', (req, res) => {
try {
// If running in local mode (no .env), return a simulated authenticated user.
if (LOCAL_MODE) {
return res.json({
ok: true,
authenticated: true,
localMode: true,
user: {
name: 'localuser',
nickname: 'localuser',
email: null,
email_verified: true
},
loginUrl: null,
logoutUrl: null
});
}
const isAuth = !!(req && req.oidc && req.oidc.isAuthenticated && req.oidc.isAuthenticated());
const user = isAuth && req.oidc && req.oidc.user ? {
name: req.oidc.user.name || null,
nickname: req.oidc.user.nickname || null,
email: req.oidc.user.email || null,
// normalize to boolean (may be undefined)
email_verified: !!req.oidc.user.email_verified
} : null;
res.json({
ok: true,
authenticated: isAuth,
user,
loginUrl: '/login',
logoutUrl: '/logout'
});
} catch (e) {
res.status(500).json({ ok: false, error: 'failed to determine auth status' });
}
});
// profile endpoint — requires authentication and returns the OIDC user profile
app.get('/profile', requireAuth, (req, res) => {
try {
return res.json(req.oidc && req.oidc.user ? req.oidc.user : {});
} catch (e) {
return res.status(500).json({ ok: false, error: 'failed to read profile' });
}
});
// serve story images via guarded route (do NOT expose STORIES_ROOT directly).
// This endpoint replaces the previous app.use('/stories', ...) static mount so we can
// enforce "published-or-owner" access control for any file under /stories/...
//
// Example incoming paths this handler will accept:
// - /stories/<userId>/<storyId>/images/<sub>/<file>
// - /stories/<userId>/<storyId>/published/<name>.md
// - any other path under /stories/... that maps to STORIES_ROOT/<...>
//
// The handler works by resolving the requested path under STORIES_ROOT, ensuring
// it is inside that directory, then deciding access based on:
// - published file exists (public)
// - or authenticated request and requester resolves to the same userId (owner)
//
function isPublished(userId, storyId) {
try {
if (!userId || !storyId) return false;
const pubPath = path.join(STORIES_ROOT, userId, safeName(storyId), 'published', `${safeName(storyId)}.md`);
return fs.existsSync(pubPath);
} catch (e) { return false; }
}
function canAccessPublishedOrOwner(req, userId, storyId) {
// published content is public
try {
if (isPublished(userId, storyId)) return true;
// otherwise require authenticated owner
if (req && req.oidc && req.oidc.isAuthenticated && req.oidc.isAuthenticated()) {
// resolve auth userId (may create user folder if not present - acceptable here)
try {
const auth = resolveUserIdFromReq(req);
if (auth && auth.userId && userId && auth.userId === userId) return true;
} catch (e) {
return false;
}
}
} catch (e) { /* fall through */ }
return false;
}
app.get('/stories/*', (req, res) => {
try {
// Allow unrestricted access in LOCAL_MODE to simplify local development (images and published pages).
// In production (LOCAL_MODE === false) the original access checks below still apply.
if (LOCAL_MODE) {
// req.params[0] contains the wildcard path after /stories/
const rel = req.params[0] || '';
// normalize and prevent path traversal
const normalized = path.normalize(rel).replace(/^(\.\.(\/|\\|$))+/, '');
const full = path.join(STORIES_ROOT, normalized);
// ensure resolved path is inside STORIES_ROOT
const rootResolved = path.resolve(STORIES_ROOT) + path.sep;
const fullResolved = path.resolve(full);
if (!fullResolved.startsWith(rootResolved)) return res.status(404).send('not found');
if (!fs.existsSync(fullResolved)) return res.status(404).send('not found');
return res.sendFile(fullResolved);
}
// req.params[0] contains the wildcard path after /stories/
const rel = req.params[0] || '';
// normalize and prevent path traversal
const normalized = path.normalize(rel).replace(/^(\.\.(\/|\\|$))+/, '');
const full = path.join(STORIES_ROOT, normalized);
// ensure resolved path is inside STORIES_ROOT
const rootResolved = path.resolve(STORIES_ROOT) + path.sep;
const fullResolved = path.resolve(full);
if (!fullResolved.startsWith(rootResolved)) return res.status(404).send('not found');
if (!fs.existsSync(fullResolved)) return res.status(404).send('not found');
// Determine probable userId and storyId from the path segments if available:
const parts = normalized.split(path.sep).filter(Boolean);
const userId = parts.length >= 1 ? parts[0] : null;
const storyId = parts.length >= 2 ? parts[1] : null;
// If we can determine a userId/storyId, enforce published-or-owner.
// If not (edge cases), be conservative and deny access unless file is in a published folder.
if (userId && storyId) {
if (!canAccessPublishedOrOwner(req, userId, storyId)) return res.status(403).send('forbidden');
} else {
// fallback: if file path contains "/published/" allow, else deny
if (!normalized.includes(path.join('published', '/'))) {
return res.status(403).send('forbidden');
}
}
return res.sendFile(fullResolved);
} catch (e) {
return res.status(500).send('error');
}
});
function safeName(name) {
// very simple sanitization: remove path separators
return name.replace(/[/\\?%*:|"<>]/g, '-');
}
function storyPath(name) {
return path.join(STORIES_ROOT, safeName(name));
}
// Helper to escape HTML for safe embedding in server-rendered pages
function escapeHtml(s) {
return String(s || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
// Typographic transforms helper (server-side):
// - "..." -> …
// - "--" -> —
// - straight double quotes " -> smart quotes “ ” (simple alternating heuristic)
// Skips <code>...</code> spans by temporarily replacing them with placeholders.
function typographicTransform(s) {
if (!s || typeof s !== 'string') return s;
const placeholders = [];
s = s.replace(/<code>[\s\S]*?<\/code>/g, (m) => {
const key = `__CODE_PLACEHOLDER_${placeholders.length}__`;
placeholders.push(m);
return key;
});
// ellipses
s = s.replace(/\.{3}/g, '…');
// em-dash
s = s.replace(/--/g, '—');
// smart double quotes (toggle heuristic)
let out = '';
let open = true;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (ch === '"') {
out += open ? '“' : '”';
open = !open;
} else {
out += ch;
}
}
s = out;
// restore code placeholders
s = s.replace(/__CODE_PLACEHOLDER_(\d+)__/g, (_m, idx) => placeholders[Number(idx)] || '');
return s;
}
function ensureStoryStructure(name) {
const base = storyPath(name);
if (!fs.existsSync(base)) {
fs.mkdirSync(base, { recursive: true });
}
// Create a minimal project.json for explicit metadata (helps future features)
const projectMetaPath = path.join(base, 'project.json');
if (!fs.existsSync(projectMetaPath)) {
try {
const meta = { name: name, createdAt: new Date().toISOString(), version: 1 };
fs.writeFileSync(projectMetaPath, JSON.stringify(meta, null, 2), 'utf8');
} catch (e) {
// ignore write errors here; higher-level handlers will surface problems
}
}
// ensure highlights directory exists (per-highlight markdown files)
const highlightsDir = path.join(base, 'highlights');
if (!fs.existsSync(highlightsDir)) {
fs.mkdirSync(highlightsDir, { recursive: true });
}
// create images subfolders (only highlights now)
const imgs = path.join(base, 'images');
const imgSub = ['highlights'];
for (const s of imgSub) {
const p = path.join(imgs, s);
if (!fs.existsSync(p)) {
fs.mkdirSync(p, { recursive: true });
}
}
// create tiles folder and minimal tiles.json (ordered array of {id,title})
const tilesDir = path.join(base, 'tiles');
if (!fs.existsSync(tilesDir)) {
fs.mkdirSync(tilesDir, { recursive: true });
}
const tilesMeta = path.join(tilesDir, 'tiles.json');
if (!fs.existsSync(tilesMeta)) {
try {
fs.writeFileSync(tilesMeta, JSON.stringify([], null, 2), 'utf8');
} catch (e) {
// ignore write errors here; higher-level handlers will surface problems
}
}
}
/**
* Helpers for per-user storage and usage
*/
function nicknameFromEmail(email) {
if (!email) return null;
const local = String(email).split('@')[0] || email;
return safeName(local);
}
function shortHash(email) {
return crypto.createHash('sha256').update(String(email)).digest('hex').slice(0, 8);
}
function resolveUserIdFromReq(req) {
// In local mode, map all requests to the 'localuser' account.
if (LOCAL_MODE) {
const nick = 'localuser';
const baseCandidate = path.join(STORIES_ROOT, nick);
if (!fs.existsSync(baseCandidate)) {
fs.mkdirSync(baseCandidate, { recursive: true });
const meta = { name: 'localuser', createdAt: new Date().toISOString() };
try { fs.writeFileSync(path.join(baseCandidate, 'user.json'), JSON.stringify(meta, null, 2), 'utf8'); } catch (e) {}
}
return { userId: nick, userPath: baseCandidate };
}
if (!req || !req.oidc || !req.oidc.user || !req.oidc.user.email) {
throw new Error('authenticated user email required');
}
const email = String(req.oidc.user.email).toLowerCase();
const nick = nicknameFromEmail(email) || safeName(email);
const baseCandidate = path.join(STORIES_ROOT, nick);
if (!fs.existsSync(baseCandidate)) {
fs.mkdirSync(baseCandidate, { recursive: true });
const meta = { email, name: req.oidc.user.nickname || req.oidc.user.name || null, createdAt: new Date().toISOString() };
try { fs.writeFileSync(path.join(baseCandidate, 'user.json'), JSON.stringify(meta, null, 2), 'utf8'); } catch (e) {}
return { userId: nick, userPath: baseCandidate };
}
const metaPath = path.join(baseCandidate, 'user.json');
if (fs.existsSync(metaPath)) {
try {
const m = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '{}');
if (m.email && String(m.email).toLowerCase() === email) {
return { userId: nick, userPath: baseCandidate };
}
// collision => create suffixed folder
const newId = `${nick}__${shortHash(email)}`;
const newPath = path.join(STORIES_ROOT, newId);
if (!fs.existsSync(newPath)) fs.mkdirSync(newPath, { recursive: true });
const meta = { email, name: req.oidc.user.nickname || req.oidc.user.name || null, createdAt: new Date().toISOString() };
try { fs.writeFileSync(path.join(newPath, 'user.json'), JSON.stringify(meta, null, 2), 'utf8'); } catch (e) {}
return { userId: newId, userPath: newPath };
} catch (e) {
const newId = `${nick}__${shortHash(email)}`;
const newPath = path.join(STORIES_ROOT, newId);
if (!fs.existsSync(newPath)) fs.mkdirSync(newPath, { recursive: true });
const meta = { email, name: req.oidc.user.nickname || req.oidc.user.name || null, createdAt: new Date().toISOString() };
try { fs.writeFileSync(path.join(newPath, 'user.json'), JSON.stringify(meta, null, 2), 'utf8'); } catch (e2) {}
return { userId: newId, userPath: newPath };
}
} else {
const newId = `${nick}__${shortHash(email)}`;
const newPath = path.join(STORIES_ROOT, newId);
if (!fs.existsSync(newPath)) fs.mkdirSync(newPath, { recursive: true });
const meta = { email, name: req.oidc.user.nickname || req.oidc.user.name || null, createdAt: new Date().toISOString() };
try { fs.writeFileSync(path.join(newPath, 'user.json'), JSON.stringify(meta, null, 2), 'utf8'); } catch (e) {}
return { userId: newId, userPath: newPath };
}
}
function resolveUserAndBase(req, storyName) {
const { userId, userPath } = resolveUserIdFromReq(req);
const base = path.join(userPath, safeName(storyName));
return { userId, base, userPath };
}
// Flexible resolver: supports either the current authenticated user's stories
// (default behavior) or an explicit user-prefixed name like "userId/storyName".
// This helps when the frontend or direct requests sometimes pass "user/story".
function resolveBaseFlexible(req, storyName) {
if (!storyName || typeof storyName !== 'string') {
return resolveUserAndBase(req, storyName);
}
// If the caller provided an explicit user prefix (userId/story), honor it.
// Use the first path segment as userId and the rest as the story name.
if (storyName.indexOf('/') !== -1) {
const parts = storyName.split('/');
const userId = parts.shift();
const name = parts.join('/');
const base = path.join(STORIES_ROOT, userId, safeName(name));
const userPath = path.join(STORIES_ROOT, userId);
return { userId, base, userPath };
}
// Fallback to resolving from the authenticated user
return resolveUserAndBase(req, storyName);
}
function ensureUserStoryStructure(userPath, storyName) {
const base = path.join(userPath, safeName(storyName));
if (!fs.existsSync(base)) {
fs.mkdirSync(base, { recursive: true });
}
// ensure highlights directory exists (per-highlight markdown files)
const highlightsDir = path.join(base, 'highlights');
if (!fs.existsSync(highlightsDir)) {
fs.mkdirSync(highlightsDir, { recursive: true });
}
const imgs = path.join(base, 'images');
const imgSub = ['highlights'];
for (const s of imgSub) {
const p = path.join(imgs, s);
if (!fs.existsSync(p)) {
fs.mkdirSync(p, { recursive: true });
}
}
const tilesDir = path.join(base, 'tiles');
if (!fs.existsSync(tilesDir)) {
fs.mkdirSync(tilesDir, { recursive: true });
}
const tilesMeta = path.join(tilesDir, 'tiles.json');
if (!fs.existsSync(tilesMeta)) {
try {
fs.writeFileSync(tilesMeta, JSON.stringify([], null, 2), 'utf8');
} catch (e) {
// ignore
}
}
}
// compute total bytes used by a user's folder (recursively)
function getUserUsageBytes(userId) {
const userPath = path.join(STORIES_ROOT, userId);
let total = 0;
if (!fs.existsSync(userPath)) return 0;
const walk = (p) => {
for (const ent of fs.readdirSync(p, { withFileTypes: true })) {
const cur = path.join(p, ent.name);
if (ent.isDirectory()) walk(cur);
else {
try { total += fs.statSync(cur).size; } catch (e) {}
}
}
};
walk(userPath);
return total;
}
app.get('/api/stories', requireAuth, (req, res) => {
try {
const { userId, userPath } = resolveUserIdFromReq(req);
const items = fs.readdirSync(userPath, { withFileTypes: true })
.filter(d => d.isDirectory())
.map(d => ({ id: d.name, name: d.name }));
res.json({ ok: true, stories: items });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
// Create story
app.post('/api/stories', requireAuth, (req, res) => {
const { name } = req.body || {};
if (!name) return res.status(400).json({ ok: false, error: 'name is required' });
const nm = safeName(name);
try {
const { userId, userPath } = resolveUserIdFromReq(req);
const base = path.join(userPath, nm);
if (fs.existsSync(base)) {
return res.status(409).json({ ok: false, error: 'story already exists' });
}
ensureUserStoryStructure(userPath, nm);
res.json({ ok: true, id: nm, name: nm });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
// Rename story
app.post('/api/stories/:name/rename', requireAuth, (req, res) => {
const oldName = req.params.name;
const { newName } = req.body || {};
if (!newName) return res.status(400).json({ ok: false, error: 'newName is required' });
try {
// Resolve the story base and the owning user path (supports explicit "user/story" or implicit current user).
const { userId, base, userPath } = resolveBaseFlexible(req, oldName);
if (!base || !fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
const oldSafe = path.basename(base);
const newSafe = safeName(newName);
const to = path.join(userPath, newSafe);
if (fs.existsSync(to)) return res.status(409).json({ ok: false, error: 'target name already exists' });
// Perform the filesystem rename (move the entire story directory)
fs.renameSync(base, to);
// If a project.json exists, update its name to reflect the new title.
try {
const projPath = path.join(to, 'project.json');
if (fs.existsSync(projPath)) {
const pm = JSON.parse(fs.readFileSync(projPath, 'utf8') || '{}');
pm.name = newName;
fs.writeFileSync(projPath, JSON.stringify(pm, null, 2), 'utf8');
}
} catch (e) {
// non-fatal: continue even if project.json update fails
}
// After moving, if a published markdown exists named with the old safe name,
// rename it to use the new safe name so the public route remains consistent.
try {
const oldPub = path.join(to, 'published', `${oldSafe}.md`);
const newPub = path.join(to, 'published', `${newSafe}.md`);
if (fs.existsSync(oldPub) && !fs.existsSync(newPub)) {
fs.renameSync(oldPub, newPub);
}
} catch (e) {
// non-fatal: do not abort rename on publish-file rename failure
}
return res.json({ ok: true, name: newName });
} catch (err) {
return res.status(500).json({ ok: false, error: err.message });
}
});
// Get story content (characters, locations) and image lists
app.get('/api/stories/:name', requireAuth, (req, res) => {
const name = req.params.name;
const { userId, base } = resolveBaseFlexible(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
try {
// Aggregate per-highlight files from the highlights/ directory (no more highlights.md)
const highlightsDir = path.join(base, 'highlights');
let highlights = '';
if (fs.existsSync(highlightsDir)) {
// read files in stable order (by mtime then name) to produce consistent concatenation
const files = fs.readdirSync(highlightsDir, { withFileTypes: true })
.filter(d => d.isFile() && d.name.endsWith('.md'))
.map(d => d.name);
// sort files by name for determinism
files.sort();
for (const fn of files) {
try {
const fp = path.join(highlightsDir, fn);
const txt = fs.readFileSync(fp, 'utf8') || '';
// ensure sections are separated by blank lines
highlights += (highlights ? '\n\n' : '') + txt.trim();
} catch (e) {
// ignore individual highlight read errors
}
}
} else {
highlights = '';
}
const imagesDir = path.join(base, 'images');
let imageList = [];
if (fs.existsSync(imagesDir)) {
imageList = fs.readdirSync(imagesDir, { withFileTypes: true })
.filter(d => d.isFile())
.map(d => '/' + ['stories', encodeURIComponent(userId), encodeURIComponent(safeName(name)), 'images', encodeURIComponent(d.name)].join('/'));
}
res.json({ ok: true, name, highlights, images: imageList });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
/*
Highlights API - per-highlight markdown files stored under:
stories/<userId>/<story>/highlights/<id>.md
Endpoints:
GET /api/stories/:name/highlights -> list highlights
GET /api/stories/:name/highlights/:id -> get highlight content
POST /api/stories/:name/highlights -> create highlight { title, content }
POST /api/stories/:name/highlights/:id/save -> save content { content }
POST /api/stories/:name/highlights/:id/rename -> rename { newName }
DELETE /api/stories/:name/highlights/:id -> delete highlight
*/
app.get('/api/stories/:name/highlights', requireAuth, (req, res) => {
const name = req.params.name;
try {
const { userId, base } = resolveBaseFlexible(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
const dir = path.join(base, 'highlights');
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const metaPath = path.join(dir, 'highlights.json');
// If highlights.json missing, return empty list per spec (no backwards compatibility)
if (!fs.existsSync(metaPath)) return res.json({ ok: true, highlights: [] });
let meta = [];
try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]'); } catch (e) { meta = []; }
// enrich with mtime if file present
const list = meta.map(item => {
const fp = path.join(dir, item.id + '.md');
let mtime = 0;
try { mtime = fs.existsSync(fp) ? fs.statSync(fp).mtimeMs || 0 : 0; } catch (e) { mtime = 0; }
return { id: item.id, title: item.title, mtime };
});
res.json({ ok: true, highlights: list });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
app.get('/api/stories/:name/highlights/:id', requireAuth, (req, res) => {
const name = req.params.name;
const id = req.params.id;
try {
const { userId, base } = resolveBaseFlexible(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
const dir = path.join(base, 'highlights');
const metaPath = path.join(dir, 'highlights.json');
if (!fs.existsSync(metaPath)) return res.status(404).json({ ok: false, error: 'highlights metadata not found' });
let meta = [];
try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]'); } catch (e) { meta = []; }
const entry = meta.find(m => m.id === id);
if (!entry) return res.status(404).json({ ok: false, error: 'highlight not found' });
const filename = path.join(dir, id + '.md');
let content = '';
if (fs.existsSync(filename)) {
try { content = fs.readFileSync(filename, 'utf8'); } catch (e) { content = ''; }
}
res.json({ ok: true, id, title: entry.title, content });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
app.post('/api/stories/:name/highlights', requireAuth, (req, res) => {
const name = req.params.name;
const { title, content } = req.body || {};
if (!title) return res.status(400).json({ ok: false, error: 'title is required' });
try {
const { userId, base } = resolveBaseFlexible(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
const dir = path.join(base, 'highlights');
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const metaPath = path.join(dir, 'highlights.json');
let meta = [];
try { meta = fs.existsSync(metaPath) ? JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]') : []; } catch (e) { meta = []; }
// Prevent creating a highlight with a title that already exists (case-insensitive, trimmed)
const normalizedTitle = String(title || '').trim().toLowerCase();
if (normalizedTitle.length > 0) {
const dup = meta.find(m => m && m.title && String(m.title).trim().toLowerCase() === normalizedTitle);
if (dup) {
return res.status(409).json({ ok: false, error: 'another highlight with that name already exists' });
}
}
let id = safeName(title) || String(Date.now());
// ensure uniqueness within meta
let candidate = id;
let suffix = 1;
while (meta.find(m => m.id === candidate)) {
candidate = `${id}-${suffix++}`;
}
id = candidate;
// write file (empty by default if no content provided)
const out = (typeof content === 'string') ? content : '';
fs.writeFileSync(path.join(dir, id + '.md'), out, 'utf8');
// append to highlights.json
const now = Date.now();
meta.push({ id, title, mtime: now });
try { fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf8'); } catch (e) {}
res.json({ ok: true, id, title });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
app.post('/api/stories/:name/highlights/:id/save', requireAuth, (req, res) => {
const name = req.params.name;
const id = req.params.id;
const { content } = req.body || {};
if (typeof content !== 'string') return res.status(400).json({ ok: false, error: 'content required' });
try {
const { userId, base } = resolveBaseFlexible(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
const dir = path.join(base, 'highlights');
const metaPath = path.join(dir, 'highlights.json');
if (!fs.existsSync(metaPath)) return res.status(404).json({ ok: false, error: 'highlights metadata not found' });
let meta = [];
try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]'); } catch (e) { meta = []; }
const entry = meta.find(m => m.id === id);
if (!entry) return res.status(404).json({ ok: false, error: 'highlight not found' });
const filename = path.join(dir, id + '.md');
fs.writeFileSync(filename, content, 'utf8');
res.json({ ok: true });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
/**
* Rename highlight title and optional propagation (search & replace).
*
* New endpoints:
* - GET /api/stories/:name/highlights/:id/rename-preview?newName=...
* -> returns a dry-run preview of matches in tiles/*.md and highlights/*.md
* - POST /api/stories/:name/highlights/:id/rename
* body: { newName, propagate: true|false }
* -> updates highlights.json title and, if propagate, replaces whole-word case-sensitive matches
* in tiles/*.md and highlights/*.md (NOT reversible).
*/
app.get('/api/stories/:name/highlights/:id/rename-preview', requireAuth, (req, res) => {
const name = req.params.name;
const id = req.params.id;
const newName = req.query.newName;
if (!newName) return res.status(400).json({ ok: false, error: 'newName query param required' });
try {
const { userId, base } = resolveBaseFlexible(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
const dir = path.join(base, 'highlights');
const metaPath = path.join(dir, 'highlights.json');
if (!fs.existsSync(metaPath)) return res.status(404).json({ ok: false, error: 'highlights metadata not found' });
let meta = [];
try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]'); } catch (e) { meta = []; }
// Prevent duplicate highlight titles on rename (case-insensitive, trimmed).
const normalizedNew = String(newName || '').trim().toLowerCase();
if (normalizedNew.length > 0) {
const duplicate = meta.find(m =>
m && m.id && m.title &&
m.id !== id && String(m.title).trim().toLowerCase() === normalizedNew
);
if (duplicate) {
return res.status(409).json({ ok: false, error: 'another highlight with that name already exists' });
}
}
const entry = meta.find(m => m.id === id);
if (!entry) return res.status(404).json({ ok: false, error: 'highlight not found' });
const oldName = entry.title || id;
// build whole-word, case-sensitive regex using escaped oldName
const escapeForRegex = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`\\b${escapeForRegex(oldName)}\\b`, 'g');
const scanDirs = ['tiles', 'highlights'];
const filesResult = [];
let totalMatches = 0;
for (const sub of scanDirs) {
const p = path.join(base, sub);
if (!fs.existsSync(p)) continue;
const ents = fs.readdirSync(p, { withFileTypes: true }).filter(d => d.isFile() && d.name.endsWith('.md')).map(d => d.name);
for (const fn of ents) {
const fp = path.join(p, fn);
let txt = '';
try { txt = fs.readFileSync(fp, 'utf8') || ''; } catch (e) { continue; }
const lines = String(txt).split(/\r?\n/);
const matches = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const m = line.match(re);
if (m && m.length) {
totalMatches += m.length;
// capture a snippet with context
const snippet = line.trim().slice(0, 240);
matches.push({ line: i + 1, snippet, count: m.length });
}
}
if (matches.length) {
filesResult.push({ path: path.relative(base, fp), matches });
}
}
}
return res.json({ ok: true, totalMatches, files: filesResult });
} catch (err) {
return res.status(500).json({ ok: false, error: err.message });
}
});
app.post('/api/stories/:name/highlights/:id/rename', requireAuth, (req, res) => {
const name = req.params.name;
const id = req.params.id;
const { newName, propagate } = req.body || {};
if (!newName) return res.status(400).json({ ok: false, error: 'newName is required' });
try {
const { userId, base } = resolveBaseFlexible(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
const dir = path.join(base, 'highlights');
const metaPath = path.join(dir, 'highlights.json');
if (!fs.existsSync(metaPath)) return res.status(404).json({ ok: false, error: 'highlights metadata not found' });
let meta = [];
try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]'); } catch (e) { meta = []; }
const entry = meta.find(m => m.id === id);
if (!entry) return res.status(404).json({ ok: false, error: 'highlight not found' });
const oldName = entry.title || id;
// Update metadata title first (authoritative)
entry.title = newName;
entry.mtime = Date.now();
try { fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf8'); } catch (e) {}
// If propagate requested, perform whole-word, case-sensitive replacements in tiles/*.md and highlights/*.md
const resultSummary = { totalReplacements: 0, filesChanged: [] };
if (propagate) {
const escapeForRegex = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`\\b${escapeForRegex(oldName)}\\b`, 'g'); // case-sensitive, whole-word
const scanDirs = ['tiles', 'highlights'];
for (const sub of scanDirs) {
const p = path.join(base, sub);
if (!fs.existsSync(p)) continue;
const ents = fs.readdirSync(p, { withFileTypes: true }).filter(d => d.isFile() && d.name.endsWith('.md')).map(d => d.name);
for (const fn of ents) {
const fp = path.join(p, fn);
let txt = '';
try { txt = fs.readFileSync(fp, 'utf8') || ''; } catch (e) { continue; }
const matches = txt.match(re);
if (!matches || matches.length === 0) continue;
const replacements = matches.length;
const newTxt = txt.replace(re, newName);
// atomic write
try {
const tmp = fp + '.tmp';
fs.writeFileSync(tmp, newTxt, 'utf8');
fs.renameSync(tmp, fp);
resultSummary.totalReplacements += replacements;
resultSummary.filesChanged.push({ path: path.relative(base, fp), replacements });
} catch (e) {
// on failure, abort and return error to avoid partial silent corruption
return res.status(500).json({ ok: false, error: 'failed to write updated file: ' + fp });
}
}
}
}
return res.json({ ok: true, id, title: newName, propagate: !!propagate, summary: resultSummary });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
app.delete('/api/stories/:name/highlights/:id', requireAuth, (req, res) => {
const name = req.params.name;
const id = req.params.id;
try {
const { userId, base } = resolveBaseFlexible(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
const dir = path.join(base, 'highlights');
const metaPath = path.join(dir, 'highlights.json');
if (!fs.existsSync(metaPath)) return res.status(404).json({ ok: false, error: 'highlights metadata not found' });
let meta = [];
try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]'); } catch (e) { meta = []; }
const idx = meta.findIndex(m => m.id === id);
if (idx !== -1) meta.splice(idx, 1);
try { fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf8'); } catch (e) {}
const filename = path.join(dir, id + '.md');
if (fs.existsSync(filename)) fs.unlinkSync(filename);
res.json({ ok: true });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
// Tiles API: minimal per-story tile storage (stories/<name>/tiles/, stories/<name>/tiles/tiles.json)
app.get('/api/stories/:name/tiles', requireAuth, (req, res) => {
const name = req.params.name;
const { userId, base } = resolveUserAndBase(req, name);
if (!fs.existsSync(base)) return res.status(404).json({ ok: false, error: 'story not found' });
try {
const tilesDir = path.join(base, 'tiles');
const metaPath = path.join(tilesDir, 'tiles.json');
let tiles = [];
if (fs.existsSync(metaPath)) {
try { tiles = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]'); } catch (e) { tiles = []; }
}
res.json({ ok: true, tiles });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
// Create a new tile
app.post('/api/stories/:name/tiles', requireAuth, (req, res) => {
const name = req.params.name;
const { title, content } = req.body || {};
const { userId, base, userPath } = resolveBaseFlexible(req, name);
// ensure story exists (create structure if missing) so tile creation works reliably
if (!fs.existsSync(base)) {
try {
ensureUserStoryStructure(userPath, name);
} catch (e) {
return res.status(500).json({ ok: false, error: 'failed to create story structure' });
}
}
try {
const tilesDir = path.join(base, 'tiles');
if (!fs.existsSync(tilesDir)) fs.mkdirSync(tilesDir, { recursive: true });
const metaPath = path.join(tilesDir, 'tiles.json');
let tiles = [];
if (fs.existsSync(metaPath)) {
try { tiles = JSON.parse(fs.readFileSync(metaPath, 'utf8') || '[]'); } catch (e) { tiles = []; }
}
const id = String(Date.now()) + '-' + Math.floor(Math.random() * 10000);
const safeId = safeName(id);