diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..903d883 --- /dev/null +++ b/.env.example @@ -0,0 +1,28 @@ +# Copy to .env and fill in real values. +# NEVER commit .env. Use strong, unique secrets in production. + +PORT=3000 + +# PostgreSQL +DB_HOST=localhost +DB_PORT=5432 +DB_USER=replace_me +DB_PWD=replace_with_strong_password +DB_DATABASE=file_cabinet + +# Neo4j +GRAPH_DB_USER=replace_me +GRAPH_DB_PWD=replace_with_strong_password +GRAPH_DB_URI=neo4j://localhost:7687 +GRAPH_DB_NAME=neo4j + +# CORS allowlist (comma-separated). Empty disables all cross-origin requests. +CORS_ALLOWED_ORIGINS=http://localhost:5173 + +# At least 32 random characters. Generate with: openssl rand -base64 48 +JWT_SECRET=replace_with_long_random_string +JWT_EXPIRES_IN=86400 + +# Uploads +UPLOAD_DIR=./uploads +MAX_UPLOAD_SIZE_BYTES=5242880 diff --git a/API.md b/API.md index 803a1a0..f82b872 100644 --- a/API.md +++ b/API.md @@ -2,32 +2,62 @@ Base URL: `http://localhost:${PORT}`. Use `Authorization: Bearer ` or HttpOnly `fc_session_token` cookie on every endpoint except register/login. JSON uses `Content-Type: application/json`; upload routes use `multipart/form-data`. -| Method + path | Auth | Input | Result / policy | -|---|---:|---|---| -| `POST /auth/register` | no | JSON: `name`, `username`, `email`, `password` | `201 {id}`; strict fields; see password policy below | -| `POST /auth/login` | no | JSON: `email`, `password` | `200 {id,token,expires_at}`; sets `fc_session_token` HttpOnly cookie; `401` is generic | -| `GET /auth/me` | yes | no body/query | `200 {id,name,username,email}` session user profile | -| `GET /auth/verify` | yes | no body/query | `200 {id,name,username,email}` session verification endpoint | -| `GET /profiles/me` | yes | no body/query | `200 {id,name,username,profile_link}` for the token user | -| `PUT /profiles/me` | yes | multipart: optional `name`, `username`, `email`, `password`, `current_password`, file `image`, `remove_image=true\|false` | `200 {id,name,username,profile_link}`; registration-style rules on changed text fields; upload replaces picture; `remove_image=true` clears it; image + remove is invalid | +| Method + path | Auth | Input | Result / policy | +| --------------------------------------------- | ----------: | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `POST /auth/register` | no | JSON: `name`, `username`, `email`, `password` | `201 {id}`; `409` if username or email is already in use; strict fields; see password policy below | +| `POST /auth/login` | no | JSON: `email`, `password` | `200 {id,token,expires_at}`; sets `fc_session_token` HttpOnly cookie; `401` is generic | +| `GET /auth/me` | yes | no body/query | `200 {id,name,username,email}` session user profile | +| `GET /auth/verify` | yes | no body/query | `200 {id,name,username,email}` session verification endpoint | +| `POST /auth/logout` | yes | no body/query | `200 {message}`; deletes the current session and clears the cookie | +| `GET /profiles/me` | yes | no body/query | `200 {id,name,username,profile_link,private}` for the token user | +| `PUT /profiles/me` | yes | multipart: optional `name`, `username`, `email`, `password`, `current_password`, `private`, file `image`, `remove_image=true\|false` | `200 {id,name,username,profile_link,private}`; registration-style rules on changed text fields; upload replaces picture; `remove_image=true` clears it; image + remove is invalid | | `DELETE /profiles/me` | yes | JSON: `password` | `200 {message}`; removes posts/images, profile picture, SQL row, graph node; clears session cookie; `401` if password is wrong | -| `GET /profiles/:id` | yes | no body/query | `200 {id,name,username,profile_link}`; email/password are never exposed | +| `GET /profiles/:id` | yes | no body/query | `200 {id,name,username,profile_link,private}`; email/password are never exposed. Private accounts return only `{id,name,username}` to non-friends | | `GET /profiles/image/:filename` | yes | no body/query | Authenticated profile picture download | -| `GET /posts` | yes | no body/query | `200` all posts; ownership does not limit viewing | -| `GET /posts/me` | yes | no body/query | `200` only posts with `author_id = token.user_id`; each includes `author_username` | +| `GET /posts` | yes | query: optional `limit` (1–100, default 20), `offset` (default 0) | `200` visible posts (see privacy rules below), newest first; ownership does not limit viewing | +| `GET /posts/me` | yes | query: optional `limit` (1–100, default 20), `offset` (default 0) | `200` only posts with `author_id = token.user_id`, newest first; each includes `author_username` | +| `GET /posts/:id` | yes | no body/query | `200` single post with `{...post, comments: []}`; `404` if not found or not visible | | `GET /posts/image/:filename` | yes | no body/query | Authenticated image download | -| `POST /posts/create` | yes | multipart fields: `title`, `text`; optional file `image` | `201` post; `author_id` always comes from token | -| `PUT /posts/edit?id=` | yes + owner | multipart: optional `title`, `text`, `image`, `remove_image=true\|false` | `200` updated post; upload replaces image; `remove_image=true` clears it; image + remove is invalid | -| `DELETE /posts/delete?id=` | yes + owner | query: `id` only | `200`; deletes only matching `id AND author_id` and removes stored image | -| `POST /create_relationship?me=&them=` | yes | query: `me`, `them` only | `200`; `me` must equal token user ID | +| `POST /posts/like?id=` | yes | query: `id` only | `200 {message}`; idempotent; `404` if post not found or not visible; `400` if invalid id | +| `DELETE /posts/like?id=` | yes | query: `id` only | `200 {message}`; idempotent; `404` if post not found or not visible | +| `POST /posts/create` | yes | multipart fields: `title`, `text`; optional file `image` | `201` post; `author_id` always comes from token | +| `PUT /posts/edit?id=` | yes + owner | multipart: optional `title`, `text`, `image`, `remove_image=true\|false` | `200` updated post; upload replaces image; `remove_image=true` clears it; image + remove is invalid | +| `DELETE /posts/delete?id=` | yes + owner | query: `id` only | `200`; deletes only matching `id AND author_id` and removes stored image | +| `GET /friends` | yes | no body/query | `200` friend list: `{id,name,username,profile_link,private}` | +| `GET /friends/requests` | yes | no body/query | `200` pending incoming friend requests (people who requested you) | +| `POST /friends/request?to=` | yes | query: `to` only | `200 {message}`; `409` if already friends or a request exists; `404` if user not found | +| `POST /friends/accept?from=` | yes | query: `from` only | `200 {message}`; creates bidirectional `FRIENDS_WITH`; `404` if no pending request from that user | +| `POST /friends/decline?from=` | yes | query: `from` only | `200 {message}`; removes the request; `404` if no pending request from that user | +| `POST /friends/cancel?to=` | yes | query: `to` only | `200 {message}`; cancels an outgoing request; `404` if none exists | +| `DELETE /friends/remove?id=` | yes | query: `id` only | `200 {message}`; removes the friendship; `404` if not a friend | +| `GET /auth/sessions` | yes | no body/query | `200` session list (id, device_name, created_at, last_used_at, current) | +| `DELETE /auth/sessions` | yes | no body/query | `200` deletes every session except the current one | +| `DELETE /auth/sessions/:id` | yes | no body/query | `200` deletes a specific session; `404` if not found or not yours | -Post objects include `author_username` and `created_at` (the database creation timestamp), joined from `people.username`; the join is left-sided so an orphaned post is not silently omitted. +Post objects include `author_username` and `created_at` (the database creation timestamp), joined from `people.username`; the join is left-sided so an orphaned post is not silently omitted. `GET /posts/:id` additionally includes a `comments` field (currently an empty array, reserved for future use). Every post response also includes `like_count` (number of `LIKES` relationships in the graph database) and `liked_by_me` (whether the token user liked it). Likes are idempotent: liking an already-liked post or unliking a non-liked post still returns `200`. + +## Likes + +- Likes live in the graph database (Neo4j) as `(:Person)-[:LIKES]->(:Post)` relationships. +- Only posts the requester can see (active + not private-inaccessible) can be liked; others return `404`, so liking does not leak the existence of hidden posts. +- Creating a post also creates its `Post` node in the graph; soft-deleting a post removes the node and its likes; deleting an account removes all of the user's posts and likes from the graph. +- Old posts created before likes existed have no graph node yet; the first like creates one automatically (`MERGE`). + +## Privacy and friendship + +- Every profile has a `private` boolean (default `false`). Set it via `PUT /profiles/me` with `private=true|false`. +- Public accounts: all authenticated users can see their posts on `GET /posts` and `GET /posts/:id`, and their full profile via `GET /profiles/:id`. +- Private accounts: only the account owner and their `FRIENDS_WITH` connections in the graph database can see their posts. Non-friends get the post filtered out of the feed and a `404` on `GET /posts/:id`. +- Private accounts: `GET /profiles/:id` returns the full profile to the owner and friends only; non-friends get a limited `{id,name,username}` response (the `private` flag and `profile_link` are hidden). +- `GET /posts/me` always shows your own posts, private or not. +- Friendships live in the graph database (Neo4j) only. A request flow creates a `REQUESTED` relationship; accepting turns it into bidirectional `FRIENDS_WITH`. ## Input rules - Any undocumented body or query field returns `400`; do not send `author_id` to create posts. - Registration: `name` 1–100 chars; `username` 1–50, no whitespace; `email` 1–254, trimmed/lowercased, valid format, no whitespace, not disposable; `password` 1–128 and at least 12 chars with lower/upper/number/special, no username/email-local-part, common password, triple repeat, or obvious sequence. -- Profile update accepts only `name`, `username`, `email`, `password`, `current_password`, and `remove_image`, plus optional file field `image`; at least one profile field or picture change is required; changing `password` requires the current password and re-applies the registration password rules against the resulting username/email. +- Profile update accepts only `name`, `username`, `email`, `password`, `current_password`, `private`, and `remove_image`, plus optional file field `image`; at least one profile field or picture change is required; changing `password` requires the current password and re-applies the registration password rules against the resulting username/email. +- Friend routes accept only their documented query parameter (`to`, `from`, or `id`) and never accept a body. - Account deletion accepts only `password` (whitespace preserved, not trimmed); failures use `401 Invalid password`. - Login accepts only `email` and `password`; email is trimmed/lowercased; password is not trimmed or otherwise transformed (ordinary whitespace is significant). - Passwords, hashes, salts, JWTs, and database details must never be logged or exposed. @@ -48,7 +78,25 @@ curl -X PUT "http://localhost:3000/posts/edit?id=12" \ -F text='Updated body' -F remove_image=true ``` -Omit `image` and `remove_image` to keep the current image. Stored image URLs require the same Bearer token. +Omit `image` and `remove_image` to keep the current image. Stored image URLs require the same Bearer token. Uploaded files are validated both by declared `Content-Type` and by their file signature (magic bytes): a file whose bytes do not match the declared type is rejected with `400` and not stored. + +Image downloads obey the same visibility rules as the content they belong to: an image of a private/inactive post or a private profile returns `404` to non-friends (even if the URL is known or leaked). + +## Rate limiting + +All endpoints are rate-limited per IP: a strict limit (20 per 15 minutes) applies to `POST /auth/login`, `POST /auth/register`, and `DELETE /profiles/me`; all other endpoints share a general limit (300 per 15 minutes). Exceeding a limit returns `429`. + +## Session management + +Login automatically creates a session (tracked by `user-agent`). Each session gets its own JWT containing the session `id` (`jti`) and a `token_version` (`tvr`). + +- **Password change** invalidates all sessions — every device must log in again. +- **`GET /auth/sessions`** lists your active sessions with a `current` boolean marker. +- **`DELETE /auth/sessions`** logs out all other devices (keeps the current one); `400` if the current session cannot be identified. +- **`DELETE /auth/sessions/:id`** logs out a specific device by session ID. +- **`POST /auth/logout`** logs out the current device (deletes its session row and clears the cookie). + +The `current` field in the session list tells you which session is making the request. Profile picture (same file rules as post images): diff --git a/README.md b/README.md index 34040b8..81737ff 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Filing Cabinet API -Node.js/Express API for accounts, JWT-authenticated actions, relationships, and posts. +Node.js/Express API for accounts, JWT-authenticated actions, friendships, and posts. ## Run @@ -49,9 +49,9 @@ Authenticated clients can read profiles through `GET /profiles/me` or `GET /prof - Registration/login validation and password rules are defined in [AUTH_INPUT_POLICY.md](AUTH_INPUT_POLICY.md). - Post creation always uses `author_id` from the verified JWT; clients must not send `author_id`. - Post edit/delete require that the JWT user owns the post. -- `/posts` is visible to any authenticated user; `/posts/me` filters by JWT `user_id`. -- Post listings include `author_username` and `created_at`; profile responses expose `id`, `name`, `username`, and `profile_link` (nullable). -- Relationship creation requires `me` to equal the JWT user ID. +- `/posts` is visible to any authenticated user; `/posts/me` filters by JWT `user_id`. Posts from private accounts appear only to the owner and their friends. +- Post listings include `author_username` and `created_at`; profile responses expose `id`, `name`, `username`, `profile_link` (nullable), and `private`. +- Friendships live in the graph database: send a request with `POST /friends/request`, accept with `POST /friends/accept`, manage via `GET /friends` and `DELETE /friends/remove`. - Uploads accept only JPEG, PNG, GIF, and WebP, one file named `image`, up to `MAX_UPLOAD_SIZE_BYTES` (default 5 MiB). Files receive random names and are stored under `UPLOAD_DIR`. - Registration rejects disposable email addresses and weak/reused-pattern passwords. Login failures use the generic `Invalid email or password` response. - Do not expose database errors or stack traces to clients. diff --git a/app.js b/app.js index 5046968..fd13841 100644 --- a/app.js +++ b/app.js @@ -1,8 +1,10 @@ const express = require("express"); const cors = require("cors"); +const helmet = require("helmet"); const app = express(); const dotenv = require("dotenv"); const { authenticateToken } = require("./middleware/authenticate_token"); +const { authLimiter, globalLimiter } = require("./middleware/rate_limit"); require("dotenv").config(); const allowedOrigins = (process.env.CORS_ALLOWED_ORIGINS || "") @@ -10,9 +12,15 @@ const allowedOrigins = (process.env.CORS_ALLOWED_ORIGINS || "") .map((origin) => origin.trim()) .filter(Boolean); -// Apply configured CORS origins to every endpoint, including preflight requests. +// Security headers and CORS apply to every endpoint, including preflight requests. +app.use(helmet()); app.use(cors({ origin: allowedOrigins, credentials: true })); app.use(express.json()); +// Brute-force protection: a strict limit on credential endpoints, a general +// limit on everything else. +app.use(globalLimiter); +app.use("/auth/login", authLimiter); +app.use("/auth/register", authLimiter); // People routes const CreatePersonRoute = require("./features/people/REGISTER_people"); @@ -27,23 +35,28 @@ app.use("/auth/verify", VerifyAuthRoute); // Every route below this point requires a valid JWT or session cookie. Registration and login stay public. app.use(authenticateToken); -// Relation routes -const CreateRelationRoute = require("./features/relations/CREATE_friendship"); - -app.use("/create_relationship", CreateRelationRoute); - // Post routes const CreatePostRoute = require("./features/posts/CREATE_post"); const DeletePostRoute = require("./features/posts/DELETE_post"); const GetPostsRoute = require("./features/posts/GET_posts"); const EditPostRoute = require("./features/posts/EDIT_post"); const GetProfileRoute = require("./features/people/GET_profile"); +const ManageSessionsRoute = require("./features/people/MANAGE_sessions"); +const GetPostDetailRoute = require("./features/posts/GET_post_detail"); +const FriendsRoute = require("./features/relations/FRIENDS_people"); +const LogoutAuthRoute = require("./features/people/LOGOUT_auth"); +const LikePostRoute = require("./features/posts/LIKE_post"); app.use("/posts", GetPostsRoute); +app.use("/posts/like", LikePostRoute); app.use("/posts/create", CreatePostRoute); app.use("/posts/delete", DeletePostRoute); app.use("/posts/edit", EditPostRoute); app.use("/profiles", GetProfileRoute); +app.use("/auth/sessions", ManageSessionsRoute); +app.use("/posts", GetPostDetailRoute); +app.use("/friends", FriendsRoute); +app.use("/auth/logout", LogoutAuthRoute); app.listen(process.env.PORT, () => { console.log(`Server draait op port ${process.env.PORT}`); diff --git a/features/people/GET_profile.js b/features/people/GET_profile.js index deacf36..dd985fd 100644 --- a/features/people/GET_profile.js +++ b/features/people/GET_profile.js @@ -18,6 +18,9 @@ const { removeUploadedProfileFile, uploadDirectory, } = require("../../middleware/post_upload"); +const { areFriends } = require("../relations/friend_graph"); +const { authLimiter } = require("../../middleware/rate_limit"); +const { deletePostsByAuthor } = require("../posts/post_graph"); const scrypt = promisify(crypto.scrypt); @@ -49,16 +52,43 @@ function resolveProfileId(req) { return id; } +function isPositiveInteger(value) { + const id = Number(value); + return Number.isInteger(id) && id > 0; +} + +function limitedProfile(profile) { + return { + id: profile.id, + name: profile.name, + username: profile.username, + }; +} + async function getProfile(req, res) { const id = resolveProfileId(req); + if (id !== req.user.id && !isPositiveInteger(id)) { + return res.status(400).send("Invalid profile id"); + } + try { const { rows } = await pool.query( - "SELECT id, name, username, profile_link FROM people WHERE id = $1", + "SELECT id, name, username, profile_link, private FROM people WHERE id = $1", [id], ); if (rows.length === 0) return res.status(404).send("Profile not found"); - return res.status(200).json(rows[0]); + + const profile = rows[0]; + const targetId = Number(id); + if ( + profile.private && + targetId !== req.user.id && + !(await areFriends(req.user.id, targetId)) + ) { + return res.status(200).json(limitedProfile(profile)); + } + return res.status(200).json(profile); } catch (err) { console.error("profile query failed", { message: err.message, @@ -132,6 +162,7 @@ async function updateProfile(req, res) { if (update.name !== undefined) addField("name", update.name); if (update.username !== undefined) addField("username", update.username); if (update.email !== undefined) addField("email", update.email); + if (update.private !== undefined) addField("private", update.private); if (update.password !== undefined) { addField("password", await hashPassword(update.password)); } @@ -142,7 +173,7 @@ async function updateProfile(req, res) { let rows; try { ({ rows } = await pool.query( - `UPDATE people SET ${fields.join(", ")} WHERE id = $${values.length} RETURNING id, name, username, profile_link`, + `UPDATE people SET ${fields.join(", ")} WHERE id = $${values.length} RETURNING id, name, username, profile_link, private`, values, )); } catch (err) { @@ -156,6 +187,11 @@ async function updateProfile(req, res) { }); } + if (update.password !== undefined) { + await pool.query("UPDATE people SET token_version = token_version + 1 WHERE id = $1", [req.user.id]); + await pool.query("DELETE FROM sessions WHERE user_id = $1", [req.user.id]); + } + if (update.name !== undefined || update.username !== undefined) { await driver.executeQuery( "MATCH (p:Person {db_id: $db_id}) SET p.name = $name, p.username = $username", @@ -207,9 +243,11 @@ async function deleteAccount(req, res) { } await removeImageLink(existing.rows[0].profile_link); - await pool.query("DELETE FROM posts WHERE author_id = $1", [req.user.id]); + await pool.query("DELETE FROM sessions WHERE user_id = $1", [req.user.id]); + await pool.query("UPDATE posts SET active = false WHERE author_id = $1", [req.user.id]); await pool.query("DELETE FROM people WHERE id = $1", [req.user.id]); + await deletePostsByAuthor(req.user.id); await driver.executeQuery( "MATCH (p:Person {db_id: $db_id}) DETACH DELETE p", { db_id: req.user.id }, @@ -237,12 +275,36 @@ async function deleteAccount(req, res) { router.get( "/image/:filename", strictInput(), - (req, res) => { + async (req, res) => { const filename = path.basename(req.params.filename); if (filename !== req.params.filename) return res.status(404).end(); - res.sendFile(filename, { root: uploadDirectory }, (err) => { - if (err && !res.headersSent) res.status(err.statusCode === 404 ? 404 : 500).end(); - }); + try { + const { rows } = await pool.query( + "SELECT id, private FROM people WHERE profile_link = $1", + [`/profiles/image/${filename}`], + ); + if (rows.length === 0) return res.status(404).send("Image not found"); + const profile = rows[0]; + if ( + profile.private && + Number(profile.id) !== req.user.id && + !(await areFriends(req.user.id, profile.id)) + ) { + return res.status(404).send("Image not found"); + } + res.set("Cache-Control", "private, no-store"); + res.sendFile(filename, { root: uploadDirectory }, (err) => { + if (err && !res.headersSent) res.status(err.statusCode === 404 ? 404 : 500).end(); + }); + } catch (err) { + console.error("profile image query failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Image could not be retrieved, request failed"); + } }, ); @@ -252,7 +314,7 @@ router.put( "/me", handleProfileUpload, strictInput({ - body: ["name", "username", "email", "password", "current_password", "remove_image"], + body: ["name", "username", "email", "password", "current_password", "remove_image", "private"], cleanupUploadedFile: true, }), sanitizeProfileUpdate, @@ -260,6 +322,7 @@ router.put( ); router.delete( "/me", + authLimiter, strictInput({ body: ["password"] }), sanitizeAccountDelete, deleteAccount, diff --git a/features/people/LOGIN_people.js b/features/people/LOGIN_people.js index a0076f9..717e0f6 100644 --- a/features/people/LOGIN_people.js +++ b/features/people/LOGIN_people.js @@ -9,15 +9,20 @@ const { signToken } = require('../../middleware/authenticate_token'); const scrypt = promisify(crypto.scrypt); +// Fixed salt for unknown emails: the scrypt work is still performed so the +// response time does not reveal whether the email address exists. +const DUMMY_SALT = '00000000000000000000000000000000'; + async function login(req, res) { try { const { email, password } = req.loginInput; const { rows } = await pool.query( - 'SELECT id, password FROM people WHERE email = $1', + 'SELECT id, password, token_version FROM people WHERE email = $1', [email] ); if (rows.length === 0) { + await scrypt(password, DUMMY_SALT, 64); res.status(401).send('Invalid email or password'); return; } @@ -34,7 +39,17 @@ async function login(req, res) { return; } - const { token, expiresAt } = signToken(rows[0].id); + const sessionId = crypto.randomUUID(); + const deviceName = (req.headers['user-agent'] || 'unknown').slice(0, 255); + await pool.query( + 'INSERT INTO sessions (id, user_id, device_name) VALUES ($1, $2, $3)', + [sessionId, rows[0].id, deviceName], + ); + + const { token, expiresAt } = signToken(rows[0].id, { + jti: sessionId, + tokenVersion: rows[0].token_version, + }); res.cookie('fc_session_token', token, { httpOnly: true, secure: true, diff --git a/features/people/LOGOUT_auth.js b/features/people/LOGOUT_auth.js new file mode 100644 index 0000000..a1178eb --- /dev/null +++ b/features/people/LOGOUT_auth.js @@ -0,0 +1,29 @@ +const express = require("express"); +const router = express.Router(); +const pool = require("../../db"); +const { strictInput } = require("../../middleware/strict_input"); + +async function logout(req, res) { + try { + if (req.user.session_id) { + await pool.query( + "DELETE FROM sessions WHERE id = $1 AND user_id = $2", + [req.user.session_id, req.user.id], + ); + } + res.clearCookie("fc_session_token", { + httpOnly: true, + secure: true, + sameSite: "Strict", + path: "/", + }); + return res.status(200).json({ message: "Logged out" }); + } catch (err) { + console.error("logout failed", { message: err.message, code: err.code }); + return res.status(500).send("Logout failed, request could not be completed"); + } +} + +router.post("/", strictInput(), logout); + +module.exports = router; diff --git a/features/people/MANAGE_sessions.js b/features/people/MANAGE_sessions.js new file mode 100644 index 0000000..355ce14 --- /dev/null +++ b/features/people/MANAGE_sessions.js @@ -0,0 +1,79 @@ +const express = require("express"); +const router = express.Router(); +const pool = require("../../db"); +const { strictInput } = require("../../middleware/strict_input"); + +async function listSessions(req, res) { + try { + const { rows } = await pool.query( + `SELECT id, device_name, created_at, last_used_at + FROM sessions + WHERE user_id = $1 + ORDER BY last_used_at DESC`, + [req.user.id], + ); + const sessions = rows.map((s) => ({ + ...s, + current: s.id === req.user.session_id, + })); + return res.status(200).json(sessions); + } catch (err) { + console.error("list sessions failed", { + message: err.message, + code: err.code, + }); + return res.status(500).send("Sessions could not be retrieved, request failed"); + } +} + +async function deleteSession(req, res) { + try { + const { id } = req.params; + const uuidPattern = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + if (!uuidPattern.test(id)) { + return res.status(400).send("Invalid session id"); + } + const result = await pool.query( + "DELETE FROM sessions WHERE id = $1 AND user_id = $2 RETURNING id", + [id, req.user.id], + ); + if (result.rowCount === 0) { + return res.status(404).send("Session not found or does not belong to you"); + } + return res.status(200).json({ message: "Session deleted" }); + } catch (err) { + console.error("delete session failed", { + message: err.message, + code: err.code, + }); + return res.status(500).send("Session could not be deleted, request failed"); + } +} + +async function deleteOtherSessions(req, res) { + if (!req.user.session_id) { + return res + .status(400) + .send("Current session could not be identified, please log in again"); + } + try { + await pool.query( + "DELETE FROM sessions WHERE user_id = $1 AND id != $2", + [req.user.id, req.user.session_id], + ); + return res.status(200).json({ message: "Other sessions deleted" }); + } catch (err) { + console.error("delete other sessions failed", { + message: err.message, + code: err.code, + }); + return res.status(500).send("Sessions could not be deleted, request failed"); + } +} + +router.get("/", strictInput(), listSessions); +router.delete("/", strictInput(), deleteOtherSessions); +router.delete("/:id", strictInput(), deleteSession); + +module.exports = router; diff --git a/features/people/REGISTER_people.js b/features/people/REGISTER_people.js index 42fb241..6c22a5f 100644 --- a/features/people/REGISTER_people.js +++ b/features/people/REGISTER_people.js @@ -62,6 +62,17 @@ async function create_people(req, res) { const person = req.person; let db_id; + const existing = await pool + .query('SELECT 1 FROM people WHERE username = $1 OR email = $2 LIMIT 1', [ + person.username, + person.email, + ]) + .catch(() => null); + if (existing && existing.rowCount > 0) { + res.status(409).send('Username or email is already in use'); + return; + } + try { db_id = await insert_db( person.name, @@ -71,6 +82,10 @@ async function create_people(req, res) { ); } catch (err) { + if (err.code === '23505') { + res.status(409).send('Username or email is already in use'); + return; + } res.status(500).send('Data was not pushed to database, request failed'); return; } @@ -80,6 +95,9 @@ async function create_people(req, res) { res.status(201).json({ id: db_id }); } catch (err) { + // Compensate the SQL insert so the user does not exist in one database + // but not the other. + await pool.query('DELETE FROM people WHERE id = $1', [db_id]).catch(() => {}); res.status(500).send('Data was not pushed to graph database, request failed'); } }; diff --git a/features/posts/CREATE_post.js b/features/posts/CREATE_post.js index e8e0972..32b13fb 100644 --- a/features/posts/CREATE_post.js +++ b/features/posts/CREATE_post.js @@ -8,6 +8,7 @@ const { imageLinkForFile, removeUploadedFile, } = require("../../middleware/post_upload"); +const driver = require("../../graph_db"); async function create_post(req, res) { try { @@ -23,7 +24,22 @@ async function create_post(req, res) { "WITH created AS (INSERT INTO posts (title, text, author_id, image_link) VALUES ($1, $2, $3, $4) RETURNING id, title, text, author_id, image_link, created_at) SELECT created.*, people.username AS author_username FROM created LEFT JOIN people ON people.id = created.author_id", [title, text, author_id, imageLink], ); - res.status(201).json(rows[0]); + const post = rows[0]; + try { + await driver.executeQuery( + "CREATE (p:Post {db_id: $db_id, author_id: $author_id, created_at: datetime()})", + { db_id: Number(post.id), author_id: Number(post.author_id) }, + { database: process.env.GRAPH_DB_NAME }, + ); + } catch (graphErr) { + await pool.query("DELETE FROM posts WHERE id = $1", [post.id]).catch(() => {}); + throw graphErr; + } + res.status(201).json({ + ...post, + like_count: 0, + liked_by_me: false, + }); } catch (err) { await removeUploadedFile(req.file); throw err; diff --git a/features/posts/DELETE_post.js b/features/posts/DELETE_post.js index 681781a..c9e426e 100644 --- a/features/posts/DELETE_post.js +++ b/features/posts/DELETE_post.js @@ -4,18 +4,20 @@ const pool = require("../../db"); const { strictInput } = require("../../middleware/strict_input"); const { authenticateToken } = require("../../middleware/authenticate_token"); const { removeImageLink } = require("../../middleware/post_upload"); +const { deletePostNode } = require("./post_graph"); async function delete_post(req, res) { try { const id = req.query.id; const result = await pool.query( - "DELETE FROM posts WHERE id = $1 AND author_id = $2 RETURNING id, image_link", + "UPDATE posts SET active = false WHERE id = $1 AND author_id = $2 RETURNING id, image_link", [id, req.user.id], ); if (result.rowCount === 0) { return res.status(404).send("Post not found or does not belong to you"); } await removeImageLink(result.rows[0].image_link); + await deletePostNode(result.rows[0].id); res.status(200).json({ message: "Post Deleted", }); diff --git a/features/posts/EDIT_post.js b/features/posts/EDIT_post.js index 9cbdc1f..270edc6 100644 --- a/features/posts/EDIT_post.js +++ b/features/posts/EDIT_post.js @@ -9,6 +9,7 @@ const { removeImageLink, removeUploadedFile, } = require("../../middleware/post_upload"); +const { likeDataForPosts } = require("./post_graph"); async function editPost(req, res) { const id = req.query.id; @@ -33,7 +34,7 @@ async function editPost(req, res) { try { const existing = await pool.query( - "SELECT id, image_link FROM posts WHERE id = $1 AND author_id = $2", + "SELECT id, image_link FROM posts WHERE id = $1 AND author_id = $2 AND active = true", [id, req.user.id], ); if (existing.rowCount === 0) { @@ -53,12 +54,13 @@ async function editPost(req, res) { if (text !== undefined) addField("text", text); if (req.file) addField("image_link", imageLinkForFile(req.file)); if (removeImage) addField("image_link", null); + fields.push("edited_last = NOW()"); values.push(id, req.user.id); let updated; try { updated = await pool.query( - `WITH updated AS (UPDATE posts SET ${fields.join(", ")} WHERE id = $${values.length - 1} AND author_id = $${values.length} RETURNING id, title, text, author_id, image_link, created_at) SELECT updated.*, people.username AS author_username FROM updated LEFT JOIN people ON people.id = updated.author_id`, + `WITH updated AS (UPDATE posts SET ${fields.join(", ")} WHERE id = $${values.length - 1} AND author_id = $${values.length} RETURNING id, title, text, author_id, image_link, created_at, edited_last) SELECT updated.*, people.username AS author_username FROM updated LEFT JOIN people ON people.id = updated.author_id`, values, ); } catch (err) { @@ -71,7 +73,14 @@ async function editPost(req, res) { console.error("old post image could not be removed", { message: err.message }); }); } - return res.status(200).json(updated.rows[0]); + const likeData = (await likeDataForPosts(req.user.id, [updated.rows[0].id])).get( + Number(updated.rows[0].id), + ) ?? { like_count: 0, liked_by_me: false }; + return res.status(200).json({ + ...updated.rows[0], + like_count: likeData.like_count, + liked_by_me: likeData.liked_by_me, + }); } catch (err) { await removeUploadedFile(req.file); console.error("database query failed", { diff --git a/features/posts/GET_post_detail.js b/features/posts/GET_post_detail.js new file mode 100644 index 0000000..8b1278b --- /dev/null +++ b/features/posts/GET_post_detail.js @@ -0,0 +1,58 @@ +const express = require("express"); +const router = express.Router(); +const pool = require("../../db"); +const { strictInput } = require("../../middleware/strict_input"); +const { areFriends } = require("../relations/friend_graph"); +const { likeDataForPosts } = require("./post_graph"); + +async function getPostDetail(req, res) { + try { + const { id } = req.params; + const postId = Number(id); + if (!Number.isInteger(postId) || postId <= 0) { + return res.status(400).send("Invalid post id"); + } + const { rows } = await pool.query( + `SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at, people.private AS author_private + FROM posts p + LEFT JOIN people ON people.id = p.author_id + WHERE p.id = $1 AND p.active = true`, + [postId], + ); + if (rows.length === 0) { + return res.status(404).send("Post not found"); + } + const post = rows[0]; + if ( + post.author_private && + Number(post.author_id) !== req.user.id && + !(await areFriends(req.user.id, post.author_id)) + ) { + return res.status(404).send("Post not found"); + } + const { author_private, ...publicPost } = post; + const likeData = (await likeDataForPosts(req.user.id, [post.id])).get( + Number(post.id), + ) ?? { like_count: 0, liked_by_me: false }; + return res + .status(200) + .json({ + ...publicPost, + comments: [], + like_count: likeData.like_count, + liked_by_me: likeData.liked_by_me, + }); + } catch (err) { + console.error("post detail query failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Post could not be retrieved, request failed"); + } +} + +router.get("/:id", strictInput(), getPostDetail); + +module.exports = router; diff --git a/features/posts/GET_posts.js b/features/posts/GET_posts.js index 641a573..ff85cf9 100644 --- a/features/posts/GET_posts.js +++ b/features/posts/GET_posts.js @@ -4,16 +4,80 @@ const pool = require("../../db"); const { strictInput } = require("../../middleware/strict_input"); const { authenticateToken } = require("../../middleware/authenticate_token"); const { uploadDirectory } = require("../../middleware/post_upload"); +const { getFriendIdsAmong, areFriends } = require("../relations/friend_graph"); +const { likeDataForPosts } = require("./post_graph"); const path = require("path"); +function parsePagination(req) { + const { limit: limitRaw, offset: offsetRaw } = req.query; + if (limitRaw === undefined && offsetRaw === undefined) { + return { limit: 20, offset: 0 }; + } + const limit = limitRaw === undefined ? 20 : Number(limitRaw); + const offset = offsetRaw === undefined ? 0 : Number(offsetRaw); + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { + return { error: "limit must be an integer between 1 and 100" }; + } + if (!Number.isInteger(offset) || offset < 0) { + return { error: "offset must be a non-negative integer" }; + } + return { limit, offset }; +} + async function getPosts(req, res, ownOnly) { + const pagination = parsePagination(req); + if (pagination.error) return res.status(400).send(pagination.error); + try { - const query = ownOnly - ? "SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at FROM posts p LEFT JOIN people ON people.id = p.author_id WHERE p.author_id = $1" - : "SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at FROM posts p LEFT JOIN people ON people.id = p.author_id"; - const values = ownOnly ? [req.user.id] : []; + const values = []; + const conditions = ["p.active = true"]; + + if (ownOnly) { + conditions.push(`p.author_id = $${values.length + 1}`); + values.push(req.user.id); + } else { + const visible = [`people.private = false`, `p.author_id = $${values.length + 1}`]; + values.push(req.user.id); + + const { rows } = await pool.query( + `SELECT DISTINCT p.author_id FROM posts p + JOIN people ON people.id = p.author_id + WHERE p.active = true AND people.private = true`, + ); + const privateAuthorIds = rows.map((row) => Number(row.author_id)); + if (privateAuthorIds.length > 0) { + const friendIds = await getFriendIdsAmong(req.user.id, privateAuthorIds); + if (friendIds.size > 0) { + visible.push(`p.author_id = ANY($${values.length + 1})`); + values.push([...friendIds]); + } + } + + conditions.push(`(${visible.join(" OR ")})`); + } + + const where = conditions.join(" AND "); + const query = `SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at + FROM posts p + LEFT JOIN people ON people.id = p.author_id + WHERE ${where} + ORDER BY p.created_at DESC + LIMIT $${values.length + 1} OFFSET $${values.length + 2}`; + values.push(pagination.limit, pagination.offset); + const { rows } = await pool.query(query, values); - res.status(200).json(rows); + + const likeData = await likeDataForPosts( + req.user.id, + rows.map((row) => row.id), + ); + const posts = rows.map((row) => ({ + ...row, + like_count: likeData.get(Number(row.id))?.like_count ?? 0, + liked_by_me: likeData.get(Number(row.id))?.liked_by_me ?? false, + })); + + res.status(200).json(posts); } catch (err) { console.error("database query failed", { message: err.message, @@ -30,26 +94,53 @@ router.get( "/image/:filename", authenticateToken, strictInput(), - (req, res) => { + async (req, res) => { const filename = path.basename(req.params.filename); if (filename !== req.params.filename) return res.status(404).end(); - res.sendFile(filename, { root: uploadDirectory }, (err) => { - if (err && !res.headersSent) res.status(err.statusCode === 404 ? 404 : 500).end(); - }); + try { + const { rows } = await pool.query( + `SELECT p.author_id, people.private AS author_private + FROM posts p + LEFT JOIN people ON people.id = p.author_id + WHERE p.image_link = $1 AND p.active = true`, + [`/posts/image/${filename}`], + ); + if (rows.length === 0) return res.status(404).send("Image not found"); + const post = rows[0]; + if ( + post.author_private && + Number(post.author_id) !== req.user.id && + !(await areFriends(req.user.id, post.author_id)) + ) { + return res.status(404).send("Image not found"); + } + res.set("Cache-Control", "private, no-store"); + res.sendFile(filename, { root: uploadDirectory }, (err) => { + if (err && !res.headersSent) res.status(err.statusCode === 404 ? 404 : 500).end(); + }); + } catch (err) { + console.error("post image query failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Image could not be retrieved, request failed"); + } }, ); router.get( "/me", authenticateToken, - strictInput(), + strictInput({ query: ["limit", "offset"] }), (req, res) => getPosts(req, res, true), ); router.get( "/", authenticateToken, - strictInput(), + strictInput({ query: ["limit", "offset"] }), (req, res) => getPosts(req, res, false), ); diff --git a/features/posts/LIKE_post.js b/features/posts/LIKE_post.js new file mode 100644 index 0000000..d441059 --- /dev/null +++ b/features/posts/LIKE_post.js @@ -0,0 +1,72 @@ +const express = require("express"); +const router = express.Router(); +const pool = require("../../db"); +const { strictInput } = require("../../middleware/strict_input"); +const { authenticateToken } = require("../../middleware/authenticate_token"); +const { areFriends } = require("../relations/friend_graph"); +const { likePost, unlikePost } = require("./post_graph"); + +async function getVisiblePostId(req) { + const postId = Number(req.query.id); + if (!Number.isInteger(postId) || postId <= 0) { + return { error: 400 }; + } + const { rows } = await pool.query( + `SELECT p.id, p.author_id, people.private AS author_private + FROM posts p + LEFT JOIN people ON people.id = p.author_id + WHERE p.id = $1 AND p.active = true`, + [postId], + ); + if (rows.length === 0) { + return { error: 404 }; + } + const post = rows[0]; + if ( + post.author_private && + Number(post.author_id) !== req.user.id && + !(await areFriends(req.user.id, post.author_id)) + ) { + return { error: 404 }; + } + return { postId: Number(post.id) }; +} + +async function handleLike(req, res, like) { + try { + const { postId, error } = await getVisiblePostId(req); + if (error === 400) return res.status(400).send("Invalid post id"); + if (error === 404) return res.status(404).send("Post not found"); + + if (like) { + await likePost(req.user.id, postId); + return res.status(200).json({ message: "Post liked" }); + } + await unlikePost(req.user.id, postId); + return res.status(200).json({ message: "Post unliked" }); + } catch (err) { + console.error(like ? "like failed" : "unlike failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Request could not be completed"); + } +} + +router.post( + "/", + authenticateToken, + strictInput({ query: ["id"] }), + (req, res) => handleLike(req, res, true), +); + +router.delete( + "/", + authenticateToken, + strictInput({ query: ["id"] }), + (req, res) => handleLike(req, res, false), +); + +module.exports = router; diff --git a/features/posts/post_graph.js b/features/posts/post_graph.js new file mode 100644 index 0000000..0f8e093 --- /dev/null +++ b/features/posts/post_graph.js @@ -0,0 +1,72 @@ +const driver = require("../../graph_db"); +const { graphIdToNumber } = require("../relations/friend_graph"); + +const GRAPH = { database: process.env.GRAPH_DB_NAME }; + +async function likePost(userId, postId) { + const { records } = await driver.executeQuery( + `MATCH (me:Person {db_id: $me}) + MERGE (p:Post {db_id: $postId}) + MERGE (me)-[l:LIKES]->(p) + SET l.created_at = coalesce(l.created_at, datetime()) + RETURN me`, + { me: Number(userId), postId: Number(postId) }, + GRAPH, + ); + return records.length > 0; +} + +async function unlikePost(userId, postId) { + await driver.executeQuery( + `MATCH (me:Person {db_id: $me})-[l:LIKES]->(p:Post {db_id: $postId}) + DELETE l`, + { me: Number(userId), postId: Number(postId) }, + GRAPH, + ); +} + +async function likeDataForPosts(userId, postIds) { + const ids = postIds.map(Number); + if (ids.length === 0) return new Map(); + const { records } = await driver.executeQuery( + `MATCH (p:Post) WHERE p.db_id IN $ids + OPTIONAL MATCH (p)<-[l:LIKES]-(:Person) + WITH p, count(l) AS like_count + OPTIONAL MATCH (me:Person {db_id: $me})-[:LIKES]->(p) + RETURN p.db_id AS id, like_count, count(me) > 0 AS liked_by_me`, + { ids, me: Number(userId) }, + GRAPH, + ); + const result = new Map(); + for (const record of records) { + result.set(graphIdToNumber(record.get("id")), { + like_count: Number(record.get("like_count")), + liked_by_me: Boolean(record.get("liked_by_me")), + }); + } + return result; +} + +async function deletePostNode(postId) { + await driver.executeQuery( + "MATCH (p:Post {db_id: $postId}) DETACH DELETE p", + { postId: Number(postId) }, + GRAPH, + ); +} + +async function deletePostsByAuthor(authorId) { + await driver.executeQuery( + "MATCH (p:Post {author_id: $authorId}) DETACH DELETE p", + { authorId: Number(authorId) }, + GRAPH, + ); +} + +module.exports = { + likePost, + unlikePost, + likeDataForPosts, + deletePostNode, + deletePostsByAuthor, +}; diff --git a/features/relations/CREATE_friendship.js b/features/relations/CREATE_friendship.js deleted file mode 100644 index cd17c38..0000000 --- a/features/relations/CREATE_friendship.js +++ /dev/null @@ -1,32 +0,0 @@ -const express = require("express"); -const router = express.Router(); -var driver = require("../../graph_db"); -const { strictInput } = require('../../middleware/strict_input'); - -async function create_friendship(req, res) { - try { - const me = req.query.me; - const them = req.query.them; - if (String(req.user.id) !== String(me)) { - return res.status(403).send("You can only create relationships as yourself"); - } - const { records } = await driver.executeQuery( - "MATCH (m:Person {db_id: $me}) MATCH (t:Person {db_id: $them}) CREATE (m)-[:FRIENDS_WITH]-> (t) CREATE (t)-[:FRIENDS_WITH]-> (m)", - { me: me, them: them }, - { database: process.env.GRAPH_DB_NAME }, - ); - res.status(200).send("Relationship has been created"); - } catch (err) { - console.error("database query failed", { - message: err.message, - code: err.code, - detail: err.detail, - hint: err.hint, - stack: err.stack, - }); - res.status(500).send("Relationship was not created, request failed"); - } -} - -router.post("/", strictInput({ query: ['me', 'them'] }), create_friendship); -module.exports = router; diff --git a/features/relations/FRIENDS_people.js b/features/relations/FRIENDS_people.js new file mode 100644 index 0000000..692c50b --- /dev/null +++ b/features/relations/FRIENDS_people.js @@ -0,0 +1,241 @@ +const express = require("express"); +const router = express.Router(); +const pool = require("../../db"); +const driver = require("../../graph_db"); +const { strictInput } = require("../../middleware/strict_input"); +const { authenticateToken } = require("../../middleware/authenticate_token"); +const { graphIdToNumber } = require("./friend_graph"); + +const GRAPH = { database: process.env.GRAPH_DB_NAME }; + +function validId(value) { + return Number.isInteger(value) && value > 0; +} + +async function personIdsFromGraph(records) { + return records.map((record) => graphIdToNumber(record.get("id"))); +} + +async function personDetails(ids) { + if (ids.length === 0) return []; + const { rows } = await pool.query( + "SELECT id, name, username, profile_link, private FROM people WHERE id = ANY($1) ORDER BY name", + [ids], + ); + return rows; +} + +async function sendRequest(req, res) { + const me = Number(req.user.id); + const to = Number(req.query.to); + if (!validId(to)) { + return res.status(400).send("Invalid user id"); + } + if (me === to) { + return res.status(400).send("You cannot send a friend request to yourself"); + } + + try { + const target = await pool.query("SELECT id FROM people WHERE id = $1", [to]); + if (target.rowCount === 0) { + return res.status(404).send("User not found"); + } + + const result = await driver.executeQuery( + `MATCH (me:Person {db_id: $me}), (them:Person {db_id: $them}) + WHERE NOT EXISTS((me)-[:FRIENDS_WITH]-(them)) + AND NOT EXISTS((me)-[:REQUESTED]->(them)) + AND NOT EXISTS((them)-[:REQUESTED]->(me)) + CREATE (me)-[:REQUESTED {created_at: datetime()}]->(them) + RETURN me`, + { me, them: to }, + GRAPH, + ); + if (result.records.length === 0) { + return res.status(409).send("Request already exists or you are already friends"); + } + return res.status(200).json({ message: "Friend request sent" }); + } catch (err) { + console.error("friend request failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Friend request was not sent, request failed"); + } +} + +async function acceptRequest(req, res) { + const me = Number(req.user.id); + const from = Number(req.query.from); + if (!validId(from)) { + return res.status(400).send("Invalid user id"); + } + + try { + const result = await driver.executeQuery( + `MATCH (f:Person {db_id: $from})-[r:REQUESTED]->(me:Person {db_id: $me}) + DELETE r + CREATE (f)-[:FRIENDS_WITH]->(me) + CREATE (me)-[:FRIENDS_WITH]->(f) + RETURN f`, + { me, from }, + GRAPH, + ); + if (result.records.length === 0) { + return res.status(404).send("No pending friend request from this user"); + } + return res.status(200).json({ message: "Friend request accepted" }); + } catch (err) { + console.error("friend request accept failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Friend request was not accepted, request failed"); + } +} + +async function declineRequest(req, res) { + const me = Number(req.user.id); + const from = Number(req.query.from); + if (!validId(from)) { + return res.status(400).send("Invalid user id"); + } + + try { + const result = await driver.executeQuery( + `MATCH (f:Person {db_id: $from})-[r:REQUESTED]->(me:Person {db_id: $me}) + DELETE r + RETURN f`, + { me, from }, + GRAPH, + ); + if (result.records.length === 0) { + return res.status(404).send("No pending friend request from this user"); + } + return res.status(200).json({ message: "Friend request declined" }); + } catch (err) { + console.error("friend request decline failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Friend request was not declined, request failed"); + } +} + +async function cancelRequest(req, res) { + const me = Number(req.user.id); + const to = Number(req.query.to); + if (!validId(to)) { + return res.status(400).send("Invalid user id"); + } + + try { + const result = await driver.executeQuery( + `MATCH (me:Person {db_id: $me})-[r:REQUESTED]->(t:Person {db_id: $to}) + DELETE r + RETURN t`, + { me, to }, + GRAPH, + ); + if (result.records.length === 0) { + return res.status(404).send("No pending friend request to this user"); + } + return res.status(200).json({ message: "Friend request cancelled" }); + } catch (err) { + console.error("friend request cancel failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Friend request was not cancelled, request failed"); + } +} + +async function listFriends(req, res) { + try { + const { records } = await driver.executeQuery( + "MATCH (me:Person {db_id: $me})-[:FRIENDS_WITH]-(f:Person) RETURN f.db_id AS id", + { me: Number(req.user.id) }, + GRAPH, + ); + const ids = await personIdsFromGraph(records); + const friends = await personDetails(ids); + return res.status(200).json(friends); + } catch (err) { + console.error("list friends failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Friends could not be retrieved, request failed"); + } +} + +async function listRequests(req, res) { + try { + const { records } = await driver.executeQuery( + "MATCH (f:Person)-[:REQUESTED]->(me:Person {db_id: $me}) RETURN f.db_id AS id", + { me: Number(req.user.id) }, + GRAPH, + ); + const ids = await personIdsFromGraph(records); + const requesters = await personDetails(ids); + return res.status(200).json(requesters); + } catch (err) { + console.error("list friend requests failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Friend requests could not be retrieved, request failed"); + } +} + +async function removeFriend(req, res) { + const me = Number(req.user.id); + const id = Number(req.query.id); + if (!validId(id)) { + return res.status(400).send("Invalid user id"); + } + + try { + const result = await driver.executeQuery( + `MATCH (me:Person {db_id: $me})-[r:FRIENDS_WITH]-(f:Person {db_id: $id}) + DELETE r + RETURN f`, + { me, id }, + GRAPH, + ); + if (result.records.length === 0) { + return res.status(404).send("Friend not found or not in your friend list"); + } + return res.status(200).json({ message: "Friend removed" }); + } catch (err) { + console.error("friend removal failed", { + message: err.message, + code: err.code, + detail: err.detail, + hint: err.hint, + }); + return res.status(500).send("Friend could not be removed, request failed"); + } +} + +router.get("/", authenticateToken, strictInput(), listFriends); +router.get("/requests", authenticateToken, strictInput(), listRequests); +router.post("/request", authenticateToken, strictInput({ query: ["to"] }), sendRequest); +router.post("/accept", authenticateToken, strictInput({ query: ["from"] }), acceptRequest); +router.post("/decline", authenticateToken, strictInput({ query: ["from"] }), declineRequest); +router.post("/cancel", authenticateToken, strictInput({ query: ["to"] }), cancelRequest); +router.delete("/remove", authenticateToken, strictInput({ query: ["id"] }), removeFriend); + +module.exports = router; diff --git a/features/relations/friend_graph.js b/features/relations/friend_graph.js new file mode 100644 index 0000000..6d42811 --- /dev/null +++ b/features/relations/friend_graph.js @@ -0,0 +1,39 @@ +const driver = require("../../graph_db"); + +function graphIdToNumber(value) { + if (typeof value === "number") return value; + if (value && typeof value.toNumber === "function") return value.toNumber(); + return Number(value); +} + +function graphParams(userId) { + return { db_id: Number(userId) }; +} + +async function getFriendIds(userId) { + const { records } = await driver.executeQuery( + "MATCH (me:Person {db_id: $db_id})-[:FRIENDS_WITH]-(f:Person) RETURN f.db_id AS id", + graphParams(userId), + { database: process.env.GRAPH_DB_NAME }, + ); + return new Set(records.map((record) => graphIdToNumber(record.get("id")))); +} + +async function getFriendIdsAmong(userId, ids) { + if (ids.length === 0) return new Set(); + const { records } = await driver.executeQuery( + `MATCH (me:Person {db_id: $db_id})-[:FRIENDS_WITH]-(f:Person) + WHERE f.db_id IN $ids + RETURN f.db_id AS id`, + { ...graphParams(userId), ids: ids.map(Number) }, + { database: process.env.GRAPH_DB_NAME }, + ); + return new Set(records.map((record) => graphIdToNumber(record.get("id")))); +} + +async function areFriends(userId, otherId) { + const friendIds = await getFriendIdsAmong(userId, [otherId]); + return friendIds.has(Number(otherId)); +} + +module.exports = { getFriendIds, getFriendIdsAmong, areFriends, graphIdToNumber }; diff --git a/middleware/authenticate_token.js b/middleware/authenticate_token.js index e0cb534..8e2ce63 100644 --- a/middleware/authenticate_token.js +++ b/middleware/authenticate_token.js @@ -1,4 +1,5 @@ const crypto = require('crypto'); +const pool = require('../db'); const DEFAULT_TOKEN_LIFETIME_SECONDS = 60 * 60; @@ -14,7 +15,7 @@ function getJwtSecret() { return secret; } -function signToken(userId) { +function signToken(userId, { jti, tokenVersion } = {}) { const now = Math.floor(Date.now() / 1000); const configuredLifetime = Number.parseInt(process.env.JWT_EXPIRES_IN, 10); const lifetime = Number.isInteger(configuredLifetime) && configuredLifetime > 0 @@ -25,6 +26,8 @@ function signToken(userId) { iat: now, exp: now + lifetime, }; + if (jti) payload.jti = jti; + if (tokenVersion !== undefined) payload.tvr = tokenVersion; const encodedHeader = base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' })); const encodedPayload = base64url(JSON.stringify(payload)); const content = `${encodedHeader}.${encodedPayload}`; @@ -57,7 +60,7 @@ function getTokenFromRequest(req) { return null; } -function authenticateToken(req, res, next) { +async function authenticateToken(req, res, next) { const token = getTokenFromRequest(req); if (!token) { @@ -92,6 +95,34 @@ function authenticateToken(req, res, next) { } req.user = { id: payload.user_id }; + + if (payload.jti || payload.tvr !== undefined) { + const { rows } = await pool.query( + 'SELECT token_version FROM people WHERE id = $1', + [payload.user_id], + ); + if (rows.length === 0 || rows[0].token_version !== payload.tvr) { + return res.status(401).send('Session has been invalidated'); + } + + if (payload.jti) { + const sessionCheck = await pool.query( + 'SELECT 1 FROM sessions WHERE id = $1 AND user_id = $2', + [payload.jti, payload.user_id], + ); + if (sessionCheck.rowCount === 0) { + return res.status(401).send('Session has been revoked'); + } + } + + req.user.session_id = payload.jti || null; + } + + if (payload.jti) { + pool.query('UPDATE sessions SET last_used_at = NOW() WHERE id = $1', [payload.jti]) + .catch(() => {}); + } + next(); } catch (err) { if (err.message.startsWith('JWT_SECRET')) { diff --git a/middleware/post_upload.js b/middleware/post_upload.js index d1c8418..99c9182 100644 --- a/middleware/post_upload.js +++ b/middleware/post_upload.js @@ -14,6 +14,38 @@ const extensionByMimeType = { "image/webp": ".webp", }; +// File signatures (magic bytes) that must match the declared Content-Type. +const signatureByMimeType = { + "image/jpeg": [Buffer.from([0xff, 0xd8, 0xff])], + "image/png": [Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])], + "image/gif": [Buffer.from("GIF87a"), Buffer.from("GIF89a")], +}; + +function hasValidImageSignature(file) { + const signatures = signatureByMimeType[file.mimetype]; + if (!signatures) { + return isWebP(file.path); + } + const header = Buffer.alloc(12); + const fd = fs.openSync(file.path, "r"); + fs.readSync(fd, header, 0, 12, 0); + fs.closeSync(fd); + return signatures.some((signature) => + header.subarray(0, signature.length).equals(signature), + ); +} + +function isWebP(filePath) { + const header = Buffer.alloc(12); + const fd = fs.openSync(filePath, "r"); + fs.readSync(fd, header, 0, 12, 0); + fs.closeSync(fd); + return ( + header.subarray(0, 4).equals(Buffer.from("RIFF")) && + header.subarray(8, 12).equals(Buffer.from("WEBP")) + ); +} + fs.mkdirSync(uploadDirectory, { recursive: true }); const storage = multer.diskStorage({ @@ -38,7 +70,13 @@ const ALLOWED_IMAGE_PREFIXES = ["/posts/image/", "/profiles/image/"]; function handleImageUpload(req, res, next) { uploadImage(req, res, (err) => { - if (!err) return next(); + if (!err) { + if (req.file && !hasValidImageSignature(req.file)) { + fs.promises.unlink(req.file.path).catch(() => {}); + return res.status(400).send("Uploaded file is not a valid image"); + } + return next(); + } if (err.code === "LIMIT_FILE_SIZE") { return res.status(413).send("Image exceeds the maximum allowed size"); } diff --git a/middleware/rate_limit.js b/middleware/rate_limit.js new file mode 100644 index 0000000..2596017 --- /dev/null +++ b/middleware/rate_limit.js @@ -0,0 +1,19 @@ +const rateLimit = require("express-rate-limit"); + +const authLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, + limit: 20, + standardHeaders: "draft-7", + legacyHeaders: false, + message: "Too many attempts, please try again later", +}); + +const globalLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, + limit: 300, + standardHeaders: "draft-7", + legacyHeaders: false, + message: "Too many requests, please try again later", +}); + +module.exports = { authLimiter, globalLimiter }; diff --git a/middleware/sanitize_person_input.js b/middleware/sanitize_person_input.js index a0222aa..4402a8d 100644 --- a/middleware/sanitize_person_input.js +++ b/middleware/sanitize_person_input.js @@ -121,6 +121,16 @@ function cleanProfileUpdateInput(input) { } } + if (body.private !== undefined) { + if (typeof body.private === 'boolean') { + values.private = body.private; + } else if (body.private === 'true' || body.private === 'false') { + values.private = body.private === 'true'; + } else { + values.private = null; + } + } + return values; } @@ -148,10 +158,14 @@ function validateOptionalPersonField(field, value) { function validateProfileUpdateInput(values, { hasImageChange = false } = {}) { const changeFields = ['name', 'username', 'email', 'password'].filter((field) => values[field] !== undefined); - if (changeFields.length === 0 && !hasImageChange) { + if (changeFields.length === 0 && values.private === undefined && !hasImageChange) { throw new Error('At least one profile field must be changed'); } + if (values.private === null) { + throw new Error('private must be true or false'); + } + if (values.password !== undefined && values.current_password === undefined) { throw new Error('current_password is required when changing password'); } diff --git a/package-lock.json b/package-lock.json index 2368295..73d664e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,9 @@ "cors": "^2.8.6", "dotenv": "^17.4.2", "express": "^5.2.1", + "express-rate-limit": "^8.6.1", "fakeout": "^1.0.65", + "helmet": "^8.3.0", "multer": "^2.2.0", "neo4j-driver": "^6.2.0", "pg": "^8.22.0", @@ -492,6 +494,24 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "8.6.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.1.tgz", + "integrity": "sha512-0D493aP61w0TJ2A0wy27riRsO7FMQ7FK+KUHOKCSfPvYo0R55aiC6emCVgFUeShH0fq0ICPVzNcgoS+BsbXQCA==", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/fakeout": { "version": "1.0.65", "resolved": "https://registry.npmjs.org/fakeout/-/fakeout-1.0.65.tgz", @@ -673,6 +693,17 @@ "node": ">= 0.4" } }, + "node_modules/helmet": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.3.0.tgz", + "integrity": "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/EvanHahn" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -742,6 +773,14 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ip-address": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.4.0.tgz", + "integrity": "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==", + "engines": { + "node": ">= 12" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", diff --git a/package.json b/package.json index dafc1c8..048889c 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,9 @@ "cors": "^2.8.6", "dotenv": "^17.4.2", "express": "^5.2.1", + "express-rate-limit": "^8.6.1", "fakeout": "^1.0.65", + "helmet": "^8.3.0", "multer": "^2.2.0", "neo4j-driver": "^6.2.0", "pg": "^8.22.0",