-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
372 lines (329 loc) · 16.6 KB
/
server.js
File metadata and controls
372 lines (329 loc) · 16.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
/**
* ano - server.js
* ===============
* HTTP server — web UI + API.
*
* ── Public pages ──────────────────────────────────────────────
* GET / landing page
* GET /login sign in / sign up (Firebase Auth)
* GET /docs API reference (public)
* POST /auth/session called by browser after Firebase sign-in → sets cookie
* POST /auth/logout clears session cookie
*
* ── Protected pages (require Firebase login) ──────────────────
* GET /dashboard developer dashboard + API key
* GET /playground live API tester
*
* ── API routes (require x-ano-api-key header) ─────────────────
* POST /feed
* POST /event
* POST /profile/:userId/onboard
* GET /profile/:userId
* POST /profile/:userId
* DELETE /profile/:userId
*
* ── Admin routes (require x-ano-master-key header) ────────────
* POST /admin/keys
* DELETE /admin/keys
* GET /admin/keys/:tenantId
*
* ── Misc ──────────────────────────────────────────────────────
* GET /health
*/
require("dotenv").config();
const express = require("express");
const ejsLayouts = require("express-ejs-layouts");
const path = require("path");
const cors = require("cors");
const { requireAuth, optionalAuth } = require("./lib/authMiddleware");
const { getTenant, createTenantIfNew } = require("./lib/tenants");
const { createApiKey, validateApiKey, revokeApiKey, listKeysForTenant } = require("./lib/apiKeys");
const { saveProfile, loadProfile, deleteProfile, profileExists } = require("./lib/storage");
const { UserProfile } = require("./lib/userProfile");
const { enrichPosts } = require("./lib/postParser");
const { rankFeed } = require("./lib/feedScorer");
const app = express();
const PORT = process.env.PORT || 3000;
const MASTER_KEY = process.env.ANO_MASTER_KEY;
const NODE_ENV = process.env.NODE_ENV || "development";
// ── View engine ───────────────────────────────────────────────
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(ejsLayouts);
app.set("layout", "layout");
// Pass shared locals to every view
app.use((req, res, next) => {
res.locals.nodeEnv = NODE_ENV;
res.locals.user = null; // overridden by auth middleware when logged in
res.locals.firebaseConfig = {
apiKey : process.env.FIREBASE_API_KEY,
authDomain : process.env.FIREBASE_AUTH_DOMAIN,
projectId : process.env.FIREBASE_PROJECT_ID,
storageBucket : process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId : process.env.FIREBASE_APP_ID,
};
next();
});
app.use(express.static(path.join(__dirname, "public")));
app.use("/ano-app", express.static(path.join(__dirname, "ano-app")));
app.use(express.json({ limit: "2mb" }));
app.use(express.urlencoded({ extended: false }));
// ── CORS ──────────────────────────────────────────────────────
// API routes are consumed by third-party apps — allow all origins.
// Restrict to specific methods & headers so preflight passes cleanly.
const API_PATHS = /^\/(?:feed|event|profile|admin)(\/|$)/;
app.use((req, res, next) => {
if (!API_PATHS.test(req.path)) return next(); // skip for web UI routes
cors({
origin: true, // reflect request origin (allows any)
methods: ["GET", "POST", "DELETE", "OPTIONS"],
allowedHeaders: [
"Content-Type",
"x-ano-api-key",
"x-ano-master-key",
"x-ano-user-id",
],
credentials: false,
maxAge: 86400, // cache preflight for 24 h
})(req, res, next);
});
// ─────────────────────────────────────────────────────────────
// PUBLIC PAGES
// ─────────────────────────────────────────────────────────────
app.get("/", optionalAuth, (req, res) => {
res.locals.user = req.user || null;
res.render("home", {
title : "Feed Engine for Developers",
topbarTitle: "ano",
page : "home",
layout : "layout",
});
});
app.get("/login", (req, res) => {
res.render("login", {
title : "Sign in",
topbarTitle: "Sign in",
page : "login",
layout : false, // login has its own full-page layout
});
});
app.get("/docs", optionalAuth, (req, res) => {
res.locals.user = req.user || null;
res.render("docs", {
title : "API Reference",
topbarTitle: "API Reference",
page : "docs",
layout : "layout",
});
});
// ─────────────────────────────────────────────────────────────
// AUTH ENDPOINTS (called by client-side JS after Firebase sign-in)
// ─────────────────────────────────────────────────────────────
/**
* POST /auth/session
* Browser sends Firebase ID token after sign-in.
* We verify it, create/fetch tenant record, set a cookie.
*/
app.post("/auth/session", async (req, res) => {
const { idToken, user: userInfo } = req.body;
if (!idToken) return res.status(400).json({ error: "idToken required" });
try {
// Create tenant record if this is their first login
const tenant = await createTenantIfNew(userInfo.uid, {
email : userInfo.email,
name : userInfo.displayName || userInfo.name || "",
photoURL: userInfo.photoURL || "",
});
// Set HTTP-only cookie with the raw Firebase token
// In production use a short-lived session cookie instead
const maxAge = 7 * 24 * 60 * 60 * 1000; // 7 days
res.cookie("ano_token", idToken, {
httpOnly: true,
secure : NODE_ENV === "production",
sameSite: "lax",
maxAge,
});
res.json({ ok: true, tenant });
} catch (err) {
console.error("[POST /auth/session]", err);
res.status(500).json({ error: err.message });
}
});
/**
* POST /auth/logout
* Clears the session cookie.
*/
app.post("/auth/logout", (req, res) => {
res.clearCookie("ano_token");
res.json({ ok: true });
});
// ─────────────────────────────────────────────────────────────
// PROTECTED PAGES (require login)
// ─────────────────────────────────────────────────────────────
app.get("/dashboard", requireAuth, async (req, res) => {
const tenant = await getTenant(req.user.uid);
res.locals.user = req.user;
res.render("dashboard", {
title : "Dashboard",
topbarTitle : "Dashboard",
page : "dashboard",
layout : "layout",
tenant,
firebaseProject: process.env.FIREBASE_PROJECT_ID || "—",
});
});
app.get("/playground", requireAuth, (req, res) => {
res.locals.user = req.user;
res.render("playground", {
title : "Playground",
topbarTitle: "API Playground",
page : "playground",
layout : "layout",
});
});
// ─────────────────────────────────────────────────────────────
// API MIDDLEWARE
// ─────────────────────────────────────────────────────────────
function requireMasterKey(req, res, next) {
const key = req.headers["x-ano-master-key"];
if (!MASTER_KEY) return res.status(500).json({ error: "ANO_MASTER_KEY not configured" });
if (key !== MASTER_KEY) return res.status(401).json({ error: "Invalid master key" });
next();
}
async function requireApiKey(req, res, next) {
const rawKey = req.headers["x-ano-api-key"];
if (!rawKey) return res.status(401).json({ error: "Missing x-ano-api-key header" });
const tenant = await validateApiKey(rawKey);
if (!tenant) return res.status(401).json({ error: "Invalid or revoked API key" });
req.tenant = tenant;
next();
}
function requireUserId(req, res, next) {
const userId = req.headers["x-ano-user-id"];
if (!userId) return res.status(400).json({ error: "Missing x-ano-user-id header" });
req.endUserId = userId;
next();
}
async function getOrCreateProfile(tenantId, userId) {
const existing = await loadProfile(tenantId, userId);
if (existing) return existing;
const fresh = new UserProfile(userId);
await saveProfile(tenantId, fresh);
return fresh;
}
// ─────────────────────────────────────────────────────────────
// ADMIN ROUTES
// ─────────────────────────────────────────────────────────────
app.post("/admin/keys", requireMasterKey, async (req, res) => {
try {
const { tenantId, label, env = "live" } = req.body;
if (!tenantId || !label) return res.status(400).json({ error: "tenantId and label required" });
if (!["live", "test"].includes(env)) return res.status(400).json({ error: "env must be live or test" });
res.status(201).json(await createApiKey(tenantId, label, env));
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.delete("/admin/keys", requireMasterKey, async (req, res) => {
try {
const { apiKey } = req.body;
if (!apiKey) return res.status(400).json({ error: "apiKey required" });
const revoked = await revokeApiKey(apiKey);
if (!revoked) return res.status(404).json({ error: "Key not found" });
res.json({ ok: true });
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.get("/admin/keys/:tenantId", requireMasterKey, async (req, res) => {
try {
res.json({ tenantId: req.params.tenantId, keys: await listKeysForTenant(req.params.tenantId) });
} catch (err) { res.status(500).json({ error: err.message }); }
});
// ─────────────────────────────────────────────────────────────
// TENANT API ROUTES
// ─────────────────────────────────────────────────────────────
app.post("/feed", requireApiKey, requireUserId, async (req, res) => {
try {
const { posts } = req.body;
if (!Array.isArray(posts) || !posts.length) return res.status(400).json({ error: "posts must be a non-empty array" });
const { tenantId } = req.tenant;
const profile = await getOrCreateProfile(tenantId, req.endUserId);
if (process.env.DECAY_ON_FETCH === "true") { profile.applyDecay(); await saveProfile(tenantId, profile); }
const ranked = rankFeed(enrichPosts(posts), profile, { limit: +process.env.FEED_LIMIT || 50, filterBlocked: true, diversify: true });
res.json({ tenantId, userId: req.endUserId, count: ranked.length, feed: ranked });
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post("/event", requireApiKey, requireUserId, async (req, res) => {
try {
const { eventType, post } = req.body;
const VALID = ["share","like","click","view","skip","hide"];
if (!VALID.includes(eventType)) return res.status(400).json({ error: `eventType must be one of: ${VALID.join(", ")}` });
if (!post?.id || !post?.title) return res.status(400).json({ error: "post.id and post.title required" });
const { tenantId } = req.tenant;
const profile = await getOrCreateProfile(tenantId, req.endUserId);
profile.recordEvent(eventType, enrichPosts([post])[0]);
await saveProfile(tenantId, profile);
res.json({ ok: true, tenantId, userId: req.endUserId, event: eventType, postId: post.id });
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post("/profile/:userId/onboard", requireApiKey, async (req, res) => {
try {
const { like = [], dislike = [] } = req.body;
if (!like.length && !dislike.length) return res.status(400).json({ error: "Provide at least one topic" });
const profile = await getOrCreateProfile(req.tenant.tenantId, req.params.userId);
like.forEach(t => profile.likeTopic(t));
dislike.forEach(t => profile.dislikeTopic(t));
await saveProfile(req.tenant.tenantId, profile);
res.json({ ok: true, tenantId: req.tenant.tenantId, userId: req.params.userId });
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.get("/profile/:userId", requireApiKey, async (req, res) => {
try {
const profile = await loadProfile(req.tenant.tenantId, req.params.userId);
if (!profile) return res.status(404).json({ error: "Profile not found" });
res.json({ tenantId: req.tenant.tenantId, ...profile.toJSON() });
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post("/profile/:userId", requireApiKey, async (req, res) => {
try {
const profile = await getOrCreateProfile(req.tenant.tenantId, req.params.userId);
const { explicitTopics } = req.body;
if (explicitTopics) {
for (const [t, v] of Object.entries(explicitTopics)) {
if (v === true) profile.likeTopic(t);
else if (v === false) profile.dislikeTopic(t);
else profile.clearExplicit(t);
}
}
await saveProfile(req.tenant.tenantId, profile);
res.json({ ok: true, tenantId: req.tenant.tenantId, profile: profile.toJSON() });
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.delete("/profile/:userId", requireApiKey, async (req, res) => {
try {
if (!await profileExists(req.tenant.tenantId, req.params.userId)) return res.status(404).json({ error: "Profile not found" });
await deleteProfile(req.tenant.tenantId, req.params.userId);
res.json({ ok: true, deleted: req.params.userId });
} catch (err) { res.status(500).json({ error: err.message }); }
});
// ─────────────────────────────────────────────────────────────
// MISC
// ─────────────────────────────────────────────────────────────
app.get("/health", (_, res) => res.json({ status: "ok", service: "ano", version: "2.0.0", uptime: Math.floor(process.uptime()) }));
app.use((req, res) => {
const isApi = req.headers["x-ano-api-key"] || req.headers["x-ano-master-key"] || req.headers["accept"]?.includes("application/json");
if (isApi) return res.status(404).json({ error: `Not found: ${req.method} ${req.path}` });
res.status(404).render("404", { title: "404", topbarTitle: "Not Found", page: "", layout: "layout" });
});
// ─────────────────────────────────────────────────────────────
// START — only listen when running locally, not on Vercel
// ─────────────────────────────────────────────────────────────
if (process.env.VERCEL !== "1") {
app.listen(PORT, () => {
console.log(`\n ┌──────────────────────────────────────────────┐`);
console.log(` │ ano feed engine │`);
console.log(` │ http://localhost:${PORT} │`);
console.log(` │ ENV : ${NODE_ENV.padEnd(33)}│`);
console.log(` │ Firebase : ${(process.env.FIREBASE_PROJECT_ID||"not set").padEnd(33)}│`);
console.log(` └──────────────────────────────────────────────┘\n`);
});
}
module.exports = app;