// /api/ — the shared store behind the menu photo, Neighbor Check-In and Marketplace. Own code. // EVERYTHING here is on-site only: the same gate as /local/ (building Wi-Fi, a verified device, or the on-site code). // Storage is the KV namespace bound as HUB. Nothing here is readable from outside the gate. import { verify, standing, readSigned, mintSigned, opted, mintNav, devKey, probing } from "../_lib.js"; const TZ = "America/Phoenix"; const json = (o, status = 200, extra) => new Response(JSON.stringify(o), { status, headers: Object.assign({ "content-type": "application/json; charset=utf-8", "cache-control": "private, no-store", "x-robots-tag": "noindex" }, extra || {}) }); // The same starter-key check used to start the circle (vouch op "found"). If the key is not configured, nobody is founder. function founderKeyOk(env, key) { const want = env.FOUNDER_KEY != null && String(env.FOUNDER_KEY) !== "" ? String(env.FOUNDER_KEY) : ""; const got = String(key == null ? "" : key); if (!want || got.length !== want.length) return false; let d = 0; for (let i = 0; i < want.length; i++) d |= want.charCodeAt(i) ^ got.charCodeAt(i); return d === 0; } async function isFounder(request, env) { if (!env.FOUNDER_KEY) return false; let key = request.headers.get("x-pt-founder") || ""; if (!key && request.method === "POST") { try { const b = await request.clone().json(); key = (b && b.key) || ""; } catch (e) { key = ""; } } return founderKeyOk(env, key); } const dayKey = (d = new Date()) => new Intl.DateTimeFormat("en-CA", { timeZone: TZ, year: "numeric", month: "2-digit", day: "2-digit" }).format(d); const clean = (s, n) => String(s == null ? "" : s).replace(/[\u0000-\u001f<>]/g, " ").replace(/\s+/g, " ").trim().slice(0, n); const id = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6); const getJ = async (kv, k, d) => { const v = await kv.get(k, "json"); return v == null ? d : v; }; // ---------- menu photo: one neighbor photographs the posted menu, everyone on site sees it ---------- async function menuPhoto(request, env, url) { const kv = env.HUB; if (request.method === "GET") { const meta = await getJ(kv, "menuphoto:latest", null); if (url.searchParams.get("img")) { if (!meta || meta.hidden) return json({ error: "none" }, 404); const buf = await kv.get(meta.key, "arrayBuffer"); if (!buf) return json({ error: "none" }, 404); return new Response(buf, { headers: { "content-type": "image/jpeg", "cache-control": "private, max-age=300", "x-content-type-options": "nosniff" } }); } return json({ onsite: true, photo: meta && !meta.hidden ? { at: meta.at, day: meta.day, today: meta.day === dayKey() } : null }); } if (request.method === "POST") { if (url.searchParams.get("hide")) { // "this is not the menu": hides it for everyone; the file is kept const meta = await getJ(kv, "menuphoto:latest", null); if (meta) { meta.hidden = true; meta.hiddenAt = new Date().toISOString(); await kv.put("menuphoto:latest", JSON.stringify(meta)); } return json({ ok: true, photo: null }); } const buf = await request.arrayBuffer(); if (buf.byteLength < 2000 || buf.byteLength > 1500000) return json({ error: "The photo must be a JPEG under 1.5 MB." }, 413); const b = new Uint8Array(buf); if (!(b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff)) return json({ error: "Not a JPEG photo." }, 415); const at = new Date().toISOString(), day = dayKey(), key = `menuphoto:${day}:${Date.now()}`; await kv.put(key, buf); await kv.put("menuphoto:latest", JSON.stringify({ key, at, day })); return json({ ok: true, photo: { at, day, today: true } }); } return json({ error: "method" }, 405); } // ---------- Neighbor Check-In: opt-in list, shared by everyone on site ---------- // A person counts as "seen" from a constellation of signals, any of which is enough: // self — they tapped "I'm here today" neighbor — a neighbor tapped "Seen today" // device — one of the devices they linked (phone, tablet, computer) was used on the Hub today. Each device also // reports where it was: "here" (building Wi-Fi, seen by the server, or the device's own location check, // done on the device so only yes/no is sent, never coordinates), "away", or "unknown". // This is a neighborly safety net for independent and assisted living. It is not a medical alert. // ---- usual-pattern record (de-identified): kept apart from the list under a random id, with no name, apartment, device id or location. // For each of the last 28 days it holds only: the hour of the first sign, and which kinds of sign there were (self / neighbor / device). const hourNow = () => +new Intl.DateTimeFormat("en-US", { timeZone: TZ, hour: "numeric", hour12: false }).format(new Date()) % 24; const dayAdd = (k, n) => { const d = new Date(k + "T12:00:00Z"); d.setUTCDate(d.getUTCDate() + n); return d.toISOString().slice(0, 10); }; function notePattern(pats, pid, kind, today, n) { // returns true when the record changed const r = pats[pid] = pats[pid] || {}; const bit = { self: 1, neighbor: 2, device: 4 }[kind] || 0; let ch = false; if (!r[today]) { r[today] = { h: hourNow(), k: 0 }; ch = true; } if (!(r[today].k & bit)) { r[today].k |= bit; ch = true; } if (n && n > (r[today].n || 0)) { r[today].n = n; r[today].l = hourNow(); ch = true; } // how many visits so far today, and the hour of the latest const cut = dayAdd(today, -28); for (const d of Object.keys(r)) if (d < cut) { delete r[d]; ch = true; } return ch; } // What is usual for this person, and is today unlike it? Needs 10 days with a sign before it says anything. function usual(r, today) { if (!r) return null; const from = dayAdd(today, -21), ds = Object.keys(r).filter(d => d >= from && d < today).sort(); if (ds.length < 10) return { learning: true, have: ds.length }; const span = Math.min(21, Math.round((Date.parse(today) - Date.parse(ds[0])) / 86400000)), rate = ds.length / Math.max(span, 1); const hs = ds.map(d => r[d].h).sort((a, b) => a - b), by = hs[Math.ceil(hs.length * 0.8) - 1]; const own = ds.filter(d => r[d].k & 5).length / ds.length; // share of days with their own sign (self or device) const hrNow = hourNow(), steady = rate >= 0.85; // only for people who show a sign on nearly every day const quiet = steady && by < 18 && !r[today] && hrNow >= by + 3; // late-evening routines are left to the days rule const missedYesterday = steady && !r[dayAdd(today, -1)] && !r[today] && hrNow >= Math.max(by, 9); const ns = ds.map(d => r[d].n || 0).filter(Boolean).sort((a, b) => a - b), typ = ns.length >= 5 ? ns[Math.floor(ns.length / 2)] : null; const nowN = r[today] ? (r[today].n || 0) : 0, light = !!(typ && typ >= 6 && r[today] && nowN <= typ * 0.25 && hourNow() >= 18); return { by, most: steady, own: own >= 0.6, quiet, missedYesterday, typ, light }; } // WHO IS WHO. A device proves which person it belongs to with its sealed note (st.pid), which only this server can write. // Nothing in a request body is trusted for that. "own" below means: this device's note names this person, and the device // has not been unlinked. Everything that changes a person's record needs "own", except a neighbor saying they saw them, // are going to check, or got no answer. const has = (o, k) => !!o && Object.prototype.hasOwnProperty.call(o, k); const devOk = d => /^[a-z0-9]{8,24}$/.test(d || ""); async function checkin(request, env, v, st) { const kv = env.HUB, K = "checkin:list"; let list = await getJ(kv, K, []), dirty = false, pats = {}, pdirty = false, cookie = null; try { pats = await getJ(kv, "checkin:patterns", {}); } catch (e) { pats = {}; } if (!Array.isArray(list)) return { res: json({ error: "The list could not be read. Nothing was changed." }, 503) }; let myPid = st.pid; // follows the sealed note, including a change made by this very request const ownOf = x => !!x && !!myPid && myPid === x.id && !(x.revoked || []).includes(st.nid); const mine = list.find(ownOf) || null; const t0 = dayKey(); if (mine && mine.unvouched && st.full) { delete mine.unvouched; dirty = true; } if (request.method === "POST") { const b = await request.json().catch(() => ({})), today = t0, now = new Date().toISOString(); const agreed = (q, what, extra) => { q.consents = (q.consents || []).concat(Object.assign({ what, at: now }, extra || {})).slice(-60); }; const p = b.id ? list.find(x => x.id === b.id) : null, own = ownOf(p); const learn = (who, n) => { if (p && p.pattern === true && notePattern(pats, p.id, who, today, n)) pdirty = true; }; const dv = devOk(b.dev) ? b.dev : "", kind = ["phone", "tablet", "computer"].includes(b.kind) ? b.kind : "device"; const byName = mine ? mine.name.split(" ")[0] : "A neighbor"; const deny = (msg) => ({ res: json({ onsite: true, resident: true, full: st.full, error: msg || "That can only be done from the person's own device." }, 403) }); const mark = (who) => { delete p.checking; delete p.noAnswer; delete p.famWorry; p.lastSeen = today; p.by = (p.by || []).concat(today).slice(-30); p.sig = p.sig || {}; p.sig[who] = today; }; const addDev = (q) => { q.devs = q.devs || {}; if (dv && !has(q.devs, dv) && Object.keys(q.devs).length < 6) { q.devs[dv] = { kind, last: now, day: "", where: "unknown", nid: st.nid, auto: true }; agreed(q, "linked-a-device", { kind }); } }; const setPid = async (pid) => { const s2 = await standing(request, env, v, { pid }); cookie = s2.setCookie; myPid = pid; }; if (b.op === "add") { const name = clean(b.name, 40); if (!name) return { res: json({ error: "A name is needed." }, 400) }; if (list.length >= 400) return { res: json({ error: "The list is full." }, 400) }; const q = { id: id(), name, apt: clean(b.apt, 8), days: Math.max(1, Math.min(3, parseInt(b.days, 10) || 2)), lastSeen: today, joined: today, sig: {}, devs: {} }; if (b.self === false) { // a neighbor puts a name forward: only a vouched-for neighbor may, and it waits for that person's own yes if (!st.full) return deny("A neighbor's vouch is needed before you can put a name forward."); if (list.filter(x => x.pending).length >= 30) return { res: json({ error: "Too many names are waiting. Ask those neighbors to agree first." }, 400) }; q.pending = true; q.invitedBy = byName; agreed(q, "put-forward-by-a-neighbor", { by: byName }); } else { // joining yourself: one person per device note if (mine) return { res: json({ error: "This device already belongs to " + mine.name + ". Use “Not me” first if that is wrong.", me: mine.id }, 409) }; if (!st.nid) return deny("Say yes to remembering this device first."); if (!st.full) { q.unvouched = true; if (list.filter(x => x.unvouched).length >= 40) return { res: json({ error: "Several new neighbors are waiting for a vouch. Ask a neighbor to vouch for you, then join." }, 400) }; } agreed(q, "joined-the-list"); q.agreed = today; q.autoDevice = b.device === true; agreed(q, q.autoDevice ? "devices-may-check-in" : "devices-do-not-check-in"); q.pattern = b.pattern === true; agreed(q, q.pattern ? "pattern-learning-on" : "pattern-learning-off"); addDev(q); await setPid(q.id); } list.push(q); dirty = true; } else if (b.op === "agree") { // the person's own yes (also used to change the two optional choices) if (!p) return deny("That name is no longer there."); if (!own) { // a put-forward name is claimed by a vouched-for device that does not belong to anyone yet if (!(p.pending && st.full && !mine && st.nid)) return deny(); delete p.pending; p.lastSeen = today; agreed(p, "agreed-to-join"); await setPid(p.id); } p.agreed = p.agreed || today; addDev(p); if (b.device !== undefined) { p.autoDevice = b.device === true; agreed(p, p.autoDevice ? "devices-may-check-in" : "devices-do-not-check-in"); } if (b.pattern !== undefined) { p.pattern = b.pattern === true; agreed(p, p.pattern ? "pattern-learning-on" : "pattern-learning-off"); if (!p.pattern && pats[p.id]) { delete pats[p.id]; pdirty = true; } } dirty = true; } else if (b.op === "thisDevice") { // switch check-in on or off for THIS device only if (!own || !dv) return deny(); addDev(p); if (has(p.devs, dv)) { p.devs[dv].auto = b.on === true; dirty = true; } } else if (b.op === "linkdev") { // "this is me" on another device: becomes that person's only when allowed if (!p || p.pending) return deny("That name is not on the list."); if (own) { addDev(p); dirty = true; } else if (mine) return { res: json({ error: "This device already belongs to " + mine.name + "." }, 409) }; else if (!st.full || !st.nid) return deny("A neighbor's vouch is needed first."); else if (st.kp && st.kp === p.id) { addDev(p); agreed(p, "linked-a-device", { kind, how: "restored from their own backup" }); await setPid(p.id); dirty = true; } // restored with THIS person's keep phrase else { p.devAsk = p.devAsk || {}; const ex = Object.values(p.devAsk).find(a => a.nid === st.nid); if (ex && ex.ok === true) { delete p.devAsk[Object.keys(p.devAsk).find(k => p.devAsk[k] === ex)]; addDev(p); await setPid(p.id); dirty = true; } else if (!ex) { if (Object.keys(p.devAsk).length >= 3) return { res: json({ error: "Other devices are already waiting to be allowed for this name." }, 400) }; p.devAsk[token(8)] = { kind, at: now, nid: st.nid, who: [] }; dirty = true; } } } else if (b.op === "linkCancel") { // "this is not me": withdraw my own waiting request if (p && p.devAsk) for (const k of Object.keys(p.devAsk)) if (p.devAsk[k].nid === st.nid) { delete p.devAsk[k]; dirty = true; } } else if (b.op === "linkAnswer") { // yes or no to a waiting device const ak = clean(b.ask, 12), a = p && has(p.devAsk, ak) ? p.devAsk[ak] : null; if (!a) return deny("That request is no longer waiting."); const buddy = mine && (p.buddies || []).includes(mine.id); if (own || buddy) { if (b.yes === true) { a.ok = true; agreed(p, "allowed-a-device", { kind: a.kind, by: own ? "you" : byName }); } else { delete p.devAsk[ak]; agreed(p, "refused-a-device", { kind: a.kind }); } } else if (st.full && mine) { // nobody of theirs can answer (lost phone, no buddy): two vouched-for neighbors who know them can if (b.yes === true) { a.who = (a.who || []).filter(x => x !== mine.id).concat(mine.id); if (a.who.length >= 2) { a.ok = true; agreed(p, "allowed-a-device", { kind: a.kind, by: "two neighbors" }); } } } else return deny(); dirty = true; } else if (b.op === "seen") { if (!p || p.pending) return deny("That name is not on the list."); if (b.by === "self") { if (!own) return deny(); mark("self"); learn("self"); } else { if (!st.full || own) return deny("A neighbor's vouch is needed for that."); mark("neighbor"); learn("neighbor"); } dirty = true; } else if (b.op === "beat") { // one of the person's own devices is in use; where is it? if (!p) return { res: json({ onsite: true, gone: true }) }; if (!own) return { res: json({ onsite: true, off: true, unlinked: true }) }; if (p.pending || !dv) return { res: json({ onsite: true, off: true }) }; addDev(p); const old = has(p.devs, dv) ? p.devs[dv] : null; if (!old) return { res: json({ onsite: true, off: true }) }; if (p.autoDevice === false || old.auto === false) return { res: json({ onsite: true, off: true }) }; const where = (v.signals.network || b.geo === true) ? "here" : (b.geo === false ? "away" : "unknown"); // Every page view is a sign. The store is rewritten when the day's count has grown meaningfully, half an hour has passed, // the place is newly known, or somebody is worried about this person right now. const n = Math.max(1, Math.min(2000, parseInt(b.n, 10) || 1)), prev = old.day === today ? (old.n || 0) : 0; const stale = !old.last || (Date.now() - Date.parse(old.last)) > 30 * 60 * 1000, worry = !!(p.checking || p.noAnswer || p.famWorry); const placeNews = where !== "unknown" && old.where !== where; if (old.day !== today || placeNews || stale || worry || n >= prev + Math.max(3, Math.ceil(prev * 0.5))) { p.devs[dv] = Object.assign({}, old, { kind: kind === "device" ? (old.kind || "device") : kind, last: now, day: today, where: where === "unknown" && old.day === today ? old.where : where, n: old.day === today ? Math.max(n, prev) : n }); const first = p.sig && p.sig.device === today ? false : true; p.lastSeen = today; p.sig = p.sig || {}; p.sig.device = today; delete p.checking; delete p.noAnswer; delete p.famWorry; if (first || n >= prev * 2) learn("device", Object.values(p.devs).reduce((a, d) => a + (d.day === today ? (d.n || 0) : 0), 0)); // the pattern record is written sparingly dirty = true; } } else if (b.op === "unlink") { // remove one of my own devices; that device can no longer act for me if (!own) return deny(); const k = devOk(b.target) ? b.target : dv; if (has(p.devs, k)) { const n0 = p.devs[k].nid; if (n0) p.revoked = (p.revoked || []).concat(n0).slice(-20); delete p.devs[k]; agreed(p, "unlinked-a-device"); dirty = true; } if (k === dv) await setPid(""); } else if (b.op === "notme") { // this device stops being that person (nothing else changes) if (own && dv && has(p.devs, dv)) { delete p.devs[dv]; dirty = true; } await setPid(""); } else if (b.op === "buddyAsk") { // ask a neighbor to be a buddy; nothing happens until they say yes if (!own || !st.full) return deny("A neighbor's vouch is needed before choosing buddies."); const q = list.find(x => x.id === b.buddy); if (q && q.id !== p.id && !q.pending && !(p.buddies || []).includes(q.id) && (p.buddies || []).length + (p.buddyAsk || []).length < 3) { p.buddyAsk = (p.buddyAsk || []).filter(x => x !== q.id).concat(q.id); agreed(p, "asked-a-buddy", { who: q.name }); dirty = true; } } else if (b.op === "buddyAnswer") { // the neighbor who was asked answers, from their own device if (!p || !mine || !(p.buddyAsk || []).includes(mine.id)) return deny(); p.buddyAsk = p.buddyAsk.filter(x => x !== mine.id); if (b.yes === true) { p.buddies = (p.buddies || []).concat(mine.id).slice(0, 3); agreed(mine, "agreed-to-be-a-buddy", { who: p.name }); agreed(p, "buddy-said-yes", { who: mine.name }); } else agreed(p, "buddy-said-no", { who: mine.name }); dirty = true; } else if (b.op === "buddyEnd") { // either side can end it if (!p || !(own || (mine && mine.id === b.buddy))) return deny(); p.buddies = (p.buddies || []).filter(x => x !== b.buddy); p.buddyAsk = (p.buddyAsk || []).filter(x => x !== b.buddy); agreed(p, "buddy-ended"); dirty = true; } else if (b.op === "claim") { // "I'll check on them" if (!p || !st.full || own) return deny("A neighbor's vouch is needed for that."); p.checking = { by: byName, day: today, at: now }; dirty = true; } else if (b.op === "noanswer") { // knocked, nobody came: stays raised for everyone until there is a real sign if (!p || !st.full || own) return deny("A neighbor's vouch is needed for that."); p.noAnswer = { by: byName, day: today, at: now }; dirty = true; } else if (b.op === "desk") { // "I called the front desk about them": so not everyone calls, and nobody assumes if (!p || !st.full || own || !p.noAnswer) return deny(); p.noAnswer.desk = { by: byName, at: now }; dirty = true; } else if (b.op === "pattern") { if (!own) return deny(); p.pattern = b.on === true; agreed(p, p.pattern ? "pattern-learning-on" : "pattern-learning-off"); if (!p.pattern && pats[p.id]) { delete pats[p.id]; pdirty = true; } dirty = true; } else if (b.op === "remove") { // leave the list (your own record), or withdraw a name you put forward that is still waiting if (!p) return deny("That name is no longer there."); if (!(own || (p.pending && st.full))) return deny("Only the person themselves can take their name off the list."); list = list.filter(x => x.id !== p.id); dirty = true; if (pats[p.id]) { delete pats[p.id]; pdirty = true; } for (const x of list) { if ((x.buddies || []).includes(p.id)) x.buddies = x.buddies.filter(y => y !== p.id); if ((x.buddyAsk || []).includes(p.id)) x.buddyAsk = x.buddyAsk.filter(y => y !== p.id); } if (own) await setPid(""); } else return { res: json({ error: "op" }, 400) }; } else if (request.method !== "GET") return { res: json({ error: "method" }, 405) }; if (dirty || pdirty) { try { if (dirty) await kv.put(K, JSON.stringify(list)); if (pdirty) await kv.put("checkin:patterns", JSON.stringify(pats)); } catch (e) { return { res: json({ ok: false, saved: false, error: "That could not be saved just now. Please try again in a minute. If someone needs help, call the front desk." }, 503), cookie }; } } const t = t0, hr = hourNow(), q = new URL(request.url).searchParams; const me = list.find(ownOf) || null; const since = k => Math.round((Date.parse(t) - Date.parse(k || t)) / 86400000); if (q.get("nudge")) { // what this device should be nudged about right now (shown on every page) const self = me && !me.pending && me.lastSeen !== t && hr >= 9 ? { id: me.id, first: me.name.split(" ")[0] } : null; if (!st.full) return { res: json({ onsite: true, today: t, hour: hr, me: me ? me.id : null, self, asks: [], devAsks: [], list: [], more: 0, limited: true }), cookie }; const out = []; for (const x of list) { if ((me && x.id === me.id) || x.pending || x.unvouched) continue; const d = x.lastSeen ? since(x.lastSeen) : 99, u = x.pattern !== true ? null : usual(pats[x.id], t); // "due" starts at 10 in the morning of the day it falls due, so nobody is flagged at five past midnight const due = d > x.days || (d === x.days && hr >= 10), quiet = !due && d > 0 && u && !u.learning && (u.quiet || u.missedYesterday); const fam = !!x.famWorry, noAns = !!x.noAnswer; if (!due && !quiet && !fam && !noAns) continue; const buddies = (x.buddies || []).filter(y => list.some(z => z.id === y)), buddy = !!me && buddies.includes(me.id); // The early "not their usual pattern" nudge goes to that person's buddies; if they have none on the list, to every vouched-for neighbor. if (quiet && !fam && !noAns && !buddy && buddies.length) continue; out.push({ id: x.id, name: x.name, apt: x.apt, stage: fam ? "family" : (due ? "due" : "quiet"), days: d, by: u && !u.learning ? u.by : null, buddy, checking: x.checking && x.checking.day === t ? { by: x.checking.by } : null, noAnswer: noAns ? { by: x.noAnswer.by, desk: x.noAnswer.desk ? x.noAnswer.desk.by : null } : null }); } out.sort((a, b) => (b.noAnswer ? 1 : 0) - (a.noAnswer ? 1 : 0) || (b.stage === "family" ? 1 : 0) - (a.stage === "family" ? 1 : 0) || (b.buddy ? 1 : 0) - (a.buddy ? 1 : 0) || b.days - a.days); const asks = me ? list.filter(x => (x.buddyAsk || []).includes(me.id)).map(x => ({ id: x.id, name: x.name, apt: x.apt })) : []; const devAsks = me ? list.flatMap(x => Object.entries(x.devAsk || {}).filter(([, a]) => a.ok !== true && a.nid !== st.nid).map(([k, a]) => ({ id: x.id, name: x.name, mine: x.id === me.id, buddy: (x.buddies || []).includes(me.id), ask: k, kind: a.kind, said: (a.who || []).includes(me.id) }))) .filter(a => a.mine || a.buddy || !a.said).slice(0, 4) : []; return { res: json({ onsite: true, today: t, hour: hr, me: me ? me.id : null, self, asks, devAsks, list: out.slice(0, 6), more: Math.max(0, out.length - 6) }), cookie }; } // What each row shows. Your own row: everything about you (device entries by id so you can unlink one). Anyone else's row: // name, apartment, the day of their last sign and how sure it is. No device ids, no exact times, no family, no consent record. const row = x => { const isMe = !!me && x.id === me.id, pat = x.pattern !== true ? null : usual(pats[x.id], t), d = x.lastSeen ? since(x.lastSeen) : 99; const base = { id: x.id, name: x.name, apt: x.apt, days: x.days, lastSeen: x.lastSeen, joined: x.joined, pending: !!x.pending || undefined, invitedBy: x.pending ? x.invitedBy : undefined, unvouched: !!x.unvouched || undefined, due: d > x.days || (d === x.days && hr >= 10), sig: x.sig || {}, signsToday: Object.values(x.devs || {}).filter(e => e.day === t).map(e => ({ kind: e.kind, where: e.where })), checking: x.checking && x.checking.day === t ? { by: x.checking.by } : undefined, noAnswer: x.noAnswer ? { by: x.noAnswer.by, desk: x.noAnswer.desk ? x.noAnswer.desk.by : undefined } : undefined, famWorry: x.famWorry ? true : undefined, quiet: pat && !pat.learning ? !!(pat.quiet || pat.missedYesterday) : undefined, usualBy: pat && !pat.learning && pat.most ? pat.by : undefined, buddies: x.buddies || [], buddyAsk: isMe ? (x.buddyAsk || []) : ((x.buddyAsk || []).includes(me ? me.id : "") ? [me.id] : []) }; if (!isMe) return base; return Object.assign(base, { agreed: x.agreed, autoDevice: x.autoDevice !== false, pattern: x.pattern === true, pat, fam: (x.family || []).length, devs: Object.fromEntries(Object.entries(x.devs || {}).map(([k, e]) => [k, { kind: e.kind, day: e.day, where: e.where, n: e.n, auto: e.auto !== false }])), devAsk: Object.fromEntries(Object.entries(x.devAsk || {}).filter(([, a]) => a.ok !== true).map(([k, a]) => [k, { kind: a.kind }])) }); }; const waiting = !me && st.nid ? list.filter(x => Object.values(x.devAsk || {}).some(a => a.nid === st.nid)).map(x => ({ id: x.id, name: x.name, allowed: Object.values(x.devAsk).some(a => a.nid === st.nid && a.ok === true) })) : []; return { res: json({ onsite: true, today: t, hour: hr, network: !!v.signals.network, full: st.full, limited: !st.full, me: me ? me.id : null, waiting, list: list.filter(x => st.full || (me && x.id === me.id)).map(row) }), cookie }; } // ---------- Marketplace: listings shared by everyone on site ---------- async function market(request, env, st) { const kv = env.HUB, K = "market:list"; let list = await getJ(kv, K, []); if (request.method === "POST") { const b = await request.json().catch(() => ({})); if (b.op === "add") { const title = clean(b.title, 80); if (!title) return json({ error: "Say what you are offering." }, 400); const photo = typeof b.photo === "string" && /^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/.test(b.photo) && b.photo.length < 260000 ? b.photo : ""; list.unshift({ id: id(), title, desc: clean(b.desc, 300), type: ["sale", "donation", "free", "need", "offer"].includes(b.type) ? b.type : "sale", price: clean(b.price, 10).replace(/[^0-9.]/g, ""), name: clean(b.name, 40) || "A neighbor", contact: clean(b.contact, 60) || "Ask at the front desk", photo, posted: dayKey(), owner: st.nid }); list = list.slice(0, 60); } else if (b.op === "gone") { // marked as gone: no longer shown, record kept const p = list.find(x => x.id === b.id); if (p && p.owner && p.owner !== st.nid) return json({ error: "Only the neighbor who posted it can take it down." }, 403); if (p) { p.gone = dayKey(); } } else return json({ error: "op" }, 400); await kv.put(K, JSON.stringify(list)); } else if (request.method !== "GET") return json({ error: "method" }, 405); return json({ onsite: true, list: list.filter(x => !x.gone).map(x => { const o = Object.assign({}, x, { mine: !!x.owner && x.owner === st.nid }); delete o.owner; return o; }) }); } // ---------- Vouching: a confirmed neighbor confirms that a new device belongs to someone who lives here ---------- // The new device asks for a 4-digit number (good for 15 minutes) and shows it. The neighbor types it on their own // confirmed device. The new device then claims it, which adds the "vouched" signal to its signed cookie. async function vouch(request, env, v, st) { if (request.method !== "POST") return { res: json({ error: "method" }, 405) }; const b = await request.json().catch(() => ({})), kv = env.HUB, code = String(b.code || "").replace(/\D/g, "").slice(0, 4); if (b.op === "ask") { // the new neighbor's device asks for a number; the number only ever works for that device if (!st.optedIn || !st.nid) return { res: json({ ok: false, needYes: true, error: "Say yes to remembering this device first." }, 409) }; for (let i = 0; i < 8; i++) { const c = String(1000 + Math.floor(Math.random() * 9000)); if (await kv.get("vouch:" + c)) continue; // never reuse or overwrite a number that is in play await kv.put("vouch:" + c, JSON.stringify({ ok: false, nid: st.nid }), { expirationTtl: 900 }); return { res: json({ ok: true, code: c, minutes: 15 }) }; } return { res: json({ ok: false, error: "Many neighbors are being vouched for right now. Please try again in a minute." }, 429) }; } if (b.op === "gift") { // a vouched-for neighbor makes a one-time square to show; the new neighbor just scans it if (!st.full) return { res: json({ ok: false, error: "Only a neighbor who was vouched for can vouch for someone else." }, 403) }; const t = token(14); await kv.put("vouch:g" + t, JSON.stringify({ ok: true }), { expirationTtl: 900 }); return { res: json({ ok: true, token: t, minutes: 15 }) }; } if (b.op === "give") { if (!st.full) return { res: json({ error: "Only a neighbor who was vouched for can vouch for someone else." }, 403) }; const cur = code.length === 4 ? await kv.get("vouch:" + code, "json") : null; if (!cur) return { res: json({ error: "That number was not found. It may have run out; ask your neighbor for a new one." }, 404) }; await kv.put("vouch:" + code, JSON.stringify({ ok: true, nid: cur.nid }), { expirationTtl: 900 }); return { res: json({ ok: true }) }; } if (b.op === "found") { // the very first neighbor. Needs the starter key held by the person who runs the site. if (!st.resident) return { res: json({ ok: false, error: "Enter the on-site code first." }, 403) }; if (!env.FOUNDER_KEY || String(b.key || "") !== String(env.FOUNDER_KEY)) return { res: json({ ok: false, error: "The circle is started by the person who runs this site. Ask a neighbor to vouch for you." }, 403) }; if (await kv.get("founder")) return { res: json({ ok: false, error: "The circle is already started. Ask a neighbor to vouch for you." }, 409) }; await kv.put("founder", new Date().toISOString()); const s2 = await standing(request, env, v, { f: 1 }); return { res: json({ ok: true, full: s2.full }), cookie: s2.setCookie }; } if (b.op === "claim") { // Answers "not yet" the same way whether or not the number exists, so numbers cannot be found by guessing. if (!st.optedIn || !st.nid) return { res: json({ ok: false, needYes: true }) }; const tk = String(b.token || "").replace(/[^a-z0-9]/g, "").slice(0, 20), key = tk ? "vouch:g" + tk : (code.length === 4 ? "vouch:" + code : ""); const cur = key ? await kv.get(key, "json") : null; if (!cur) return { res: json({ ok: false, gone: !!tk, error: tk ? "This square was already used or has run out. Ask your neighbor for a new one." : undefined }) }; if (!tk && cur.nid !== st.nid) return { res: json({ ok: false }) }; // a number works only on the device that asked for it if (!cur.ok) return { res: json({ ok: false }) }; const s2 = await standing(request, env, v, { v: 1 }); if (!s2.full) return { res: json({ ok: false, error: "This device could not keep the vouch. Please try again." }) }; // not used up unless it worked await kv.delete(key); return { res: json({ ok: true, resident: s2.resident, full: s2.full, standing: s2.signals, count: s2.count }), cookie: s2.setCookie }; } return { res: json({ error: "op" }, 400) }; } // ---------- Family nudges, by consent ---------- // Nothing about a resident reaches family unless the resident invites that family member from their own linked device. // The invitation records the consent (who, what they may see, when). The resident can end it at any time. // A family member's phone holds a signed link to that one person only: it can never see the list or anyone else. // level "nudge" — family is told only when something is off level "daily" — family also sees "a sign today" // Family can answer "I talked to them" (counts as a sign) or "I can't reach them" (asks neighbors on site to knock). const FAM = "pt_fam"; const token = (n) => { const a = crypto.getRandomValues(new Uint8Array(n)); return [...a].map(x => "abcdefghjkmnpqrstuvwxyz23456789"[x % 31]).join(""); }; async function family(request, env, v, st, url) { const kv = env.HUB, K = "checkin:list", today = dayKey(), now = new Date().toISOString(); let list = await getJ(kv, K, []); const links = ((await readSigned(env, request, FAM)) || {}).l || []; const mine = () => links.map(l => { const p = list.find(x => x.id === l.p), f = p && (p.family || []).find(y => y.fid === l.f); return p && f ? { p, f } : null; }).filter(Boolean); if (request.method === "GET") { // what this family phone may see const pats = await getJ(kv, "checkin:patterns", {}); const since = k => Math.round((Date.parse(today) - Date.parse(k || today)) / 86400000); const out = mine().map(({ p, f }) => { const d = p.lastSeen ? since(p.lastSeen) : 99, u = p.pattern !== true ? null : usual(pats[p.id], today); const state = (d > p.days || (d === p.days && hourNow() >= 10)) ? "due" : (d > 0 && u && !u.learning && (u.quiet || u.missedYesterday) ? "quiet" : "ok"); const o = { fid: f.fid, first: p.name.split(" ")[0], you: f.label, level: f.level, state, noAnswer: !!p.noAnswer, worry: !!p.famWorry }; // Family never gets hours, counts, patterns or places: only whether a call would be welcome, and how pressing it is. if (state === "due") o.span = d >= 4 ? "several days" : "a couple of days"; else if (state === "ok" && f.level === "daily") o.today = d === 0; return o; }); return { res: json({ ok: true, family: out, hour: hourNow() }) }; } if (request.method !== "POST") return { res: json({ error: "method" }, 405) }; const b = await request.json().catch(() => ({})); // ---- the resident's side: only from a confirmed device that is linked to that person ---- const ownP = x => !!x && !!st.pid && st.pid === x.id && !(x.revoked || []).includes(st.nid); if (b.op === "myrecord") { // "show me what you hold about me": the whole record, to its owner's own device only const p = list.find(x => x.id === b.id); if (!st.resident || !ownP(p)) return { res: json({ ok: false }, 403) }; const pats = await getJ(kv, "checkin:patterns", {}), safe = JSON.parse(JSON.stringify(p)); for (const d of Object.values(safe.devs || {})) delete d.nid; for (const a of Object.values(safe.devAsk || {})) delete a.nid; delete safe.revoked; return { res: json({ ok: true, person: safe, pattern: pats[p.id] || null }) }; } if (["invite", "revoke", "mine", "uninvite"].includes(b.op)) { const p = list.find(x => x.id === b.id); if (!st.resident || !ownP(p) || p.pending) return { res: json({ error: "Only the person themselves, on their own device, can share with family or friends." }, 403) }; if (b.op === "invite") { const label = clean(b.label, 40); if (!label) return { res: json({ error: "Say who this is for, like “my daughter Ann”." }, 400) }; p.invites = (p.invites || []).filter(i => Date.parse(i.at) > Date.now() - 7 * 86400000); if ((p.family || []).length + p.invites.length >= 5) return { res: json({ error: "Five people is the most. End one first." }, 400) }; const t = token(20), level = b.level === "daily" ? "daily" : "nudge"; await kv.put("faminv:" + t, JSON.stringify({ pid: p.id, label, level, at: now }), { expirationTtl: 7 * 86400 }); p.invites.push({ t, label, level, at: now }); p.consents = (p.consents || []).concat({ what: "family-invite", label, level, at: now }).slice(-60); await kv.put(K, JSON.stringify(list)); return { res: json({ ok: true, token: t, days: 7 }) }; } if (b.op === "uninvite") { // cancel an invitation that has not been opened yet const i = (p.invites || []).find(x => x.t === b.token); if (i) { p.invites = p.invites.filter(x => x !== i); await kv.delete("faminv:" + i.t); await kv.put(K, JSON.stringify(list)); } } if (b.op === "revoke") { const f = (p.family || []).find(y => y.fid === b.fid); if (f) { p.family = p.family.filter(y => y.fid !== b.fid); p.consents = (p.consents || []).concat({ what: "family-ended", label: f.label, at: now }).slice(-60); await kv.put(K, JSON.stringify(list)); } } const live = (p.invites || []).filter(i => Date.parse(i.at) > Date.now() - 7 * 86400000); return { res: json({ ok: true, family: (p.family || []).map(f => ({ fid: f.fid, label: f.label, level: f.level, since: f.since })), waiting: live.map(i => ({ token: i.t, label: i.label, level: i.level, at: i.at })), consents: (p.consents || []).slice(-25).reverse() }) }; } // ---- the family member's side ---- if (b.op === "peek" || b.op === "accept") { // peek: who is inviting me (nothing is used up). accept: only on the person's own tap. const t = clean(b.token, 40).replace(/[^a-z0-9]/g, ""), inv = t ? await getJ(kv, "faminv:" + t, null) : null; if (!inv) return { res: json({ ok: false, error: "This invitation was already used or has run out. Ask for a new one." }, 404) }; const p = list.find(x => x.id === inv.pid); if (!p) return { res: json({ ok: false, error: "That person is no longer on the list." }, 404) }; if (b.op === "peek") return { res: json({ ok: true, first: p.name.split(" ")[0], label: inv.label, level: inv.level }) }; if ((p.family || []).length >= 5) return { res: json({ ok: false, error: "They are already sharing with five people. Ask them to end one first." }, 409) }; const fid = token(10), l = links.filter(x => x.p !== p.id).concat({ p: p.id, f: fid }).slice(-6); const ck = await mintSigned(env, FAM, { l }, 730, request); // write the phone's link first; the invitation is used up only if that worked if (!ck) return { res: json({ ok: false, error: "This phone could not keep the link. Please open the invitation again." }, 409) }; p.family = (p.family || []).concat({ fid, label: inv.label, level: inv.level, since: today, opened: today }); p.invites = (p.invites || []).filter(i => i.t !== t); p.consents = (p.consents || []).concat({ what: "family-accepted", label: inv.label, at: now }).slice(-60); await kv.put(K, JSON.stringify(list)); await kv.delete("faminv:" + t); return { res: json({ ok: true, first: p.name.split(" ")[0] }), cookie: ck }; } if (b.op === "talked" || b.op === "worry" || b.op === "leave") { const m = mine().find(x => x.f.fid === b.fid); if (!m) return { res: json({ ok: false, error: "This link is no longer active." }, 403) }; const p = m.p; if (b.op === "talked") { if (p.lastSeen === today && !p.noAnswer && !p.famWorry) return { res: json({ ok: true, nothingToClear: true }) }; p.lastSeen = today; p.by = (p.by || []).concat(today).slice(-30); p.sig = p.sig || {}; p.sig.family = today; delete p.checking; delete p.noAnswer; delete p.famWorry; if (p.pattern === true) { const pats = await getJ(kv, "checkin:patterns", {}); if (notePattern(pats, p.id, "neighbor", today)) await kv.put("checkin:patterns", JSON.stringify(pats)); } } else if (b.op === "worry") p.famWorry = { label: "Their family", day: today, at: now }; else { p.family = (p.family || []).filter(y => y.fid !== b.fid); p.consents = (p.consents || []).concat({ what: "family-left", label: m.f.label, at: now }).slice(-60); } await kv.put(K, JSON.stringify(list)); return { res: json({ ok: true }) }; } return { res: json({ error: "op" }, 400) }; } // ---------- Tech help counts (de-identified) ---------- // One record per day: how many times each help topic was opened, said to be fixed, or left someone stuck, by device family. // No name, no person id, no device id, no address is received or stored. Used to show what neighbors most need help with. const TECH_TOPICS = ["text", "wifi", "sound", "home", "restart", "video", "scam", "update"], TECH_FAM = ["ios", "android", "windows", "mac", "other"], TECH_WHAT = ["open", "fixed", "stuck"]; async function tech(request, env, counts) { const kv = env.HUB, today = dayKey(); if (request.method === "POST") { const b = await request.json().catch(() => ({})); if (!TECH_TOPICS.includes(b.topic) || !TECH_FAM.includes(b.fam) || !TECH_WHAT.includes(b.what)) return json({ error: "bad" }, 400); if (b.dry === true) return json({ ok: true, dry: true, wouldStore: { key: "tech:" + today, add1To: b.topic + "|" + b.fam + "|" + b.what }, ignoredFromYourRequest: Object.keys(b).filter(k => !["topic", "fam", "what", "dry"].includes(k)) }); if (!counts) return json({ ok: true, counted: false, why: "This device has not said yes to counting." }); const rec = await getJ(kv, "tech:" + today, {}), k = b.topic + "|" + b.fam + "|" + b.what; rec[k] = Math.min((rec[k] || 0) + 1, 100000); await kv.put("tech:" + today, JSON.stringify(rec), { expirationTtl: 400 * 86400 }); return json({ ok: true }); } if (request.method !== "GET") return json({ error: "method" }, 405); const tot = {}; const days = await kv.list({ prefix: "tech:" }); const cut = dayAdd(today, -30); for (const key of days.keys) { const d = key.name.slice(5); if (d < cut) continue; const rec = await getJ(kv, key.name, {}); for (const [k, n] of Object.entries(rec)) { const [topic, , what] = k.split("|"); const t = tot[topic] = tot[topic] || { topic, n: 0, fixed: 0, stuck: 0 }; if (what === "open") t.n += n; else t[what] += n; } } return json({ ok: true, days: 30, topics: Object.values(tot).filter(x => x.n).sort((a, b) => b.n - a.n) }); } // ---------- Audit: an inventory of everything this site's storage holds, by kind ---------- // Founder-only (same starter key as starting the circle). Returns how many records of each kind exist and their names' shapes, never their contents. Anything that does not // match a known kind is reported as "unexpected", so a reader can see there is no hidden store of locations, addresses or logs. const KINDS = [["checkin:list", "The Check-In list (one record holding every person who joined)"], ["checkin:patterns", "Usual-pattern hours, under random numbers"], ["market:list", "Lend a hand listings"], ["menuphoto:", "Menu photos and the pointer to the latest one"], ["keep:", "Locked device backups the site cannot open"], ["vouch:", "Vouch numbers (erase themselves after 15 minutes)"], ["founder", "The date the first neighbor started the circle"], ["keepproof:", "Proof-page samples (erase themselves after 5 minutes)"], ["codefail:", "A count of wrong code tries per hour (no names)"], ["faminv:", "Family and friend invitations (erase themselves after 7 days)"], ["tech:", "Daily tech-help counts"]]; async function audit(env) { const kv = env.HUB, counts = KINDS.map(([p, what]) => ({ prefix: p, what, records: 0 })); let unexpected = 0, total = 0, cursor; do { const page = await kv.list({ cursor, limit: 1000 }); cursor = page.list_complete ? null : page.cursor; for (const k of page.keys) { total++; const c = counts.find(x => k.name === x.prefix || (x.prefix.endsWith(":") && k.name.startsWith(x.prefix))); if (c) c.records++; else unexpected++; } } while (cursor && total < 20000); const list = await getJ(kv, "checkin:list", []); return json({ ok: true, at: new Date().toISOString(), total, unexpected, kinds: counts.map(c => ({ prefix: c.prefix, what: c.what, records: c.records > 0 ? (c.prefix.endsWith(":") ? "some" : 1) : 0 })), fieldsKeptPerPerson: [...new Set(list.flatMap(p => Object.keys(p)))].sort(), fieldsKeptPerDevice: [...new Set(list.flatMap(p => Object.values(p.devs || {}).flatMap(d => Object.keys(d))))].sort() }); } // ---------- Keep: so a new or replacement phone does not start over ---------- // Each device backs up its own small settings (pet, game progress, text size, Check-In link) once a day. // The backup is locked ON THE DEVICE with a key made from the owner's keep phrase before it is sent, and it is filed // under a number also made on the device from the phrase. This site never receives the phrase, so it cannot open a backup. // The one thing the site adds is "res": whether a confirmed device made the backup (used as one confirmation signal). async function sha(t) { const b = await crypto.subtle.digest("SHA-256", new TextEncoder().encode("keep:" + t)); return [...new Uint8Array(b)].map(x => x.toString(16).padStart(2, "0")).join(""); } async function keep(request, env, v, st) { if (request.method !== "POST") return { res: json({ error: "method" }, 405) }; const b = await request.json().catch(() => ({})), kv = env.HUB; const kid = String(b.kid || ""); if (!/^[a-f0-9]{64}$/.test(kid)) return { res: json({ ok: false, error: "That does not look like a keep phrase." }, 400) }; const key = "keep:" + (await sha(kid)); if (b.op === "save") { const enc = String(b.enc || ""); if (b.proof === true) { // the Proof page's made-up sample: small, kept apart, and gone in five minutes if (!/^[A-Za-z0-9+/=]{40,4000}$/.test(enc)) return { res: json({ error: "bad sample" }, 400) }; await kv.put("keepproof:" + (await sha(kid)), JSON.stringify({ enc, at: new Date().toISOString() }), { expirationTtl: 300 }); return { res: json({ ok: true, proof: true }) }; } if (!opted(request, "k")) return { res: json({ ok: false, error: "Backups are off on this device." }, 409) }; if (!st.resident) return { res: json({ ok: false, error: "Backups are for residents' devices." }, 403) }; if (!/^[A-Za-z0-9+/=]{40,300000}$/.test(enc)) return { res: json({ error: "bad backup" }, 400) }; const old = await getJ(kv, key, null); // "res": a fully confirmed device made this backup. "pid": whose it is, so a restore can only ever link back to that same person. await kv.put(key, JSON.stringify({ enc, res: !!(st.full || (old && old.res)), pid: st.pid || (old && old.pid) || "", at: new Date().toISOString() })); return { res: json({ ok: true, at: new Date().toISOString() }) }; } if (b.op === "load") { const rec = (b.proof === true ? await getJ(kv, "keepproof:" + (await sha(kid)), null) : null) || await getJ(kv, key, null); if (!rec || !rec.enc) return { res: json({ ok: false, error: "No backup was found for that phrase. Check the spelling and the number at the end." }, 404) }; let cookie = null, s2 = st; if (rec.res && b.proof !== true && !st.full) { const recent = (rec.used || []).filter(t => Date.now() - Date.parse(t) < 30 * 86400000); if (recent.length < 2) { // otherwise the settings still come back, but the phrase confirms nothing more s2 = await standing(request, env, v, { k: 1, kp: rec.pid || "" }); cookie = s2.setCookie; if (s2.full) { rec.used = recent.concat(new Date().toISOString()); await kv.put(key, JSON.stringify(rec)); if (rec.pid) { const L = await getJ(kv, "checkin:list", []), q = L.find(x => x.id === rec.pid); if (q) { q.consents = (q.consents || []).concat({ what: "restored-on-a-new-device", at: new Date().toISOString() }).slice(-60); await kv.put("checkin:list", JSON.stringify(L)); } } } } } return { res: json({ ok: true, enc: rec.enc, at: rec.at, resident: s2.resident, standing: s2.signals }), cookie }; } if (b.op === "erase") { await kv.delete("keepproof:" + (await sha(kid))); if (b.proof !== true) await kv.delete(key); return { res: json({ ok: true }) }; } return { res: json({ error: "op" }, 400) }; } // Gentle signs of life (added 2026-12-03, preprod). The site stores only a daily // indicator ("ok" or "unsure"), the person's opt-in and away flags, and private // friend replies used for the 2-of-3 rule. Replies are never returned to other // friends. Rhythm and raw signs stay on the person's device. async function life(request, env, v, st) { const today = dayKey(); const hourRaw = Number(new Date().toLocaleString("en-US", { timeZone: TZ, hour: "numeric", hour12: false })); const hour = hourRaw === 24 ? 0 : hourRaw; const quiet = hour >= 20 || hour < 9; const all = await getJ(env.HUB, "life:state", {}); const pid = st.pid || ""; function rec(id) { const r = Object.assign({ on: false, away: false, state: "unsure", here: false, replies: {} }, all[id] || {}); if (r.day !== today) { r.day = today; r.state = r.away ? "ok" : "unsure"; r.here = false; r.replies = {}; r.follow = false; // Keep selfAsked from a previous day so the 24-hour wait can complete. } return r; } async function save() { await env.HUB.put("life:state", JSON.stringify(all)); } // Small virtual gifts (added 2026-12-03). Stored: sender, recipient, gift type, preset message number, day. Nothing else. Gone after 7 days. const GIFTS = ["wave", "coffee", "flower", "sun", "note", "cookie", "lunch"]; const gday = d => Math.round((Date.parse(today) - Date.parse(d)) / 86400000); const firstOf = p => String((p && p.name) || "a neighbor").split(" ")[0].slice(0, 24); const loadGifts = async () => (await getJ(env.HUB, "life:gifts", [])).filter(g => g && gday(g.d) <= 7 && gday(g.d) >= -1); const saveGifts = gl => env.HUB.put("life:gifts", JSON.stringify(gl)); const canGive = (list, mine, to) => !!mine && !!to && to.id !== pid && !to.pending && (st.full || (to.buddies || []).includes(pid) || (mine.buddies || []).includes(to.id)); if (request.method === "GET") { const me = pid ? rec(pid) : { on: false, away: false, state: "unsure" }; const out = { ok: true, today, hour, canUse: !!(st.resident && pid), on: !!me.on, away: !!me.away, state: me.on ? (me.state === "ok" ? "ok" : "unsure") : null, selfReminder: false, needAskStamp: false, askFriend: null, circle: 0 }; if (me.on && pid && !me.away && me.state !== "ok" && !quiet) { out.selfReminder = true; out.needAskStamp = !me.selfAsked; } if (st.resident && pid) { const list = await getJ(env.HUB, "checkin:list", []); const mine = list.find(p => p && p.id === pid); if (me.on && mine) out.circle = (mine.buddies || []).filter(Boolean).length; if (!quiet) { for (const p of list) { if (!p || p.id === pid) continue; if (!(p.buddies || []).includes(pid)) continue; const r = rec(p.id); if (!r.on || r.away || r.state === "ok") continue; if (!r.selfAsked || r.selfAsked >= today) continue; if ((r.replies || {})[pid]) continue; const first = String(p.first || p.name || "a neighbor").split(" ")[0]; out.askFriend = { id: p.id, first: first }; break; } } } out.gifts = []; out.people = []; out.mutedAny = !!(all[pid] && (all[pid].mutes || []).length); if (st.resident && pid) { const list = await getJ(env.HUB, "checkin:list", []); const mine = list.find(p => p && p.id === pid); out.people = list.filter(p => p && p.id && canGive(list, mine, p)).slice(0, 40).map(p => ({ id: p.id, first: firstOf(p) })); const muted = (all[pid] && all[pid].mutes) || []; out.gifts = (await loadGifts()).filter(g => g.t === pid && gday(g.d) <= 3 && !muted.includes(g.f)).slice(0, 3).map(g => { const f = list.find(p => p && p.id === g.f); return { k: g.f + "." + g.d + "." + g.g, from: g.f, first: firstOf(f), g: g.g, m: g.m }; }); } return json(out); } if (request.method !== "POST") return json({ error: "method" }, 405); if (!st.resident || !pid) return json({ error: "This is for confirmed neighbors." }, 403); let body = {}; try { body = await request.json(); } catch (e) { return json({ error: "bad" }, 400); } const op = body.op; if (op === "gift") { if (!GIFTS.includes(body.g)) return json({ error: "gift" }, 400); const m = Number.isInteger(body.m) && body.m >= 0 && body.m < 4 ? body.m : -1; const list = await getJ(env.HUB, "checkin:list", []); const mine = list.find(p => p && p.id === pid), to = list.find(p => p && p.id === body.to); if (!canGive(list, mine, to)) return json({ error: "That person is not in your circle." }, 403); const gl = await loadGifts(); const today5 = gl.filter(x => x.f === pid && x.d === today); if (today5.length >= 5) return json({ ok: false, note: "That is plenty for today. Tomorrow is a good day for another." }); if (today5.some(x => x.t === to.id)) return json({ ok: false, note: "You already sent them something today." }); const muted = ((all[to.id] && all[to.id].mutes) || []).includes(pid); if (!muted) gl.push({ f: pid, t: to.id, g: body.g, m, d: today }); await saveGifts(gl); return json({ ok: true }); } if (op === "giftdone") { const gl = await loadGifts(); await saveGifts(gl.filter(x => !(x.t === pid && (x.f + "." + x.d + "." + x.g) === body.k))); return json({ ok: true }); } if (op === "mute" || op === "unmuteall") { const r = rec(pid); all[pid] = r; if (op === "mute") { r.mutes = (r.mutes || []).filter(x => x !== body.from).concat(String(body.from || "").slice(0, 40)).slice(-40); const gl = await loadGifts(); await saveGifts(gl.filter(x => !(x.t === pid && x.f === body.from))); } else r.mutes = []; await save(); return json({ ok: true }); } const me = rec(pid); all[pid] = me; if (op === "opt") { me.on = !!body.on; if (!me.on) { me.away = false; me.state = "unsure"; me.here = false; me.selfAsked = null; me.replies = {}; me.follow = false; } else { me.selfAsked = null; } await save(); return json({ ok: true, on: me.on, away: me.away, state: me.on ? (me.state === "ok" ? "ok" : "unsure") : null }); } if (op === "away") { if (!me.on) return json({ error: "off" }, 400); me.away = !!body.on; if (me.away) { me.state = "ok"; me.selfAsked = null; me.replies = {}; me.follow = false; } await save(); return json({ ok: true, away: me.away, state: me.state === "ok" ? "ok" : "unsure" }); } if (op === "asked") { if (me.on && !me.away && me.state !== "ok" && !me.selfAsked) me.selfAsked = today; await save(); return json({ ok: true }); } if (op === "here") { if (!me.on) return json({ error: "off" }, 400); me.here = true; me.state = "ok"; me.away = false; me.replies = {}; me.follow = false; me.selfAsked = null; await save(); return json({ ok: true, state: "ok" }); } if (op === "indicator") { if (!me.on) return json({ error: "off" }, 400); // The device may raise the day to "ok". It cannot force a friend question. if (body.state === "ok") { me.state = "ok"; me.replies = {}; me.follow = false; me.selfAsked = null; } await save(); return json({ ok: true, state: me.state === "ok" ? "ok" : "unsure" }); } if (op === "reply") { const list = await getJ(env.HUB, "checkin:list", []); const p = list.find(x => x && x.id === body.id); if (!p || !(p.buddies || []).includes(pid)) return json({ error: "not in that circle" }, 403); const r = rec(p.id); all[p.id] = r; if (!r.on || r.away || r.state === "ok") return json({ ok: true, state: r.state === "ok" ? "ok" : "unsure" }); const ans = body.ans; if (ans !== "yes" && ans !== "noheard" && ans !== "nottoday") return json({ error: "ans" }, 400); r.replies = r.replies || {}; r.replies[pid] = ans; if (ans === "yes") { r.state = "ok"; r.replies = {}; r.follow = false; r.selfAsked = null; } else { const buds = (p.buddies || []).filter(Boolean); const nos = buds.filter(id => r.replies[id] === "noheard" || r.replies[id] === "nottoday"); r.follow = nos.length >= 2; } await save(); return json({ ok: true }); } return json({ error: "unknown" }, 400); } export async function onRequest({ request, env, params }) { const v = await verify(request, env, null); if (params.name === "audit") { if (!(await isFounder(request, env))) return json({ error: "not found" }, 404); if (!env.HUB) return json({ error: "no store" }, 503); return audit(env); } if (!env.HUB) return json({ error: "The shared store is not set up for this site." }, 503); if (request.method === "POST") { // same-origin posts only const o = request.headers.get("origin"); let same = true; if (o) { try { same = new URL(o).host === new URL(request.url).host; } catch (e) { same = false; } } if (!same) return json({ error: "origin" }, 403); } const st = await standing(request, env, v); // resident or not is decided by the server from signed signals const open = ["keep", "family", "tech", "vouch", "life"].includes(params.name); if (!v.ok && !st.onsite && !open) return json({ onsite: false, error: "This part is for people at Park Terrace. Confirm this device once on the Neighbors page." }, 403); const url = new URL(request.url), n = params.name; let res, extra = null, extra2 = null; // Names, listings and uploads are for confirmed residents. Looking at the shared menu photo needs only the on-site gate. // Your own use of the Hub needs a "resident" device. Anything that shows or changes OTHER people needs a "full" one // (vouched for by a neighbor). Looking at the shared menu photo needs only the on-site gate. const needsFull = n === "market" || (n === "menu-photo" && request.method === "POST"); if (n === "checkin" && !st.resident) res = json({ onsite: true, resident: false, full: false, standing: st.signals, error: "This part is for residents. Confirm this device once on the Neighbors page." }, 403); else if (needsFull && !st.full) res = json({ onsite: true, resident: st.resident, full: false, standing: st.signals, error: st.resident ? "This part opens once a neighbor has vouched for you. It takes them a few seconds, on the Neighbors page." : "This part is for residents. Confirm this device once on the Neighbors page." }, 403); else if (n === "menu-photo") res = await menuPhoto(request, env, url); else if (n === "checkin") { const o = await checkin(request, env, v, st); res = o.res; extra = o.cookie || null; } else if (n === "market") res = await market(request, env, st); else if (n === "vouch") { const o = await vouch(request, env, v, st); res = o.res; extra = o.cookie; } else if (n === "tech") res = await tech(request, env, opted(request, "t")); else if (n === "keep") { const o = await keep(request, env, v, st); res = o.res; extra = o.cookie; } else if (n === "family") { const o = await family(request, env, v, st, url); res = o.res; extra2 = o.cookie; } else if (n === "life") res = await life(request, env, v, st); else res = json({ error: "not found" }, 404); let navCk = null; if (st.onsite && !v.signals.network && !v.signals.nav && devKey(request) && !probing(request)) navCk = await mintNav(env, request); if (st.setCookie || extra || extra2 || navCk) { res = new Response(res.body, res); [extra || st.setCookie, extra2, navCk].filter(Boolean).forEach(c => res.headers.append("set-cookie", c)); } return res; }