-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
3782 lines (3363 loc) · 141 KB
/
Copy pathserver.ts
File metadata and controls
3782 lines (3363 loc) · 141 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
import express from "express";
import path from "path";
import fs from "fs";
import { createServer as createViteServer } from "vite";
import { GoogleGenAI, Type } from "@google/genai";
import dotenv from "dotenv";
import { initializeApp } from "firebase/app";
import { initializeFirestore, collection, getDocs, doc, setDoc, deleteDoc } from "firebase/firestore";
import nodemailer from "nodemailer";
import { MicroserviceRegistry } from "./src/services/MicroserviceRegistry";
import { extractArxivId, cleanJsonText, generateSlug, parseArxivXml, parseArxivFeedXml, extractSvgString } from "./src/lib/arxivUtils";
import { generateProceduralBannerSvg } from "./src/lib/svgBannerGenerator";
import { generateScientificArticleFromArxiv } from "./src/lib/paperGenerationEngine";
import { auditArticleAgainstArxiv, auditCatalogUniqueness } from "./src/lib/arxivAuditor";
import {
buildLinkedInSystemInstruction,
buildLinkedInUserPrompt,
generateFallbackLinkedInPost,
sanitizeHashtags
} from "./src/lib/linkedinUtils";
import {
buildXSystemInstruction,
buildXUserPrompt,
generateFallbackXPost,
sanitizeHashtags as sanitizeXHashtags
} from "./src/lib/xUtils";
import {
syncAllBlogsToGitHub,
testGitHubConnection,
getGitHubSyncConfig,
writeLocalBlogFiles,
generateDataTsContent
} from "./src/lib/githubSync";
import {
resolveBlogSlugOrId,
normalizeSlug,
stripSlugTimestampSuffix
} from "./src/lib/slugResolver";
import {
postTweetToX,
testXConnection,
executeTestTweet
} from "./src/lib/xApi";
import {
getArtTime
} from "./src/lib/dailyEditorialEngine";
import {
persistMultiTierBlogs,
appendGenerationJournal,
readPipelineRecords,
createBlogSnapshot
} from "./src/lib/persistenceManager";
import {
createPipelineTracker,
recordStepProgress,
finalizePipelineSuccess,
finalizePipelineFailure,
estimateTokens
} from "./src/lib/pipelineAuditor";
import { PipelineExecutionRecord } from "./src/types";
import {
PortalTokenData,
PasskeyRecord,
AuthSessionRecord,
DeviceFingerprint,
PasskeyAuditEvent,
validatePasskeyCredential,
generatePortalToken,
cleanExpiredTokens,
verifyPortalToken,
pollAuthToken,
validateRegistrationToken,
verifyRegistrationPassword,
authenticatePasskeyCredential,
registerNewPasskey,
syncPasskeyCollections,
createAuthSession,
validateAndRestoreSession,
touchSessionActivity,
revokeAuthSession,
cleanExpiredSessions,
createPasskeyAuditEvent,
appendPasskeyAuditRecord,
readPasskeyAuditRecords,
extractClientFingerprint,
generateSecureChallenge
} from "./src/lib/passkeyManager";
import {
fetchLiveBinanceTickers,
fetchLiveBinanceDepth,
fetchLiveBinanceKlines,
fetchBinanceAccountInfo,
fetchBinanceOpenOrders,
executeBinanceTestOrder,
previewOrder,
getPublicDonationAddresses,
DEFAULT_TRACKED_SYMBOLS,
DEFAULT_SYMBOL_RULES,
} from "./src/lib/binanceManager";
dotenv.config();
const app = express();
const PORT = 3000;
// Domain Canonical Redirection Middleware (Redirects generic Cloud Run host to custom domain ask-meridian.uk)
app.use((req, res, next) => {
const host = (req.headers["x-forwarded-host"] || req.headers.host || "").toString().toLowerCase();
// Exclude local development and AI Studio preview containers
const isAiStudioPreview = host.startsWith("ais-dev-") || host.startsWith("ais-pre-") || host.includes("localhost") || host.includes("127.0.0.1");
if (!isAiStudioPreview && (host.includes("meridian-blog-620868709178.us-west1.run.app") || (host.endsWith(".run.app") && !host.includes("ais-")))) {
const targetUrl = `https://ask-meridian.uk${req.originalUrl}`;
console.log(`[Redirect] 301 Permanent Redirect from ${host}${req.originalUrl} -> ${targetUrl}`);
return res.redirect(301, targetUrl);
}
next();
});
// Google AdSense Authorized Digital Sellers (ads.txt) Verification Endpoint
app.get("/ads.txt", (req, res) => {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Cache-Control", "public, max-age=3600");
res.send("google.com, pub-7734562716191044, DIRECT, f08c47fec0942fa0\n");
});
// Search Engine Optimization (robots.txt) Endpoint
app.get("/robots.txt", (req, res) => {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Cache-Control", "public, max-age=86400");
const robotsPath = path.join(process.cwd(), "public", "robots.txt");
if (fs.existsSync(robotsPath)) {
res.send(fs.readFileSync(robotsPath, "utf-8"));
} else {
res.send("User-agent: *\nAllow: /\nDisallow: /api/\nSitemap: https://ask-meridian.uk/sitemap.xml\n");
}
});
// Dynamic XML Sitemap Endpoint
app.get("/sitemap.xml", (req, res) => {
res.setHeader("Content-Type", "application/xml; charset=utf-8");
res.setHeader("Cache-Control", "public, max-age=3600");
const sitemapPath = path.join(process.cwd(), "public", "sitemap.xml");
if (fs.existsSync(sitemapPath)) {
res.send(fs.readFileSync(sitemapPath, "utf-8"));
} else {
res.status(404).send("<error>Sitemap not found</error>");
}
});
// GitHub Pages / Jekyll bypass endpoint
app.get("/.nojekyll", (req, res) => {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.send("");
});
// Privacy Policy Serving Endpoints (Serves at https://ask-meridian.uk/privacy-policy)
app.get(["/privacy-policy", "/privacy-policy.html"], (req, res) => {
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.setHeader("Cache-Control", "public, max-age=3600");
const publicPath = path.join(process.cwd(), "public", "privacy-policy.html");
const rootPath = path.join(process.cwd(), "privacy-policy.html");
if (fs.existsSync(publicPath)) {
return res.sendFile(publicPath);
} else if (fs.existsSync(rootPath)) {
return res.sendFile(rootPath);
}
res.status(404).send("Privacy Policy not found");
});
// Terms of Service Serving Endpoints (Serves at https://ask-meridian.uk/terms-of-service)
app.get(["/terms-of-service", "/terms-of-service.html"], (req, res) => {
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.setHeader("Cache-Control", "public, max-age=3600");
const publicPath = path.join(process.cwd(), "public", "terms-of-service.html");
const rootPath = path.join(process.cwd(), "terms-of-service.html");
if (fs.existsSync(publicPath)) {
return res.sendFile(publicPath);
} else if (fs.existsSync(rootPath)) {
return res.sendFile(rootPath);
}
res.status(404).send("Terms of Service not found");
});
// Authorized OAuth Callback URI (Serves at https://ask-meridian.uk/auth/callback)
app.get(["/auth/callback", "/auth/callback.html"], (req, res) => {
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
const publicPath = path.join(process.cwd(), "public", "auth", "callback.html");
const rootPath = path.join(process.cwd(), "auth", "callback.html");
if (fs.existsSync(publicPath)) {
return res.sendFile(publicPath);
} else if (fs.existsSync(rootPath)) {
return res.sendFile(rootPath);
}
res.status(404).send("OAuth callback handler not found");
});
app.use(express.json({ limit: "10mb" }));
// Initialize Google GenAI client safely
const getGeminiClient = () => {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.log("Notice: GEMINI_API_KEY is not defined. Procedural generation fallback will be used.");
}
return new GoogleGenAI({
apiKey: apiKey || "MOCK_KEY",
httpOptions: {
headers: {
"User-Agent": "aistudio-build",
},
},
});
};
// Cached availability check for GitHub Models (Azure AI Inference) endpoint
let isGitHubModelsSupported: boolean | null = null;
async function checkGitHubModelsAvailability(): Promise<boolean> {
if (isGitHubModelsSupported !== null) return isGitHubModelsSupported;
try {
const dns = await import("dns/promises");
await dns.lookup("models.inference.ai.azure.com");
isGitHubModelsSupported = true;
} catch {
isGitHubModelsSupported = false;
}
return isGitHubModelsSupported;
}
// Simple arXiv API fetcher with quick abort timeout
const fetchArxivMetadata = async (id: string) => {
try {
const url = `http://export.arxiv.org/api/query?id_list=${encodeURIComponent(id)}`;
const res = await fetch(url, { signal: AbortSignal.timeout(3500) });
if (!res.ok) throw new Error("Failed to fetch from arXiv API");
const xml = await res.text();
// Extract metadata using robust helper function
const { title, summary, authors } = parseArxivXml(xml);
return { title, summary, authors, arxivLink: `https://arxiv.org/abs/${id}` };
} catch (error) {
console.warn("Notice: arXiv metadata fetch timed out or failed, falling back to direct input parsing:", error);
return null;
}
};
const CUSTOM_BLOGS_FILE = path.join(process.cwd(), "custom_blogs.json");
const readCustomBlogs = (): any[] => {
try {
if (fs.existsSync(CUSTOM_BLOGS_FILE)) {
const data = fs.readFileSync(CUSTOM_BLOGS_FILE, "utf-8");
return JSON.parse(data);
}
} catch (error) {
console.error("Error reading custom_blogs.json:", error);
}
return [];
};
const writeCustomBlogs = (blogs: any[]) => {
try {
fs.writeFileSync(CUSTOM_BLOGS_FILE, JSON.stringify(blogs, null, 2), "utf-8");
} catch (error) {
console.error("Error writing custom_blogs.json:", error);
}
};
const DISPATCHED_EMAILS_FILE = path.join(process.cwd(), "dispatched_emails.json");
const SMTP_CONFIG_FILE = path.join(process.cwd(), "smtp_config.json");
const readDispatchedEmails = (): any[] => {
try {
if (fs.existsSync(DISPATCHED_EMAILS_FILE)) {
const data = fs.readFileSync(DISPATCHED_EMAILS_FILE, "utf-8");
return JSON.parse(data);
}
} catch (error) {
console.error("Error reading dispatched_emails.json:", error);
}
return [];
};
const writeDispatchedEmails = (emails: any[]) => {
try {
fs.writeFileSync(DISPATCHED_EMAILS_FILE, JSON.stringify(emails, null, 2), "utf-8");
} catch (error) {
console.error("Error writing dispatched_emails.json:", error);
}
};
const PASSKEYS_FILE = path.join(process.cwd(), "passkeys.json");
const PASSKEYS_BACKUP_FILE = path.join(process.cwd(), "data", "passkeys_backup.json");
const ACTIVE_SESSIONS_FILE = path.join(process.cwd(), "data", "active_sessions.json");
const logPasskeyAudit = (
eventType: any,
status: "success" | "failure" | "pending" | "info",
options?: {
credentialId?: string;
deviceName?: string;
token?: string;
details?: Record<string, any>;
req?: express.Request;
}
) => {
try {
const ip = (options?.req?.headers["x-forwarded-for"] as string) || options?.req?.socket?.remoteAddress;
const userAgent = (options?.req?.headers["user-agent"] as string);
const event = createPasskeyAuditEvent(eventType, status, {
credentialId: options?.credentialId,
deviceName: options?.deviceName,
token: options?.token,
details: options?.details,
ip,
userAgent
});
appendPasskeyAuditRecord(event, fs);
} catch (err) {
console.error("[PasskeyAudit] Failed to log audit event:", err);
}
};
const readPasskeys = (): PasskeyRecord[] => {
// 1. Try primary passkeys.json
try {
if (fs.existsSync(PASSKEYS_FILE)) {
const data = fs.readFileSync(PASSKEYS_FILE, "utf-8");
const parsed = JSON.parse(data);
if (Array.isArray(parsed) && parsed.length > 0) {
return parsed;
}
}
} catch (error) {
console.error("Error reading primary passkeys.json, trying backup:", error);
}
// 2. Fallback to backup mirror data/passkeys_backup.json
try {
if (fs.existsSync(PASSKEYS_BACKUP_FILE)) {
const data = fs.readFileSync(PASSKEYS_BACKUP_FILE, "utf-8");
const parsed = JSON.parse(data);
if (Array.isArray(parsed) && parsed.length > 0) {
console.log("[PasskeyPersistence] Recovered passkeys from backup mirror.");
writePasskeys(parsed, false); // Restore primary
return parsed;
}
}
} catch (error) {
console.error("Error reading passkeys_backup.json:", error);
}
return [];
};
const writePasskeys = (passkeys: PasskeyRecord[], syncBackup: boolean = true) => {
try {
// 1. Write primary passkeys.json
fs.writeFileSync(PASSKEYS_FILE, JSON.stringify(passkeys, null, 2), "utf-8");
// 2. Write redundant backup mirror
if (syncBackup) {
const dataDir = path.join(process.cwd(), "data");
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
fs.writeFileSync(PASSKEYS_BACKUP_FILE, JSON.stringify(passkeys, null, 2), "utf-8");
// 3. Create timestamped snapshot in snapshots dir
const snapshotsDir = path.join(dataDir, "snapshots");
if (!fs.existsSync(snapshotsDir)) {
fs.mkdirSync(snapshotsDir, { recursive: true });
}
const snapFile = path.join(snapshotsDir, `passkeys_snapshot_${Date.now()}.json`);
fs.writeFileSync(snapFile, JSON.stringify(passkeys, null, 2), "utf-8");
// Prune old snapshots (keep last 15)
const existing = fs.readdirSync(snapshotsDir).filter(f => f.startsWith("passkeys_snapshot_")).sort().reverse();
if (existing.length > 15) {
existing.slice(15).forEach(f => {
try { fs.unlinkSync(path.join(snapshotsDir, f)); } catch {}
});
}
}
} catch (error) {
console.error("Error writing passkeys across multi-tier storage:", error);
}
};
// Persistent Active Sessions Map (survives window closures, tab reloads, and container restarts)
const authSessions = new Map<string, AuthSessionRecord>();
const loadPersistedSessions = () => {
try {
if (fs.existsSync(ACTIVE_SESSIONS_FILE)) {
const data = fs.readFileSync(ACTIVE_SESSIONS_FILE, "utf-8");
const list: AuthSessionRecord[] = JSON.parse(data);
const now = Date.now();
if (Array.isArray(list)) {
list.forEach(sess => {
if (sess.expiresAt > now) {
authSessions.set(sess.sessionId, sess);
}
});
}
}
} catch (err) {
console.error("[PasskeySessions] Error loading persisted active sessions:", err);
}
};
const savePersistedSessions = () => {
try {
const dataDir = path.join(process.cwd(), "data");
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
const list = Array.from(authSessions.values());
fs.writeFileSync(ACTIVE_SESSIONS_FILE, JSON.stringify(list, null, 2), "utf-8");
} catch (err) {
console.error("[PasskeySessions] Error saving active sessions to disk:", err);
}
};
// Initial session load
loadPersistedSessions();
// Store temporary portal tokens for passkey device registration/authentication
const portalTokens = new Map<string, PortalTokenData>();
const readSmtpConfig = (): any => {
try {
if (fs.existsSync(SMTP_CONFIG_FILE)) {
const data = fs.readFileSync(SMTP_CONFIG_FILE, "utf-8");
return JSON.parse(data);
}
} catch (error) {
console.error("Error reading smtp_config.json:", error);
}
// Fallback to environment variables
return {
host: process.env.SMTP_HOST || "",
port: parseInt(process.env.SMTP_PORT || "587") || 587,
user: process.env.SMTP_USER || "",
pass: process.env.SMTP_PASS || "",
from: process.env.SMTP_FROM || "Meridian Research <no-reply@ask-meridian.uk>",
recipient: process.env.USER_EMAIL || "lucas.kempe@icloud.com",
twilioSid: process.env.TWILIO_ACCOUNT_SID || "",
twilioToken: process.env.TWILIO_AUTH_TOKEN || "",
twilioFrom: process.env.TWILIO_FROM_NUMBER || "+14155238886",
whatsappRecipient: process.env.WHATSAPP_RECIPIENT || "1170666236"
};
};
const writeSmtpConfig = (config: any) => {
try {
fs.writeFileSync(SMTP_CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
} catch (error) {
console.error("Error writing smtp_config.json:", error);
}
};
// Initialize Firestore on Server Side
let db: any = null;
const CONFIG_FILE = path.join(process.cwd(), "firebase-applet-config.json");
let firebaseConfig: any = null;
if (fs.existsSync(CONFIG_FILE)) {
try {
firebaseConfig = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf-8"));
} catch (err) {
console.error("Failed to parse firebase-applet-config.json:", err);
}
}
if (firebaseConfig && firebaseConfig.projectId) {
try {
const firebaseApp = initializeApp(firebaseConfig);
db = initializeFirestore(firebaseApp, {
experimentalForceLongPolling: true,
}, firebaseConfig.firestoreDatabaseId);
console.log("Firebase Firestore successfully initialized on Server!");
} catch (error) {
console.error("Failed to initialize Firebase on Server:", error);
}
}
// Resolves a high-precision numeric timestamp for any blog post
const getBlogTimestamp = (blog: any): number => {
if (blog?.createdAt && typeof blog.createdAt === "number" && !isNaN(blog.createdAt)) {
return blog.createdAt;
}
if (blog?.timestamp && typeof blog.timestamp === "number" && !isNaN(blog.timestamp)) {
return blog.timestamp;
}
if (blog?.id && typeof blog.id === "string") {
const match = blog.id.match(/(?:generated|draft|blog)-(\d+)/);
if (match && match[1]) {
const val = Number(match[1]);
if (!isNaN(val) && val > 1000000000) return val;
}
}
if (blog?.date && typeof blog.date === "string") {
const parsed = Date.parse(blog.date);
if (!isNaN(parsed)) return parsed;
}
return 0;
};
// Chronologically sort blogs so newest articles appear first deterministically
const sortBlogsChronologically = (blogs: any[]): any[] => {
return [...blogs].sort((a: any, b: any) => {
const timeA = getBlogTimestamp(a);
const timeB = getBlogTimestamp(b);
if (timeA !== timeB) {
return timeB - timeA;
}
return (a?.title || "").localeCompare(b?.title || "");
});
};
// Get all blogs, with fallback to local JSON file
const getBlogs = async (): Promise<any[]> => {
const localBlogs = sortBlogsChronologically(readCustomBlogs());
if (!db) {
return localBlogs;
}
try {
const querySnapshot = await getDocs(collection(db, "blogs"));
const firestoreBlogs: any[] = [];
querySnapshot.forEach((doc) => {
firestoreBlogs.push(doc.data());
});
if (firestoreBlogs.length === 0 && localBlogs.length > 0) {
// Seed Firestore with local blogs if Firestore is completely empty
console.log(`Firestore blogs collection is empty. Seeding with ${localBlogs.length} local blogs...`);
for (const blog of localBlogs) {
if (blog && blog.id) {
await setDoc(doc(db, "blogs", blog.id), blog);
}
}
return localBlogs;
}
return sortBlogsChronologically(firestoreBlogs);
} catch (error) {
console.error("Error reading from Firestore, falling back to local file:", error);
return localBlogs;
}
};
let lastGitHubSyncTimestamp: number | null = null;
let lastGitHubSyncStatus: any = null;
// Active Server-Sent Events (SSE) connections for live real-time pipeline monitoring
const activePipelineStreams = new Map<string, Set<express.Response>>();
function broadcastPipelineUpdate(record: PipelineExecutionRecord) {
if (!record || !record.jobId) return;
const clients = activePipelineStreams.get(record.jobId);
if (clients && clients.size > 0) {
const ssePayload = `data: ${JSON.stringify(record)}\n\n`;
for (const res of clients) {
try {
res.write(ssePayload);
} catch (err) {
clients.delete(res);
}
}
}
}
// 99.999% Multi-Tier Save for a single blog: custom_blogs.json, src/data.ts, snapshot, sitemap, Firestore, GitHub
const saveBlog = async (blog: any, reason: string = "save blog") => {
const rawLocalBlogs = readCustomBlogs();
const existingIdx = rawLocalBlogs.findIndex((b: any) => b.id === blog.id || b.slug === blog.slug);
if (existingIdx !== -1) {
rawLocalBlogs[existingIdx] = { ...rawLocalBlogs[existingIdx], ...blog };
} else {
rawLocalBlogs.unshift(blog);
}
const localBlogs = sortBlogsChronologically(rawLocalBlogs);
// Execute 6-Tier replication
const result = await persistMultiTierBlogs(localBlogs, db, `${reason}: ${blog.title?.slice(0, 40) || blog.id}`);
lastGitHubSyncTimestamp = Date.now();
lastGitHubSyncStatus = result.tiers;
return result;
};
// 99.999% Multi-Tier Save for multiple blogs: custom_blogs.json, src/data.ts, snapshot, sitemap, Firestore, GitHub
const saveBlogs = async (blogs: any[], reason: string = "batch sync") => {
const sortedBlogs = sortBlogsChronologically(blogs);
const result = await persistMultiTierBlogs(sortedBlogs, db, reason);
lastGitHubSyncTimestamp = Date.now();
lastGitHubSyncStatus = result.tiers;
return result;
};
// Delete a blog from local files, Firestore, and GitHub mirror
const deleteBlog = async (id: string): Promise<boolean> => {
// 1. Delete locally
const localBlogs = readCustomBlogs();
const filtered = localBlogs.filter((b: any) => b.id !== id && b.slug !== id);
await persistMultiTierBlogs(filtered, db, `delete article ${id}`);
// 2. Delete from Firestore explicitly
let firestoreSuccess = true;
if (db) {
try {
await deleteDoc(doc(db, "blogs", id));
console.log(`Blog ${id} successfully deleted from Firestore.`);
} catch (error) {
console.error("Error deleting from Firestore:", error);
firestoreSuccess = false;
}
}
return firestoreSuccess;
};
// View counter state & persistent tracking
const blogViewsMap = new Map<string, number>();
const getBlogViews = (idOrSlug: string): number => {
if (!idOrSlug) return 100;
if (blogViewsMap.has(idOrSlug)) {
return blogViewsMap.get(idOrSlug)!;
}
// Compute a deterministic realistic base view count between 320 and 1850
let hash = 0;
for (let i = 0; i < idOrSlug.length; i++) {
hash = (hash << 5) - hash + idOrSlug.charCodeAt(i);
hash |= 0;
}
const baseViews = 320 + (Math.abs(hash) % 1530);
blogViewsMap.set(idOrSlug, baseViews);
return baseViews;
};
const incrementBlogViews = (idOrSlug: string): { views: number; activeReaders: number } => {
const current = getBlogViews(idOrSlug);
const updated = current + 1;
blogViewsMap.set(idOrSlug, updated);
// Deterministic realistic active readers count between 2 and 18
let hash = 0;
for (let i = 0; i < idOrSlug.length; i++) {
hash = (hash << 5) - hash + idOrSlug.charCodeAt(i);
hash |= 0;
}
const activeReaders = 2 + (Math.abs(hash + updated) % 17);
return { views: updated, activeReaders };
};
// API: Get all custom blogs
app.get("/api/blogs", async (req, res) => {
const rawBlogs = await getBlogs();
const blogs = rawBlogs.map((b) => ({
...b,
views: b.views || getBlogViews(b.id)
}));
res.json({ blogs });
});
// API: Resilient single blog resolver (by exact slug, base slug, ID, or arXiv ID)
app.get("/api/blogs/:idOrSlug", async (req, res) => {
const { idOrSlug } = req.params;
const allBlogs = await getBlogs();
const matched = resolveBlogSlugOrId(idOrSlug, allBlogs);
if (matched) {
const views = matched.views || getBlogViews(matched.id);
return res.json({ blog: { ...matched, views } });
}
return res.status(404).json({ error: "Article not found", query: idOrSlug });
});
// API: Real-time SSE stream for generation pipeline execution
app.get("/api/pipeline/stream/:jobId", (req, res) => {
const { jobId } = req.params;
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache, no-transform");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
res.flushHeaders();
if (!activePipelineStreams.has(jobId)) {
activePipelineStreams.set(jobId, new Set());
}
activePipelineStreams.get(jobId)!.add(res);
// Send initial ping
res.write(`data: ${JSON.stringify({ status: "connected", jobId, timestamp: Date.now() })}\n\n`);
req.on("close", () => {
const clients = activePipelineStreams.get(jobId);
if (clients) {
clients.delete(res);
if (clients.size === 0) {
activePipelineStreams.delete(jobId);
}
}
});
});
// API: Get historical pipeline generation records
app.get("/api/pipeline/records", (req, res) => {
try {
const records = readPipelineRecords();
res.json({ records, count: records.length });
} catch (err: any) {
res.status(500).json({ error: err.message || "Failed to retrieve pipeline records" });
}
});
// API: Get single pipeline execution record by jobId
app.get("/api/pipeline/records/:jobId", (req, res) => {
try {
const records = readPipelineRecords();
const found = records.find(r => r.jobId === req.params.jobId);
if (found) {
return res.json({ record: found });
}
return res.status(404).json({ error: "Pipeline record not found" });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// API: Multi-tier storage diagnostic self-check
app.post("/api/pipeline/audit-check", async (req, res) => {
const customBlogsExists = fs.existsSync(CUSTOM_BLOGS_FILE);
const dataTsExists = fs.existsSync(path.join(process.cwd(), "src", "data.ts"));
const journalExists = fs.existsSync(path.join(process.cwd(), "data", "generation_journal.jsonl"));
const sitemapExists = fs.existsSync(path.join(process.cwd(), "public", "sitemap.xml"));
const allBlogs = await getBlogs();
res.json({
healthy: customBlogsExists && dataTsExists,
totalArticles: allBlogs.length,
tiers: {
customBlogsJson: { exists: customBlogsExists, count: readCustomBlogs().length },
dataTs: { exists: dataTsExists },
journalJsonl: { exists: journalExists },
sitemapXml: { exists: sitemapExists },
firestore: { connected: !!db },
gitHubMirror: { configured: !!process.env.GITHUB_TOKEN }
},
sampleArticleTest: {
quantumFramePotentialFound: !!resolveBlogSlugOrId("towards-optimal-quantum-estimators-for-state-frame-potential-9854", allBlogs)
}
});
});
// API: Increment blog view counter
app.post("/api/blogs/:id/view", async (req, res) => {
const { id } = req.params;
if (!id) {
return res.status(400).json({ error: "Missing blog ID parameter" });
}
const { views, activeReaders } = incrementBlogViews(id);
// If blog exists in local file or Firestore, update its view property
const localBlogs = readCustomBlogs();
const targetIndex = localBlogs.findIndex((b: any) => b.id === id || b.slug === id);
if (targetIndex !== -1) {
localBlogs[targetIndex].views = views;
writeCustomBlogs(localBlogs);
}
res.json({ success: true, id, views, activeReaders });
});
// API: Delete a custom blog
app.delete("/api/blogs/:id", async (req, res) => {
const { id } = req.params;
const password = req.headers["x-deletion-password"] || req.query.password || req.body?.password;
const expectedPassword = process.env.EDITOR_PASSWORD || process.env.GENERATION_PASSWORD || "meridian";
if (!password || password !== expectedPassword) {
return res.status(403).json({ error: "Unauthorized: Incorrect editor password." });
}
const success = await deleteBlog(id);
res.json({ success });
});
// API: Verify Editor Password
app.post("/api/verify-editor-password", (req, res) => {
const { password } = req.body;
const expectedPassword = process.env.EDITOR_PASSWORD || process.env.GENERATION_PASSWORD || "meridian";
if (password === expectedPassword) {
res.json({ success: true });
} else {
res.status(403).json({ error: "Incorrect password." });
}
});
// API: Get GitHub Mirror Status
app.get("/api/github/status", async (req, res) => {
try {
const config = getGitHubSyncConfig();
const conn = await testGitHubConnection();
const allBlogs = await getBlogs();
res.json({
configured: config.configured,
connected: conn.connected,
repo: config.repo,
branch: config.branch,
authorName: config.authorName,
authorEmail: config.authorEmail,
user: conn.user || null,
message: conn.message,
totalArticles: allBlogs.length,
lastSyncTimestamp: lastGitHubSyncTimestamp,
lastSyncStatus: lastGitHubSyncStatus
});
} catch (err: any) {
console.error("Error checking GitHub status:", err);
res.status(500).json({ error: err.message || "Failed to check GitHub status" });
}
});
// API: Manually trigger instant GitHub sync
app.post("/api/github/sync", async (req, res) => {
const { password, reason } = req.body || {};
const expectedPassword = process.env.EDITOR_PASSWORD || process.env.GENERATION_PASSWORD || "meridian";
if (password && password !== expectedPassword) {
return res.status(403).json({ error: "Unauthorized: Incorrect password." });
}
try {
const allBlogs = await getBlogs();
const result = await syncAllBlogsToGitHub(
allBlogs,
reason || "manual mirror sync via dashboard"
);
lastGitHubSyncTimestamp = Date.now();
lastGitHubSyncStatus = result;
res.json(result);
} catch (err: any) {
console.error("Manual GitHub sync error:", err);
res.status(500).json({
success: false,
error: err.message || "Failed to execute GitHub sync",
message: err.message
});
}
});
// API: Export complete repository bundle (JSON + TypeScript source)
app.get("/api/export/repo-bundle", async (req, res) => {
try {
const allBlogs = await getBlogs();
const dataTs = generateDataTsContent(allBlogs);
res.json({
totalArticles: allBlogs.length,
timestamp: Date.now(),
customBlogsJson: allBlogs,
dataTsSource: dataTs,
instructions: "To update your local GitHub clone: save customBlogsJson into custom_blogs.json, or save dataTsSource into src/data.ts, and git commit."
});
} catch (err: any) {
console.error("Export bundle error:", err);
res.status(500).json({ error: "Failed to generate export bundle" });
}
});
// API: Pull all published articles directly from production (https://ask-meridian.uk/api/blogs)
app.post("/api/blogs/pull-prod", async (req, res) => {
const { password } = req.body || {};
const expectedPassword = process.env.EDITOR_PASSWORD || process.env.GENERATION_PASSWORD || "meridian";
if (password && password !== expectedPassword) {
return res.status(403).json({ error: "Unauthorized: Incorrect password." });
}
try {
const prodRes = await fetch("https://ask-meridian.uk/api/blogs", {
headers: { "User-Agent": "Meridian-AIStudio-Sync" },
signal: AbortSignal.timeout(12000)
});
if (!prodRes.ok) {
throw new Error(`Production server returned HTTP ${prodRes.status}`);
}
const data: any = await prodRes.json();
const prodBlogs = data.blogs || [];
if (!Array.isArray(prodBlogs) || prodBlogs.length === 0) {
throw new Error("No blogs returned from production");
}
await saveBlogs(prodBlogs, "pull and sync from production");
res.json({
success: true,
message: `Successfully pulled and synchronized ${prodBlogs.length} articles from production.`,
totalArticles: prodBlogs.length,
blogs: prodBlogs
});
} catch (err: any) {
console.error("Error pulling from production:", err);
res.status(500).json({ success: false, error: err.message || "Failed to pull articles from production" });
}
});
// Get registered passkeys, syncing with Firestore if available
const getPasskeys = async (): Promise<any[]> => {
const localPasskeys = readPasskeys();
if (!db) {
return localPasskeys;
}
try {
const querySnapshot = await getDocs(collection(db, "passkeys"));
const firestorePasskeys: any[] = [];
querySnapshot.forEach((doc) => {
firestorePasskeys.push(doc.data());
});
// Merge them by ID
const mergedMap = new Map<string, any>();
localPasskeys.forEach((p) => mergedMap.set(p.id, p));
firestorePasskeys.forEach((p) => mergedMap.set(p.id, p));
const mergedList = Array.from(mergedMap.values());
if (mergedList.length > localPasskeys.length) {
writePasskeys(mergedList);
}
return mergedList;
} catch (error) {
console.error("Error reading passkeys from Firestore, falling back to local file:", error);
return localPasskeys;
}
};
// API: Generate WebAuthn Challenge & Detect Device Fingerprint
app.post("/api/passkeys/challenge", (req, res) => {
try {
const fingerprint = extractClientFingerprint(req);
const challenge = generateSecureChallenge();
logPasskeyAudit("challenge_generated", "success", {
details: {
fingerprintHash: fingerprint.fingerprintHash,
platform: fingerprint.platform,
language: fingerprint.language
},
req
});
res.json({
challenge,
fingerprint,
rpId: req.hostname
});
} catch (err: any) {
logPasskeyAudit("challenge_generated", "failure", { details: { error: err.message }, req });
res.status(500).json({ error: "Failed to generate security challenge" });
}
});
// API: Get registered passkeys
app.get("/api/passkeys/list", async (req, res) => {
const passkeys = await getPasskeys();
res.json({ passkeys });
});
// API: Bidirectional synchronization of passkeys between client localStorage and server storage tiers
app.post("/api/passkeys/sync", async (req, res) => {
try {
const { passkeys: clientPasskeys, fingerprint } = req.body;
const currentPasskeys = await getPasskeys();
const syncResult = syncPasskeyCollections(currentPasskeys, clientPasskeys);
// Persist merged set across all server tiers
writePasskeys(syncResult.merged, true);
// Sync to Firestore if db is available
if (db && syncResult.addedCount > 0) {
for (const pk of syncResult.merged) {
try {
await setDoc(doc(db, "passkeys", pk.id), pk);
} catch (err) {