import { DatabaseSync } from 'node:sqlite'; import { randomBytes, scrypt as derive, timingSafeEqual, createHash } from 'node:crypto'; import { promisify } from 'node:util'; const scrypt = promisify(derive); export class InputError extends Error { constructor(key, status = 400) { super(key); this.status = status; } } export function validateProfile(input) { const out = {}; for (const [key, min, max] of [['height',100,250],['weight',25,350],['age',18,100]]) { const value = input[key]; if (!['number','string'].includes(typeof value) || !/^\d+(?:[.,]\d+)?$/.test(String(value))) throw new InputError(key); out[key] = Number(String(value).replace(',', '.')); if (!Number.isFinite(out[key]) || out[key] < min || out[key] > max) throw new InputError(key); } if (!Number.isInteger(out.age)) throw new InputError('age'); if (!['male','female'].includes(input.sex)) throw new InputError('sex'); out.sex = input.sex; if (!['1.2','1.375','1.55','1.725'].includes(String(input.activity))) throw new InputError('activity'); out.activity = Number(input.activity); return out; } export function nutrition(profile) { const p = validateProfile(profile); const calories = Math.round((10*p.weight + 6.25*p.height - 5*p.age + (p.sex === 'male' ? 5 : -161))*p.activity); const protein = Math.round(p.weight*1.6); // One illustrative day: proportions sum to the daily energy estimate. const menu = [ { name: 'breakfast', share: .3, kcal100: 130, protein100: 7 }, { name: 'lunch', share: .4, kcal100: 150, protein100: 12 }, { name: 'dinner', share: .3, kcal100: 140, protein100: 11 }, ].map(m => ({name:m.name, grams: Math.round(calories*m.share/m.kcal100*100), calories: Math.round(calories*m.share), protein: Math.round(calories*m.share/m.kcal100*m.protein100)})); return { calories, protein, menu }; } const hash = value => createHash('sha256').update(value).digest('hex'); export class ProfileService { constructor(file, {now = () => Date.now()} = {}) { this.now = now; this.db = new DatabaseSync(file); this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, salt TEXT NOT NULL, password TEXT NOT NULL, profile TEXT NOT NULL); CREATE TABLE IF NOT EXISTS sessions (token TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id), expires INTEGER NOT NULL);`); } credentials(input) { if (typeof input.username !== 'string' || !/^[a-zA-Z0-9_-]{3,40}$/.test(input.username)) throw new InputError('username'); if (typeof input.password !== 'string' || input.password.length < 12 || input.password.length > 128) throw new InputError('password'); return input.username.toLowerCase(); } async authenticate(input, register) { const username = this.credentials(input); const profile = validateProfile(input); const user = this.db.prepare('SELECT * FROM users WHERE username=?').get(username); const salt = register || !user ? randomBytes(16).toString('hex') : user.salt; const password = Buffer.from(await scrypt(input.password, salt, 64)); let id; if (register) { if (user) throw new InputError('credentials', 409); id = this.db.prepare('INSERT INTO users(username,salt,password,profile) VALUES(?,?,?,?)').run(username,salt,password.toString('hex'),JSON.stringify(profile)).lastInsertRowid; } else { if (!user || !timingSafeEqual(password, Buffer.from(user.password,'hex'))) throw new InputError('credentials',401); id = user.id; this.db.prepare('UPDATE users SET profile=? WHERE id=?').run(JSON.stringify(profile), id); } this.db.prepare('DELETE FROM sessions WHERE expires<=?').run(this.now()); const token = randomBytes(32).toString('hex'); this.db.prepare('INSERT INTO sessions VALUES(?,?,?)').run(hash(token),id,this.now()+7*86400000); return token; } user(token) { if (!token) throw new InputError('signin',401); const user = this.db.prepare('SELECT users.* FROM users JOIN sessions ON user_id=users.id WHERE token=? AND expires>?').get(hash(token),this.now()); if (!user) throw new InputError('signin',401); return user; } read(token) { const user = this.user(token), profile = JSON.parse(user.profile); return {username:user.username,profile,nutrition:nutrition(profile)}; } update(token,input) { const user = this.user(token), profile = validateProfile(input); this.db.prepare('UPDATE users SET profile=? WHERE id=?').run(JSON.stringify(profile),user.id); return this.read(token); } logout(token) { this.db.prepare('DELETE FROM sessions WHERE token=?').run(hash(token || '')); } close() { this.db.close(); } }