-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
290 lines (243 loc) · 8.42 KB
/
server.js
File metadata and controls
290 lines (243 loc) · 8.42 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
// server.js (ESM)
import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import sqlite3 from "sqlite3";
import { open } from "sqlite";
import jwt from "jsonwebtoken";
import crypto from "crypto";
import "dotenv/config";
// ---------- env / constants ----------
const PORT = process.env.PORT || 3000;
const ORIGIN = process.env.CLIENT_ORIGIN || "http://localhost:5173";
const IS_PROD = process.env.NODE_ENV === "production";
const JWT_SECRET = process.env.JWT_SECRET || "dev-secret-change-me";
const COOKIE_NAME = "access";
const CSRF_COOKIE = "csrf";
// ---------- app ----------
const app = express();
app.use(cors({ origin: ORIGIN, credentials: true }));
app.use(express.json());
app.use(cookieParser());
// ---------- db ----------
const db = await open({
filename: "./data.sqlite",
driver: sqlite3.Database,
});
// Users: add role so you can do role-based UI/permissions later
await db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user'
);
`);
// ---------- helpers ----------
function makeHash(name, pass) {
// NOTE: simple/fast for dev compatibility; consider bcrypt/scrypt in prod.
return crypto.createHash("sha256").update(name + pass).digest("hex");
}
function signAccessToken(payload) {
// Short-lived access token in httpOnly cookie
return jwt.sign(payload, JWT_SECRET, { expiresIn: "15m" });
}
function setAuthCookie(res, token) {
res.cookie(COOKIE_NAME, token, {
httpOnly: true,
secure: IS_PROD,
sameSite: "lax",
path: "/",
// You can also set domain if serving behind a shared parent domain
});
}
function clearAuthCookie(res) {
res.clearCookie(COOKIE_NAME, { path: "/" });
}
function ensureCsrfCookie(req, res) {
let secret = req.cookies[CSRF_COOKIE];
if (!secret) {
secret = crypto.randomBytes(32).toString("hex");
res.cookie(CSRF_COOKIE, secret, {
httpOnly: true, // JS can't read this; safer
secure: IS_PROD,
sameSite: "lax",
path: "/",
});
}
return secret;
}
function csrfTokenFromSecret(secret) {
// Double-submit: client gets token via /csrf and echoes in header x-csrf-token
return crypto.createHmac("sha256", secret).update("csrf").digest("hex");
}
// ---------- middleware ----------
function requireAuth(req, res, next) {
const token = req.cookies[COOKIE_NAME];
if (!token) return res.status(401).json({ error: "unauthorized" });
try {
const payload = jwt.verify(token, JWT_SECRET);
req.user = payload; // { id, name, role, iat, exp }
next();
} catch (e) {
return res.status(401).json({ error: "invalid token" });
}
}
// Use on mutating routes (POST/PUT/PATCH/DELETE)
function verifyCsrf(req, res, next) {
const method = (req.method || "GET").toUpperCase();
const needs = ["POST", "PUT", "PATCH", "DELETE"].includes(method);
if (!needs) return next();
const secret = req.cookies[CSRF_COOKIE];
const header = req.get("x-csrf-token") || "";
if (!secret) return res.status(403).json({ error: "missing csrf cookie" });
const expected = csrfTokenFromSecret(secret);
if (header !== expected) {
return res.status(403).json({ error: "bad csrf token" });
}
next();
}
// Apply CSRF verification globally (it no-ops on safe methods)
app.use(verifyCsrf);
// ---------- auth routes ----------
app.post("/auth/register", async (req, res, next) => {
try {
const { name, pass, role } = req.body || {};
if (!name || typeof name !== "string") return res.status(400).json({ error: "name (string) is required" });
if (!pass || typeof pass !== "string") return res.status(400).json({ error: "pass (string) is required" });
const nm = name.trim();
const hash = makeHash(nm, pass.trim());
const userRole = (role && typeof role === "string" ? role.trim() : "user") || "user";
const result = await db.run(
"INSERT INTO users (name, hash, role) VALUES (?, ?, ?)",
nm, hash, userRole
);
const created = await db.get("SELECT id, name, role FROM users WHERE id = ?", result.lastID);
res.status(201).json(created);
} catch (err) {
if (err && err.code === "SQLITE_CONSTRAINT") {
return res.status(409).json({ error: "name already exists" });
}
next(err);
}
});
app.post("/auth/login", async (req, res, next) => {
try {
const { name, pass } = req.body || {};
if (!name || !pass) return res.status(400).json({ error: "name and pass are required" });
const nm = name.trim();
const row = await db.get("SELECT id, name, hash, role FROM users WHERE name = ?", nm);
if (!row) return res.status(401).json({ error: "invalid credentials" });
const hash = makeHash(nm, pass.trim());
if (hash !== row.hash) return res.status(401).json({ error: "invalid credentials" });
const token = signAccessToken({ id: row.id, name: row.name, role: row.role });
setAuthCookie(res, token);
// ensure CSRF cookie and return a fresh token to the client
const secret = ensureCsrfCookie(req, res);
const csrfToken = csrfTokenFromSecret(secret);
return res.json({
ok: true,
user: { id: row.id, name: row.name, role: row.role },
csrfToken, // your frontend can stash this in memory
});
} catch (err) {
next(err);
}
});
app.post("/auth/logout", (req, res) => {
clearAuthCookie(res);
res.clearCookie(CSRF_COOKIE, { path: "/" });
res.json({ ok: true });
});
app.get("/me", requireAuth, (req, res) => {
// Return minimal user info for the session
const { id, name, role } = req.user;
res.json({ id, name, role });
});
// Separate endpoint the frontend calls after mount or after login
app.get("/csrf", (req, res) => {
const secret = ensureCsrfCookie(req, res);
const csrfToken = csrfTokenFromSecret(secret);
res.json({ csrfToken });
});
// ---------- example protected APIs ----------
app.get("/api/users", requireAuth, async (req, res, next) => {
try {
// Example: only allow admins to list users
if (req.user.role !== "admin") return res.status(403).json({ error: "forbidden" });
const rows = await db.all("SELECT id, name, role FROM users ORDER BY id DESC");
res.json(rows);
} catch (err) {
next(err);
}
});
app.delete("/api/users/:id", requireAuth, async (req, res, next) => {
try {
if (req.user.role !== "admin") return res.status(403).json({ error: "forbidden" });
const id = Number(req.params.id);
if (!Number.isInteger(id) || id <= 0) {
return res.status(400).json({ error: "invalid id" });
}
const info = await db.run("DELETE FROM users WHERE id = ?", id);
if (info.changes === 0) return res.status(404).json({ error: "user not found" });
res.json({ ok: true, deletedId: id });
} catch (err) {
next(err);
}
});
// A tiny "demo" protected mutating route (needs both auth + CSRF)
app.post("/api/secret", requireAuth, (req, res) => {
res.json({ ok: true, msg: `Hi ${req.user.name}, your POST passed CSRF.` });
});
// ---------- errors ----------
app.use((err, _req, res, _next) => {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
});
// ---------- start ----------
app.listen(PORT, () => {
console.log(`API running on http://localhost:${PORT}`);
console.log(`CORS origin: ${ORIGIN}`);
});
// Used by the React gate (returns JSON so your client can branch UI)
app.get(
"/api/entitlement",
requireAuth,
requireEntitlement("admin"), // pick roles you consider entitled
(req, res) => {
console.log("b")
// you can include anything useful for the UI here
res.status(200).json({ ok: true, role: req.user.role });
}
);
// Used by Nginx auth_request to guard /assets/protected/**
// IMPORTANT: return only 200/401/403 (no body).
app.get(
"/authz",
requireAuthBare,
requireEntitlement("admin"),
(req, res) => res.sendStatus(200)
);
// Nginx Auth
function requireAuthBare(req, res, next) {
const token = req.cookies[COOKIE_NAME];
if (!token) return res.sendStatus(401);
try {
const payload = jwt.verify(token, JWT_SECRET);
req.user = payload;
next();
} catch {
return res.sendStatus(401);
}
}
function requireEntitlement(...allowedRoles) {
return (req, res, next) => {
// no user means not authenticated
if (!req.user) return res.sendStatus(401);
// if no roles provided, any authenticated user passes
if (allowedRoles.length === 0 || allowedRoles.includes(req.user.role)) {
return next();
}
return res.sendStatus(403);
};
}