Updated profile and post capabilities

This commit is contained in:
Sven laptop
2026-07-29 22:35:36 +02:00
parent eaeb0a29bc
commit 494b583cbc
9 changed files with 485 additions and 34 deletions
+23 -4
View File
@@ -1,13 +1,18 @@
# API contract (agent reference) # API contract (agent reference)
Base URL: `http://localhost:${PORT}`. Use `Authorization: Bearer <token>` on every endpoint except register/login. JSON uses `Content-Type: application/json`; upload routes use `multipart/form-data`. Base URL: `http://localhost:${PORT}`. Use `Authorization: Bearer <token>` 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 | | 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/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}`; `401` is generic | | `POST /auth/login` | no | JSON: `email`, `password` | `200 {id,token,expires_at}`; sets `fc_session_token` HttpOnly cookie; `401` is generic |
| `GET /profiles/me` | yes | no body/query | `200 {id,name,username}` for the token user | | `GET /auth/me` | yes | no body/query | `200 {id,name,username,email}` session user profile |
| `GET /profiles/:id` | yes | no body/query | `200 {id,name,username}`; email/password are never exposed | | `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 |
| `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/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` | 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/me` | yes | no body/query | `200` only posts with `author_id = token.user_id`; each includes `author_username` |
| `GET /posts/image/:filename` | yes | no body/query | Authenticated image download | | `GET /posts/image/:filename` | yes | no body/query | Authenticated image download |
@@ -22,6 +27,8 @@ Post objects include `author_username` and `created_at` (the database creation t
- Any undocumented body or query field returns `400`; do not send `author_id` to create posts. - Any undocumented body or query field returns `400`; do not send `author_id` to create posts.
- Registration: `name` 1100 chars; `username` 150, no whitespace; `email` 1254, trimmed/lowercased, valid format, no whitespace, not disposable; `password` 1128 and at least 12 chars with lower/upper/number/special, no username/email-local-part, common password, triple repeat, or obvious sequence. - Registration: `name` 1100 chars; `username` 150, no whitespace; `email` 1254, trimmed/lowercased, valid format, no whitespace, not disposable; `password` 1128 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.
- 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). - 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. - Passwords, hashes, salts, JWTs, and database details must never be logged or exposed.
@@ -42,3 +49,15 @@ curl -X PUT "http://localhost:3000/posts/edit?id=12" \
``` ```
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.
Profile picture (same file rules as post images):
```sh
curl -X PUT http://localhost:3000/profiles/me \
-H "Authorization: Bearer $TOKEN" \
-F image=@avatar.png
curl -X PUT http://localhost:3000/profiles/me \
-H "Authorization: Bearer $TOKEN" \
-F remove_image=true
```
+10 -4
View File
@@ -23,19 +23,25 @@ Database and graph-database variables are also required by the relevant routes.
## Authentication ## Authentication
`POST /auth/register` and `POST /auth/login` are public. Every other route requires: `POST /auth/register` and `POST /auth/login` are public. Every other route requires either:
```http ```http
Authorization: Bearer <JWT> Authorization: Bearer <JWT>
``` ```
Login returns `{ id, token, expires_at }`. The token is HS256-signed and contains `user_id`, `iat`, and `exp`. Never log or expose tokens, passwords, password hashes, or salts. or an HttpOnly session cookie set upon login:
```http
Cookie: fc_session_token=<JWT>
```
`POST /auth/login` returns `{ id, token, expires_at }` and sets the `fc_session_token` cookie (`HttpOnly; Secure; SameSite=Strict; Path=/`). Clients can verify their session automatically via `GET /auth/me` or `GET /auth/verify`. The token is HS256-signed and contains `user_id`, `iat`, and `exp`. Never log or expose tokens, passwords, password hashes, or salts.
## API ## API
The compact endpoint contract is in [API.md](API.md). Unknown body/query fields are rejected with `400`; clients must send only documented fields. The compact endpoint contract is in [API.md](API.md). Unknown body/query fields are rejected with `400`; clients must send only documented fields.
Authenticated clients can read profiles through `GET /profiles/me` or `GET /profiles/:id`. Post responses include the public author username as `author_username` and the database creation timestamp as `created_at`. Authenticated clients can read profiles through `GET /profiles/me` or `GET /profiles/:id`, update their account with `PUT /profiles/me`, and delete it with `DELETE /profiles/me` (password confirmation). Post responses include the public author username as `author_username` and the database creation timestamp as `created_at`.
## Security and ownership ## Security and ownership
@@ -44,7 +50,7 @@ Authenticated clients can read profiles through `GET /profiles/me` or `GET /prof
- Post creation always uses `author_id` from the verified JWT; clients must not send `author_id`. - 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. - 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`. - `/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 only `id`, `name`, and `username`. - 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. - Relationship creation requires `me` to equal the JWT user ID.
- 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`. - 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. - Registration rejects disposable email addresses and weak/reused-pattern passwords. Login failures use the generic `Invalid email or password` response.
+5 -2
View File
@@ -11,17 +11,20 @@ const allowedOrigins = (process.env.CORS_ALLOWED_ORIGINS || "")
.filter(Boolean); .filter(Boolean);
// Apply configured CORS origins to every endpoint, including preflight requests. // Apply configured CORS origins to every endpoint, including preflight requests.
app.use(cors({ origin: allowedOrigins })); app.use(cors({ origin: allowedOrigins, credentials: true }));
app.use(express.json()); app.use(express.json());
// People routes // People routes
const CreatePersonRoute = require("./features/people/REGISTER_people"); const CreatePersonRoute = require("./features/people/REGISTER_people");
const LoginPersonRoute = require("./features/people/LOGIN_people"); const LoginPersonRoute = require("./features/people/LOGIN_people");
const VerifyAuthRoute = require("./features/people/VERIFY_auth");
app.use("/auth/register", CreatePersonRoute); app.use("/auth/register", CreatePersonRoute);
app.use("/auth/login", LoginPersonRoute); app.use("/auth/login", LoginPersonRoute);
app.use("/auth/me", VerifyAuthRoute);
app.use("/auth/verify", VerifyAuthRoute);
// Every route below this point requires a valid JWT. Registration and login stay public. // Every route below this point requires a valid JWT or session cookie. Registration and login stay public.
app.use(authenticateToken); app.use(authenticateToken);
// Relation routes // Relation routes
+242 -5
View File
@@ -1,15 +1,60 @@
const express = require("express"); const express = require("express");
const crypto = require("crypto");
const path = require("path");
const { promisify } = require("util");
const router = express.Router(); const router = express.Router();
const pool = require("../../db"); const pool = require("../../db");
const driver = require("../../graph_db");
const { strictInput } = require("../../middleware/strict_input"); const { strictInput } = require("../../middleware/strict_input");
const { authenticateToken } = require("../../middleware/authenticate_token"); const {
sanitizeProfileUpdate,
sanitizeAccountDelete,
validatePasswordRules,
} = require("../../middleware/sanitize_person_input");
const {
handleProfileUpload,
profileImageLinkForFile,
removeImageLink,
removeUploadedProfileFile,
uploadDirectory,
} = require("../../middleware/post_upload");
const scrypt = promisify(crypto.scrypt);
async function verifyStoredPassword(storedHash, password) {
const [salt, storedKeyHex] = storedHash.split(":");
const storedKey = Buffer.from(storedKeyHex || "", "hex");
const derivedKey = await scrypt(password, salt, 64);
return (
storedKey.length === derivedKey.length &&
crypto.timingSafeEqual(storedKey, derivedKey)
);
}
async function hashPassword(password) {
const salt = crypto.randomBytes(16).toString("hex");
const derivedKey = await scrypt(password, salt, 64);
return `${salt}:${derivedKey.toString("hex")}`;
}
function isUniqueViolation(err) {
return err.code === "23505";
}
function resolveProfileId(req) {
const { id } = req.params;
if (id === undefined || id === "me") {
return req.user.id;
}
return id;
}
async function getProfile(req, res) { async function getProfile(req, res) {
const id = req.params.id === "me" ? req.user.id : req.params.id; const id = resolveProfileId(req);
try { try {
const { rows } = await pool.query( const { rows } = await pool.query(
"SELECT id, name, username FROM people WHERE id = $1", "SELECT id, name, username, profile_link FROM people WHERE id = $1",
[id], [id],
); );
if (rows.length === 0) return res.status(404).send("Profile not found"); if (rows.length === 0) return res.status(404).send("Profile not found");
@@ -25,7 +70,199 @@ async function getProfile(req, res) {
} }
} }
router.get("/me", authenticateToken, strictInput(), getProfile); async function updateProfile(req, res) {
router.get("/:id", authenticateToken, strictInput(), getProfile); const update = req.profileUpdate;
const { remove_image: removeImageValue } = req.body;
const removeImage = removeImageValue === "true";
if (removeImageValue !== undefined && !["true", "false"].includes(removeImageValue)) {
await removeUploadedProfileFile(req.file);
return res.status(400).send("remove_image must be true or false");
}
if (req.file && removeImage) {
await removeUploadedProfileFile(req.file);
return res.status(400).send("Choose either an image or remove_image=true");
}
try {
const existing = await pool.query(
"SELECT id, name, username, email, password, profile_link FROM people WHERE id = $1",
[req.user.id],
);
if (existing.rowCount === 0) {
await removeUploadedProfileFile(req.file);
return res.status(404).send("Profile not found");
}
const current = existing.rows[0];
const nextName = update.name ?? current.name;
const nextUsername = update.username ?? current.username;
const nextEmail = update.email ?? current.email;
if (update.password !== undefined) {
const passwordMatches = await verifyStoredPassword(
current.password,
update.current_password,
);
if (!passwordMatches) {
await removeUploadedProfileFile(req.file);
return res.status(401).send("Current password is incorrect");
}
try {
validatePasswordRules(update.password, {
username: nextUsername,
email: nextEmail,
});
} catch (err) {
await removeUploadedProfileFile(req.file);
return res.status(400).send(err.message);
}
}
const oldProfileLink = current.profile_link;
const fields = [];
const values = [];
const addField = (field, value) => {
fields.push(`${field} = $${values.length + 1}`);
values.push(value);
};
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.password !== undefined) {
addField("password", await hashPassword(update.password));
}
if (req.file) addField("profile_link", profileImageLinkForFile(req.file));
if (removeImage) addField("profile_link", null);
values.push(req.user.id);
let rows;
try {
({ rows } = await pool.query(
`UPDATE people SET ${fields.join(", ")} WHERE id = $${values.length} RETURNING id, name, username, profile_link`,
values,
));
} catch (err) {
await removeUploadedProfileFile(req.file);
throw err;
}
if (req.file || removeImage) {
await removeImageLink(oldProfileLink).catch((err) => {
console.error("old profile image could not be removed", { message: err.message });
});
}
if (update.name !== undefined || update.username !== undefined) {
await driver.executeQuery(
"MATCH (p:Person {db_id: $db_id}) SET p.name = $name, p.username = $username",
{ db_id: req.user.id, name: rows[0].name, username: rows[0].username },
{ database: process.env.GRAPH_DB_NAME },
);
}
return res.status(200).json(rows[0]);
} catch (err) {
await removeUploadedProfileFile(req.file);
if (isUniqueViolation(err)) {
return res.status(409).send("Username or email is already in use");
}
console.error("profile update failed", {
message: err.message,
code: err.code,
detail: err.detail,
hint: err.hint,
});
return res.status(500).send("Profile was not updated, request failed");
}
}
async function deleteAccount(req, res) {
try {
const existing = await pool.query(
"SELECT id, password, profile_link FROM people WHERE id = $1",
[req.user.id],
);
if (existing.rowCount === 0) {
return res.status(404).send("Profile not found");
}
const passwordMatches = await verifyStoredPassword(
existing.rows[0].password,
req.accountDelete.password,
);
if (!passwordMatches) {
return res.status(401).send("Invalid password");
}
const posts = await pool.query(
"SELECT image_link FROM posts WHERE author_id = $1",
[req.user.id],
);
for (const post of posts.rows) {
await removeImageLink(post.image_link);
}
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 people WHERE id = $1", [req.user.id]);
await driver.executeQuery(
"MATCH (p:Person {db_id: $db_id}) DETACH DELETE p",
{ db_id: req.user.id },
{ database: process.env.GRAPH_DB_NAME },
);
res.clearCookie("fc_session_token", {
httpOnly: true,
secure: true,
sameSite: "Strict",
path: "/",
});
return res.status(200).json({ message: "Account deleted" });
} catch (err) {
console.error("account delete failed", {
message: err.message,
code: err.code,
detail: err.detail,
hint: err.hint,
});
return res.status(500).send("Account was not deleted, request failed");
}
}
router.get(
"/image/:filename",
strictInput(),
(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();
});
},
);
router.get("/me", strictInput(), getProfile);
router.get("/:id", strictInput(), getProfile);
router.put(
"/me",
handleProfileUpload,
strictInput({
body: ["name", "username", "email", "password", "current_password", "remove_image"],
cleanupUploadedFile: true,
}),
sanitizeProfileUpdate,
updateProfile,
);
router.delete(
"/me",
strictInput({ body: ["password"] }),
sanitizeAccountDelete,
deleteAccount,
);
module.exports = router; module.exports = router;
+6
View File
@@ -35,6 +35,12 @@ async function login(req, res) {
} }
const { token, expiresAt } = signToken(rows[0].id); const { token, expiresAt } = signToken(rows[0].id);
res.cookie('fc_session_token', token, {
httpOnly: true,
secure: true,
sameSite: 'Strict',
path: '/',
});
res.status(200).json({ id: rows[0].id, token, expires_at: expiresAt }); res.status(200).json({ id: rows[0].id, token, expires_at: expiresAt });
} }
catch (err) { catch (err) {
+27
View File
@@ -0,0 +1,27 @@
const express = require('express');
const router = express.Router();
const pool = require('../../db');
const { strictInput } = require('../../middleware/strict_input');
const { authenticateToken } = require('../../middleware/authenticate_token');
async function verifyAuth(req, res) {
try {
const { rows } = await pool.query(
'SELECT id, name, username, email FROM people WHERE id = $1',
[req.user.id]
);
if (rows.length === 0) {
return res.status(404).send('User not found');
}
return res.status(200).json(rows[0]);
} catch (err) {
console.error('verify auth failed', { message: err.message, code: err.code });
return res.status(500).send('Session verification failed, request could not be completed');
}
}
router.get('/', authenticateToken, strictInput(), verifyAuth);
router.get('/me', authenticateToken, strictInput(), verifyAuth);
router.get('/verify', authenticateToken, strictInput(), verifyAuth);
module.exports = router;
+24 -4
View File
@@ -36,16 +36,36 @@ function signToken(userId) {
return { token: `${content}.${signature}`, expiresAt: payload.exp }; return { token: `${content}.${signature}`, expiresAt: payload.exp };
} }
function authenticateToken(req, res, next) { function getTokenFromRequest(req) {
const authorization = req.get('authorization') || ''; const authorization = req.get('authorization') || '';
const match = authorization.match(/^Bearer\s+([^\s]+)$/i); const match = authorization.match(/^Bearer\s+([^\s]+)$/i);
if (match) {
return match[1];
}
if (!match) { const cookieHeader = req.get('cookie') || '';
return res.status(401).send('A valid Bearer token is required'); if (cookieHeader) {
const cookies = cookieHeader.split(';');
for (const cookie of cookies) {
const [name, ...rest] = cookie.trim().split('=');
if (name === 'fc_session_token') {
return rest.join('=');
}
}
}
return null;
}
function authenticateToken(req, res, next) {
const token = getTokenFromRequest(req);
if (!token) {
return res.status(401).send('A valid Bearer token or session cookie is required');
} }
try { try {
const [encodedHeader, encodedPayload, providedSignature] = match[1].split('.'); const [encodedHeader, encodedPayload, providedSignature] = token.split('.');
if (!encodedHeader || !encodedPayload || !providedSignature) { if (!encodedHeader || !encodedPayload || !providedSignature) {
throw new Error('Malformed token'); throw new Error('Malformed token');
} }
+27 -4
View File
@@ -34,7 +34,9 @@ const uploadImage = multer({
}, },
}).single("image"); }).single("image");
function handlePostUpload(req, res, next) { const ALLOWED_IMAGE_PREFIXES = ["/posts/image/", "/profiles/image/"];
function handleImageUpload(req, res, next) {
uploadImage(req, res, (err) => { uploadImage(req, res, (err) => {
if (!err) return next(); if (!err) return next();
if (err.code === "LIMIT_FILE_SIZE") { if (err.code === "LIMIT_FILE_SIZE") {
@@ -44,26 +46,47 @@ function handlePostUpload(req, res, next) {
}); });
} }
function imageLinkForFile(file) { function handlePostUpload(req, res, next) {
return file ? `/posts/image/${file.filename}` : null; return handleImageUpload(req, res, next);
}
function handleProfileUpload(req, res, next) {
return handleImageUpload(req, res, next);
}
function imageLinkForFile(file, prefix = "/posts/image/") {
return file ? `${prefix}${file.filename}` : null;
}
function profileImageLinkForFile(file) {
return imageLinkForFile(file, "/profiles/image/");
} }
async function removeImageLink(imageLink) { async function removeImageLink(imageLink) {
if (!imageLink || !imageLink.startsWith("/posts/image/")) return; if (!imageLink || !ALLOWED_IMAGE_PREFIXES.some((prefix) => imageLink.startsWith(prefix))) {
return;
}
const filename = path.basename(imageLink); const filename = path.basename(imageLink);
await fs.promises.unlink(path.join(uploadDirectory, filename)).catch((err) => { await fs.promises.unlink(path.join(uploadDirectory, filename)).catch((err) => {
if (err.code !== "ENOENT") throw err; if (err.code !== "ENOENT") throw err;
}); });
} }
async function removeUploadedProfileFile(file) {
if (file) await removeImageLink(profileImageLinkForFile(file));
}
async function removeUploadedFile(file) { async function removeUploadedFile(file) {
if (file) await removeImageLink(imageLinkForFile(file)); if (file) await removeImageLink(imageLinkForFile(file));
} }
module.exports = { module.exports = {
handlePostUpload, handlePostUpload,
handleProfileUpload,
imageLinkForFile, imageLinkForFile,
profileImageLinkForFile,
removeImageLink, removeImageLink,
removeUploadedFile, removeUploadedFile,
removeUploadedProfileFile,
uploadDirectory, uploadDirectory,
}; };
+121 -11
View File
@@ -57,45 +57,149 @@ function validateCommonFields(values, { requireName = true } = {}) {
} }
} }
function validateRegistrationInput(values) { function validatePasswordRules(password, { username, email }) {
validateCommonFields(values); if (!password || password.length > LIMITS.password) {
throw new Error(`password must be between 1 and ${LIMITS.password} characters`);
}
if (values.password.length < MIN_PASSWORD_LENGTH) { if (password.length < MIN_PASSWORD_LENGTH) {
throw new Error(`password must be at least ${MIN_PASSWORD_LENGTH} characters`); throw new Error(`password must be at least ${MIN_PASSWORD_LENGTH} characters`);
} }
const passwordLower = values.password.toLowerCase(); const passwordLower = password.toLowerCase();
const normalizedPassword = passwordLower.replace(/[^a-z0-9]/g, ''); const normalizedPassword = passwordLower.replace(/[^a-z0-9]/g, '');
const emailLocalPart = values.email.split('@')[0]; const emailLocalPart = email.split('@')[0];
if ( if (
COMMON_PASSWORDS.has(normalizedPassword) || COMMON_PASSWORDS.has(normalizedPassword) ||
passwordLower.includes(values.username.toLowerCase()) || passwordLower.includes(username.toLowerCase()) ||
passwordLower.includes(emailLocalPart) passwordLower.includes(emailLocalPart)
) { ) {
throw new Error('password is too common or contains account details'); throw new Error('password is too common or contains account details');
} }
if (!/[a-z]/.test(values.password) || !/[A-Z]/.test(values.password)) { if (!/[a-z]/.test(password) || !/[A-Z]/.test(password)) {
throw new Error('password must contain lowercase and uppercase letters'); throw new Error('password must contain lowercase and uppercase letters');
} }
if (!/[0-9]/.test(values.password)) { if (!/[0-9]/.test(password)) {
throw new Error('password must contain a number'); throw new Error('password must contain a number');
} }
if (!/[^a-zA-Z0-9\s]/.test(values.password)) { if (!/[^a-zA-Z0-9\s]/.test(password)) {
throw new Error('password must contain a special character'); throw new Error('password must contain a special character');
} }
if (/(.)\1\1/.test(values.password) || /(0123|1234|2345|3456|4567|5678|6789|abcd|bcde|cdef)/i.test(values.password)) { if (/(.)\1\1/.test(password) || /(0123|1234|2345|3456|4567|5678|6789|abcd|bcde|cdef)/i.test(password)) {
throw new Error('password must not contain obvious repeated or sequential characters'); throw new Error('password must not contain obvious repeated or sequential characters');
} }
}
function validateRegistrationInput(values) {
validateCommonFields(values);
validatePasswordRules(values.password, {
username: values.username,
email: values.email,
});
if (isDisposableEmail(values.email)) { if (isDisposableEmail(values.email)) {
throw new Error('temporary email addresses are not allowed'); throw new Error('temporary email addresses are not allowed');
} }
} }
function cleanProfileUpdateInput(input) {
const body = input || {};
const values = {};
for (const field of ['name', 'username', 'email', 'password', 'current_password']) {
if (body[field] !== undefined) {
const preserveWhitespace = field === 'password' || field === 'current_password';
let value = cleanText(body[field], { trim: !preserveWhitespace });
if (field === 'email') {
value = value.toLowerCase();
}
values[field] = value;
}
}
return values;
}
function validateOptionalPersonField(field, value) {
if (!value || value.length > LIMITS[field]) {
throw new Error(`${field} must be between 1 and ${LIMITS[field]} characters`);
}
if (field === 'username' && /\s/.test(value)) {
throw new Error('username must not contain spaces');
}
if (field === 'email') {
if (/\s/.test(value)) {
throw new Error('email must not contain spaces');
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
throw new Error('email must be a valid email address');
}
if (isDisposableEmail(value)) {
throw new Error('temporary email addresses are not allowed');
}
}
}
function validateProfileUpdateInput(values, { hasImageChange = false } = {}) {
const changeFields = ['name', 'username', 'email', 'password'].filter((field) => values[field] !== undefined);
if (changeFields.length === 0 && !hasImageChange) {
throw new Error('At least one profile field must be changed');
}
if (values.password !== undefined && values.current_password === undefined) {
throw new Error('current_password is required when changing password');
}
if (values.current_password !== undefined && values.password === undefined) {
throw new Error('password is required when submitting current_password');
}
for (const field of ['name', 'username', 'email']) {
if (values[field] !== undefined) {
validateOptionalPersonField(field, values[field]);
}
}
if (values.current_password !== undefined && (
!values.current_password || values.current_password.length > LIMITS.password
)) {
throw new Error(`current_password must be between 1 and ${LIMITS.password} characters`);
}
}
function sanitizeProfileUpdate(req, res, next) {
try {
const values = cleanProfileUpdateInput(req.body);
const removeImageValue = req.body?.remove_image;
const hasImageChange = Boolean(req.file) || removeImageValue === 'true';
validateProfileUpdateInput(values, { hasImageChange });
req.profileUpdate = values;
next();
}
catch (err) {
res.status(400).send(err.message);
}
}
function sanitizeAccountDelete(req, res, next) {
try {
const password = cleanText((req.body || {}).password, { trim: false });
if (!password || password.length > LIMITS.password) {
throw new Error(`password must be between 1 and ${LIMITS.password} characters`);
}
req.accountDelete = { password };
next();
}
catch (err) {
res.status(400).send(err.message);
}
}
function sanitizePersonInput(req, res, next) { function sanitizePersonInput(req, res, next) {
try { try {
const values = cleanPersonInput(req.body || {}); const values = cleanPersonInput(req.body || {});
@@ -120,4 +224,10 @@ function sanitizeLoginInput(req, res, next) {
} }
} }
module.exports = { sanitizePersonInput, sanitizeLoginInput }; module.exports = {
sanitizePersonInput,
sanitizeLoginInput,
sanitizeProfileUpdate,
sanitizeAccountDelete,
validatePasswordRules,
};