Files
hub/board.js
T
nmemmertandClaude Sonnet 5.5 a45fc1b89c
build-container / build (push) Successful in 3m35s
Board: all people visible in the name picker, PIN enters itself, no number before shopping items
- Name picker wraps in a wider box so five or more people fit
- The board knows each PIN's length and submits when the last digit is typed
- Shopping items typed in are added with no quantity and shown without Mealie's leading 1
- Test updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-26 15:12:22 -04:00

96 lines
10 KiB
JavaScript

// The family board and "who is this?": what a family device (see devices.js) shows before anyone signs in, and the way a person picks their name there.
// Children tap their name; everyone else enters a PIN they set for themselves (or signs in with a passkey). The board only ever shows the family's shared things.
const fs = require('fs'), path = require('path'), crypto = require('crypto');
const atomicWrite = require('./atomic');
const users = require('./users'), auth = require('./auth'), audit = require('./audit'), devices = require('./devices');
const cal = require('./cal'), chores = require('./chores'), notes = require('./notes'), tasks = require('./tasks'), recipes = require('./recipes'), chat = require('./chat');
const { readBody } = require('./body');
const { Readable } = require('stream');
const json = (res, code, o) => { res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(o)); };
const fail = (code, message) => Object.assign(new Error(message), { code });
const FILE = () => path.join(process.env.DATA_DIR || path.join(__dirname, 'data'), 'pins.json');
let pins = null;
const db = () => pins || (pins = (() => { try { return JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch { return {}; } })());
const savePins = () => { fs.mkdirSync(path.dirname(FILE()), { recursive: true }); atomicWrite(FILE(), JSON.stringify(db()), { mode: 0o600 }); };
const hash = (pin, salt) => crypto.scryptSync(String(pin), salt, 32).toString('hex');
const hasPin = uid => !!db()[uid];
const MAX_FAILS = 5, LOCK_MS = 5 * 60e3;
// (a PIN's length is kept as `n`, so a shared screen can enter it for you as soon as you have typed all the digits)
function setPin(uid, pin) { if (!/^\d{4,8}$/.test(String(pin || ''))) throw fail(400, 'A PIN is 4 to 8 digits'); const salt = crypto.randomBytes(12).toString('hex'); db()[uid] = { s: salt, h: hash(pin, salt), n: String(pin).length, fails: 0, until: 0 }; savePins(); }
function checkPin(uid, pin) {
const r = db()[uid]; if (!r) return false; if (r.until > Date.now()) throw fail(429, 'Too many wrong tries. Wait a few minutes.');
const ok = /^\d{4,8}$/.test(String(pin || '')) && crypto.timingSafeEqual(Buffer.from(hash(pin, r.s), 'hex'), Buffer.from(r.h, 'hex'));
if (ok) { if (r.fails) { r.fails = 0; savePins(); } return true; }
r.fails = (r.fails || 0) + 1; if (r.fails >= MAX_FAILS) { r.fails = 0; r.until = Date.now() + LOCK_MS; } savePins(); return false;
}
const ymdOk = s => /^\d{4}-\d{2}-\d{2}$/.test(s || '');
const isKid = u => !!(u.kid && u.kid.on);
const palette = ['#e0742b', '#2f9e6e', '#4f7cff', '#8a5cf0', '#d9453a', '#2aa6a0', '#e5a00d'];
const onBoard = u => !u.disabled && u.board !== false; // the admin picks who is on the family board
const people = () => users.all().filter(onBoard).map((u, i) => ({ id: u.id, name: u.name, kid: isKid(u), pin: hasPin(u.id), pinLen: (db()[u.id] || {}).n || 0, color: palette[i % palette.length] }));
/** Check it is really this person: a child with no PIN just taps their name; everyone else needs their PIN. */
function identify(t, pin, req) {
if (isKid(t) && !hasPin(t.id)) return;
if (!hasPin(t.id)) throw fail(403, 'Set a PIN first (Settings, on your own device), or sign in with your passkey');
if (!checkPin(t.id, pin)) { audit.log('family device: wrong PIN', { who: t.name }, req); throw fail(401, 'That PIN is not right'); }
}
function eventFields(title, b) {
const day = /^\d{4}-\d{2}-\d{2}$/.test(b.date || '') ? b.date : new Date().toISOString().slice(0, 10), time = /^\d{2}:\d{2}$/.test(b.time || '') ? b.time : '';
if (!time) return { title, allDay: true, start: day, end: day };
const end = String((+time.slice(0, 2) + 1) % 24).padStart(2, '0') + time.slice(2); return { title, allDay: false, start: day + 'T' + time, end: +time.slice(0, 2) === 23 ? day + 'T23:59' : day + 'T' + end, tz: b.tz || 'UTC' };
}
async function board(day) {
const t1 = chores.addDays(day, 1), from = new Date(day + 'T00:00:00').getTime() - 864e5, to = new Date(t1 + 'T23:59:59').getTime() + 864e5;
let events = []; try { events = cal.familyEvents({ from, to, fd: day, td: t1 }); } catch {}
return { day, people: people(), announcement: chat.announcement(), events, chores: chores.board(day).filter(i => !i.user || onBoard(users.get(i.user) || {})).map(i => ({ chore: i.chore, title: i.title, points: i.points, user: i.user, userName: i.userName, done: !!i.done, doneBy: i.done ? i.done.byName : '', claimable: !!i.claimable, claimed: !!i.claimed })), week: (w => ({ from: w.from, tiers: w.tiers, people: w.people.filter(p => onBoard(users.get(p.id) || {})).map(p => ({ id: p.id, name: p.name, points: p.points, count: p.count, tiers: p.tiers, earned: p.earned, given: p.given })) }))(chores.week(day)), shopping: await recipes.shoppingOpen(), notes: notes.familyNotes(), tasks: tasks.familyOpen() };
}
async function handle(req, res) {
const u = new URL(req.url, 'http://x'), p = u.pathname, me = auth.currentUser(req), dev = auth.deviceOf(req);
try {
if (p === '/api/board' && req.method === 'GET') { if (!dev) throw fail(403, 'This is not a family device'); const day = u.searchParams.get('day'); return json(res, 200, await board(ymdOk(day) ? day : new Date().toISOString().slice(0, 10))); }
if (p === '/api/board/chore' && req.method === 'POST') { // a person on the shared screen takes a chore, ticks it off, or undoes it, without signing in
if (!dev) throw fail(403, 'This is not a family device'); const b = JSON.parse(await readBody(req, 5e3) || '{}'), t = users.get(String(b.uid));
if (!t || !onBoard(t)) throw fail(404, 'Person not found'); if (!users.can(t, 'chores')) throw fail(403, 'Chores are not turned on for that person'); identify(t, b.pin);
const path = { claim: '/api/chores/claim', unclaim: '/api/chores/claim', done: '/api/chores/done', undo: '/api/chores/done' }[b.action]; if (!path) throw fail(400, 'Unknown action');
const body = JSON.stringify({ chore: b.chore, date: ymdOk(b.date) ? b.date : undefined, undo: b.action === 'unclaim' || b.action === 'undo' || undefined }), r = Readable.from([Buffer.from(body)]); r.url = path; r.method = 'POST'; r.headers = {};
return users.runAs(t, () => chores.handle(r, res)); // (as that person: all of the chore rules apply to them)
}
if (p === '/api/board/add' && req.method === 'POST') { // put something on one of the family's lists from the shared screen, as the person who picked their name
if (!dev) throw fail(403, 'This is not a family device'); const b = JSON.parse(await readBody(req, 8e3) || '{}'), t = users.get(String(b.uid));
if (!t || !onBoard(t)) throw fail(404, 'Person not found'); const text = String(b.text || '').replace(/\s+/g, ' ').trim().slice(0, 200); if (!text) throw fail(400, 'Write something first');
const plan = { shopping: ['recipes', recipes, '/api/recipes/shopping/add', { text }],
task: ['tasks', tasks, '/api/tasks', { list: 'local:family', fields: { title: text, due: /^\d{4}-\d{2}-\d{2}$/.test(b.due || '') ? b.due : '' } }],
item: ['notes', notes, '/api/notes/' + String(b.note || '') + '/items', { text }],
event: ['calendar', cal, '/api/cal/event', { cal: 'family~local', fields: eventFields(text, b) }] }[b.kind];
if (!plan) throw fail(400, 'Unknown list'); if (!users.can(t, plan[0])) throw fail(403, 'That part of the hub is not turned on for ' + t.name);
if (b.kind === 'item') { const n = notes.familyNotes().find(x => x.id === String(b.note) && x.type === 'list'); if (!n) throw fail(404, 'That list is not shared with the family'); }
identify(t, b.pin, req); const r = Readable.from([Buffer.from(JSON.stringify(plan[3]))]); r.url = plan[2]; r.method = 'POST'; r.headers = {};
return users.runAs(t, () => plan[1].handle(r, res)); // (as that person, so that person's own rules apply)
}
if (p === '/api/board/switch' && req.method === 'POST') {
if (!dev) throw fail(403, 'This is not a family device'); const b = JSON.parse(await readBody(req, 5e3) || '{}'), t = users.get(String(b.uid));
if (!t || !onBoard(t)) throw fail(404, 'Person not found');
identify(t, b.pin, req);
auth.startSession(req, res, t); audit.log('family device: picked a profile', { who: t.name }, req); return json(res, 200, { ok: true });
}
if (p === '/api/device' && req.method === 'GET') { if (!me) throw fail(401, 'Not signed in'); return json(res, 200, { device: !!dev, pin: hasPin(me.id), devices: me.role === 'admin' ? devices.load() : undefined }); }
if (p === '/api/device/pin' && (req.method === 'POST' || req.method === 'DELETE')) {
if (!me) throw fail(401, 'Not signed in'); if (req.method === 'DELETE') { delete db()[me.id]; savePins(); return json(res, 200, { pin: false }); }
const b = JSON.parse(await readBody(req, 5e3) || '{}'); setPin(me.id, b.pin); return json(res, 200, { pin: true });
}
if (p === '/api/device/enable' && req.method === 'POST') { // an admin makes this screen a family device (and it goes back to the board)
if (!me || me.role !== 'admin') throw fail(403, 'Only an admin can do this'); const b = JSON.parse(await readBody(req, 5e3) || '{}'); auth.enrollDevice(req, res, b.name, me.name); audit.log('family device added', { who: me.name, detail: String(b.name || '').slice(0, 40) }, req);
res.setHeader('Set-Cookie', [].concat(res.getHeader('Set-Cookie') || [], 'hub_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0')); return json(res, 200, { ok: true });
}
if (p === '/api/device/remove' && req.method === 'POST') { // switch one off: this screen, or another from the list
if (!me || me.role !== 'admin') throw fail(403, 'Only an admin can do this'); const b = JSON.parse(await readBody(req, 5e3) || '{}');
if (b.id) devices.remove(String(b.id)); else auth.forgetDevice(req, res); audit.log('family device removed', { who: me.name }, req); return json(res, 200, { ok: true });
}
return json(res, 404, { error: 'Not found' });
} catch (e) { return json(res, e.code >= 400 && e.code < 600 ? e.code : 400, { error: e instanceof SyntaxError ? 'Bad request' : e.message }); }
}
module.exports = { handle, board, setPin, hasPin };