-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
399 lines (344 loc) · 10.6 KB
/
server.js
File metadata and controls
399 lines (344 loc) · 10.6 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
// /opt/ghost-like-button/server.js
import express from "express";
import helmet from "helmet";
import rateLimit from "express-rate-limit";
import crypto from "crypto";
import Database from "better-sqlite3";
const PORT = 8787;
const GHOST_URL = process.env.GHOST_URL;
if (!GHOST_URL) {
console.error("ERROR: GHOST_URL environment variable is required");
process.exit(1);
}
let db;
try {
db = new Database("/data/ghost-like-button.db", { fileMustExist: false });
db.pragma("journal_mode = WAL");
db.pragma("synchronous = NORMAL");
db.exec(`
CREATE TABLE IF NOT EXISTS like_counts (
url_hash BLOB PRIMARY KEY,
url TEXT NOT NULL,
like_count INTEGER NOT NULL DEFAULT 0,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS like_actors (
url_hash BLOB NOT NULL,
actor_type TEXT NOT NULL, -- 'member'
actor TEXT NOT NULL, -- member email (sub)
liked INTEGER NOT NULL DEFAULT 1,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (url_hash, actor_type, actor)
);
`);
console.log("Database initialized successfully");
} catch (err) {
console.error("FATAL: Database initialization failed:", err.message);
console.error("Please check that /data directory has correct permissions");
process.exit(1);
}
const getCount = db.prepare("SELECT like_count FROM like_counts WHERE url_hash = ?");
const upsertCount = db.prepare(`
INSERT INTO like_counts (url_hash, url, like_count, updated_at)
VALUES (?, ?, 1, CURRENT_TIMESTAMP)
ON CONFLICT(url_hash) DO UPDATE SET
like_count = like_count + 1,
updated_at = CURRENT_TIMESTAMP
`);
const decrementCount = db.prepare(`
UPDATE like_counts
SET like_count = MAX(0, like_count - 1),
updated_at = CURRENT_TIMESTAMP
WHERE url_hash = ?
`);
const getMember = db.prepare("SELECT liked FROM like_actors WHERE url_hash=? AND actor_type='member' AND actor=?");
const insertMember = db.prepare(`
INSERT INTO like_actors (url_hash, actor_type, actor, liked, updated_at)
VALUES (?, 'member', ?, 1, CURRENT_TIMESTAMP)
`);
const deleteMember = db.prepare(`
DELETE FROM like_actors
WHERE url_hash=? AND actor_type='member' AND actor=?
`);
const app = express();
app.disable("x-powered-by");
app.set("trust proxy", 1);
app.use(helmet({ crossOriginResourcePolicy: false }));
app.use(express.text({ type: "*/*", limit: "64b" }));
app.use(rateLimit({
windowMs: 60_000,
max: 90,
standardHeaders: true,
legacyHeaders: false
}));
// CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", GHOST_URL);
res.setHeader("Vary", "Origin");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader("Access-Control-Expose-Headers", "X-Has-Liked");
if (req.method === "OPTIONS") return res.sendStatus(204);
next();
});
const normUrl = (raw) => {
try {
const u = new URL(raw);
u.hash = "";
u.protocol = u.protocol.toLowerCase();
u.hostname = u.hostname.toLowerCase();
if (!u.pathname) u.pathname = "/";
return u.href;
} catch { return null; }
};
const md5buf = (s) => Buffer.from(crypto.createHash("md5").update(s, "utf8").digest("hex"), "hex");
function decodeJWT(token) {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
return payload;
} catch (err) {
return null;
}
}
async function verifyGhostToken(bearer) {
if (!bearer?.startsWith("Bearer ")) return null;
const token = bearer.slice(7);
try {
const payload = decodeJWT(token);
if (!payload) return null;
const expectedAudience = new URL("/members/api", GHOST_URL).href;
const expectedIssuer = new URL("/members/api", GHOST_URL).href;
if (payload.aud !== expectedAudience) return null;
if (payload.iss !== expectedIssuer) return null;
const now = Math.floor(Date.now() / 1000);
if (payload.exp && payload.exp < now) return null;
return typeof payload.sub === "string" ? payload.sub.toLowerCase() : null;
} catch (err) {
return null;
}
}
// Helper function to check if request is from browser
const isBrowserRequest = (req) => {
const accept = req.get('accept') || '';
return accept.includes('text/html');
};
// Helper function to serve 404 page
const serve404 = (res) => {
const ghostUrl = GHOST_URL;
res.status(404).type('text/html').send(`
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="UTF-8">
<title>404 — Page not found</title>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<style>
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
html, body {
margin: 0;
padding: 0;
height: 100%;
font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;
font-size: 62.5%;
line-height: 1.65;
letter-spacing: .2px;
color: #343f44;
overflow: hidden;
}
main, section, div, h1, h2, a {
box-sizing: border-box;
}
a {
text-decoration: none;
background-color: transparent;
color: #5ba4e5;
transition: background .3s, color .3s;
}
a:hover {
text-decoration: underline;
}
.gh-app, .gh-viewport, .gh-view, .error-content, .error-details, .error-message {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.gh-app, .gh-viewport {
height: 100%;
overflow: hidden;
}
.gh-view {
flex-grow: 1;
}
.error-content {
flex-grow: 1;
padding: 8vw;
}
.error-details {
flex-direction: row;
margin-bottom: 4rem;
}
.error-message {
margin: 15px;
}
.error-code {
margin: 0;
color: #c5d2d9;
font-size: 10vw;
font-weight: 600;
line-height: .9em;
letter-spacing: -.4vw;
}
.error-description {
margin: 0;
padding: 0;
color: #54666d;
font-size: 2.3rem;
font-weight: 300;
line-height: 1.3em;
}
.error-link {
font-size: 1.4rem;
line-height: 1;
margin: 8px 0;
}
</style>
</head>
<body>
<main role="main" id="main">
<div class="gh-app">
<div class="gh-viewport">
<div class="gh-view">
<section class="error-content error-404 js-error-container">
<section class="error-details">
<section class="error-message">
<h1 class="error-code">404</h1>
<h2 class="error-description">Page not found</h2>
<a class="error-link" href="${ghostUrl}">Go to the front page →</a>
</section>
</section>
</section>
</div>
</div>
</div>
</main>
</body>
</html>
`);
};
// Health check endpoint
app.get("/health", (req, res) => {
// Show 404 page if accessed from browser
if (isBrowserRequest(req)) {
return serve404(res);
}
try {
// Test database connectivity
db.prepare("SELECT 1").get();
res.status(200).json({
status: "ok",
service: "ghost-like-button",
timestamp: new Date().toISOString()
});
} catch (err) {
res.status(503).json({
status: "error",
service: "ghost-like-button",
error: "Database unavailable"
});
}
});
// Root route - serve Ghost-like 404
app.get("/", (req, res) => {
serve404(res);
});
// GET: total count + whether THIS member has liked
app.get("/get-likes", async (req, res) => {
// Show 404 page if accessed from browser
if (isBrowserRequest(req)) {
return serve404(res);
}
const raw = req.query.url || req.get("referer");
const url = normUrl(raw || "");
if (!url) return res.type("text/plain").send("0");
const h = md5buf(url);
const row = getCount.get(h);
const count = row ? row.like_count : 0;
const memberId = await verifyGhostToken(req.headers.authorization || "");
let has = 0;
if (memberId) {
const m = getMember.get(h, memberId);
has = m ? 1 : 0;
}
res.setHeader("X-Has-Liked", has ? "1" : "0");
return res.type("text/plain").send(String(count));
});
// GET on POST-only endpoint - show 404
app.get("/update-likes", (_req, res) => {
serve404(res);
});
// POST: toggle like/unlike
app.post("/update-likes", async (req, res) => {
// Show 404 page if accessed from browser
if (isBrowserRequest(req)) {
return serve404(res);
}
const raw = req.query.url || req.get("referer");
const url = normUrl(raw || "");
if (!url) return res.type("text/plain").send("0");
const memberId = await verifyGhostToken(req.headers.authorization || "");
if (!memberId) return res.sendStatus(401);
const h = md5buf(url);
const tx = db.transaction(() => {
const already = getMember.get(h, memberId);
let hasLiked;
if (!already) {
// Like: member hasn't liked yet
insertMember.run(h, memberId);
upsertCount.run(h, url);
hasLiked = 1;
} else {
// Unlike: member has already liked, remove it
deleteMember.run(h, memberId);
decrementCount.run(h);
hasLiked = 0;
}
const c = getCount.get(h);
return { total: c ? c.like_count : 0, hasLiked };
});
const result = tx();
res.setHeader("X-Has-Liked", String(result.hasLiked));
return res.type("text/plain").send(String(result.total));
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error("Server error:", err);
res.status(500).send("Internal Server Error");
});
const server = app.listen(PORT, "0.0.0.0", () => {
console.log("ghost-like-button API listening on :" + PORT);
console.log("GHOST_URL:", GHOST_URL);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM received, shutting down gracefully...');
server.close(() => {
console.log('HTTP server closed');
db.close();
console.log('Database connection closed');
process.exit(0);
});
});
process.on('SIGINT', () => {
console.log('SIGINT received, shutting down gracefully...');
server.close(() => {
console.log('HTTP server closed');
db.close();
console.log('Database connection closed');
process.exit(0);
});
});