// On-site verification for theterrace.mik3s.us /local/* — a "constellation" of signals, any one admits: // 1. network — the visitor's public IP is one of the building's Wi-Fi egress IPs (env ONSITE_IPS, comma-separated) // 2. device — a signed cookie minted earlier on a device that already passed (survives leaving the building) // 3. code — the on-site passcode (env ONSITE_CODE), entered once // A device cookie is minted whenever signal 1 or 3 succeeds, so the phone/tablet/computer each get verified once. // Env vars live in the Pages project (Settings → Variables): ONSITE_IPS, ONSITE_CODE, ONSITE_SECRET. const COOKIE = "pt_onsite"; const DAYS = 180; function b64url(buf) { return btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } async function hmac(secret, msg) { const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); return b64url(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(msg))); } function ipList(env) { return (env.ONSITE_IPS || "").split(/[,\s]+/).map(s => s.trim()).filter(Boolean); } // True opt-in. The cookie pt_opt holds the choices a person has said yes to on this device, one letter each: // s = remember this device (signs that it belongs here) k = back up my settings t = count the help topics I open // Without the letter, the matching thing is not written, not sent and not stored. The site sets nothing on a first visit. export function opted(request, letter) { const m = /(?:^|;\s*)pt_opt=([a-z]*)/.exec(request.headers.get("cookie") || ""); return !!m && m[1].includes(letter); } // ---- Sealed notes (added 2026-11-20). The notes this site keeps on a device are encrypted, not just signed, and are honoured // only when enough about the request matches the device they belong to (see weigh() below): a constellation, not a single lock. // Fail closed: with no secret configured, no note can be made or read, and the gate lets nobody through by cookie. function need(env) { if (!env.ONSITE_SECRET) throw new Error("site secret is not configured"); return String(env.ONSITE_SECRET); } export function uaFam(request) { const u = request.headers.get("user-agent") || ""; const os = /iPhone|iPod/.test(u) ? "iphone" : /iPad/.test(u) ? "ipad" : /Android/.test(u) ? "android" : /Windows/.test(u) ? "win" : /Macintosh/.test(u) ? "mac" : /CrOS/.test(u) ? "cros" : /Linux/.test(u) ? "linux" : "other"; const br = /Edg/.test(u) ? "edge" : /SamsungBrowser/.test(u) ? "samsung" : /Firefox|FxiOS/.test(u) ? "firefox" : /Chrome|CriOS/.test(u) ? "chrome" : /Safari/.test(u) ? "safari" : "other"; return os + "/" + br; } export function devKey(request) { const k = request.headers.get("x-pt-k") || ""; return /^[a-f0-9]{32}$/.test(k) ? k : ""; } export const probing = request => request.headers.get("x-pt-probe") === "1"; // a look-only request (the Proof page): never sets a note const b64u = buf => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); const unb64u = s => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), c => c.charCodeAt(0)); // The note is encrypted with the site's secret, so only the site can read it. Whether THIS request may use it is decided // the same way everything else here is decided: by a constellation, not by one hard test. Inside the note are four marks of // the device it belongs to. Each one that matches adds weight; none is required; enough together open it. // 2 the device's own key (kept in its storage, sent by the page) 1 the same kind of device and browser // 1 the same language setting 1 a network this device has used before // Three points open the note. So a phone whose storage was cleared, or whose browser was updated, carries on without // starting over; while a bare copy of the cookie on someone else's device, somewhere else, scores 0 to 2 and opens nothing. const OPEN_AT = 3; async function sealKey(env, name) { const raw = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(need(env) + "|sealed|" + name)); return crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]); } const short = async (env, t) => (await hmac(need(env), "mark|" + t)).slice(0, 12); const langOf = request => ((request.headers.get("accept-language") || "").split(",")[0] || "").trim().toLowerCase().slice(0, 8); const netOf = request => { const ip = request.headers.get("cf-connecting-ip") || ""; return ip.includes(":") ? ip.split(":").slice(0, 4).join(":") : ip.split(".").slice(0, 3).join("."); }; async function marks(env, request, prev) { // the marks to write into the note, carrying forward what this request cannot supply const k = devKey(request), n = await short(env, "net|" + netOf(request)), nets = ((prev && prev.nets) || []).filter(x => x !== n).concat(n).slice(-4); return { kh: k ? await short(env, "key|" + k) : ((prev && prev.kh) || ""), ua: uaFam(request), lg: langOf(request), nets }; } async function weigh(env, request, b) { // how well this request matches the device the note belongs to const k = devKey(request), m = { key: 0, ua: 0, lang: 0, net: 0 }; if (b.kh && k && b.kh === await short(env, "key|" + k)) m.key = 2; if (b.ua && b.ua === uaFam(request)) m.ua = 1; if (b.lg && b.lg === langOf(request)) m.lang = 1; if ((b.nets || []).includes(await short(env, "net|" + netOf(request)))) m.net = 1; m.score = m.key + m.ua + m.lang + m.net; return m; } /** Returns the Set-Cookie line (null on a look-only request). `prev` is the marks from the note being replaced, if any. */ export async function sealCookie(env, request, name, obj, days, prev) { if (probing(request)) return null; const body = Object.assign({}, obj, { _b: await marks(env, request, prev) }); const iv = crypto.getRandomValues(new Uint8Array(12)), ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await sealKey(env, name), new TextEncoder().encode(JSON.stringify(body))); return `${name}=v3.${b64u(iv)}.${b64u(ct)}; Path=/; Max-Age=${(days || 180) * 86400}; Secure; HttpOnly; SameSite=Lax`; } /** {present, value, match}: value is null when there is no note, or when too little about this request matches its device. */ export async function openCookie(env, request, name) { const m = new RegExp("(?:^|;\\s*)" + name + "=([^;]+)").exec(request.headers.get("cookie") || ""); if (!m) return { present: false, value: null }; const p = decodeURIComponent(m[1]).split("."); if (p.length !== 3 || p[0] !== "v3") return { present: true, value: null }; let o; try { o = JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv: unb64u(p[1]) }, await sealKey(env, name), unb64u(p[2])))); } catch (e) { return { present: true, value: null }; } const b = o._b || {}, match = await weigh(env, request, b); delete o._b; if (match.score < OPEN_AT) return { present: true, value: null, match }; // refresh the marks when this is plainly the same device with something changed (new key after cleared storage, new network) const stale = (devKey(request) && !match.key) || !match.net || !match.ua || !match.lang; return { present: true, value: o, match, marks: b, stale }; } export function clientIp(request) { return request.headers.get("cf-connecting-ip") || ""; } function cookies(request) { const out = {}; (request.headers.get("cookie") || "").split(";").forEach(p => { const i = p.indexOf("="); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); }); return out; } // The old long-lived device cookie (pt_onsite) could be copied and used anywhere on the same kind of browser, so it is no // longer read or written. What a device has earned lives only in the sealed note (pt_res). Because an ordinary page load // cannot send the device key, the page first proves itself with a keyed request (see /whereami) and is handed a // "page pass": good for 15 minutes, and only from the same kind of browser on the same network. const NAV = "pt_nav"; export async function mintNav(env, request) { const ts = Date.now(); return `${NAV}=${ts}.${await hmac(need(env), `nav|${ts}|${uaFam(request)}|${netOf(request)}`)}; Path=/; Max-Age=900; Secure; HttpOnly; SameSite=Lax`; } async function validNav(env, request) { const v = cookies(request)[NAV]; if (!v) return false; const [ts, sig] = v.split("."); if (!ts || !sig || Date.now() - Number(ts) > 15 * 60 * 1000) return false; return (await hmac(need(env), `nav|${ts}|${uaFam(request)}|${netOf(request)}`)) === sig; } export const hasNote = request => /(?:^|;\s*)pt_res=/.test(request.headers.get("cookie") || ""); /** Returns {ok, signals:{network,device,code}, ip, setCookie?} */ export async function verify(request, env, codeAttempt) { const ip = clientIp(request); const network = ipList(env).includes(ip); const nav = !network && await validNav(env, request); const code = !!(codeAttempt && env.ONSITE_CODE && codeAttempt.trim().toLowerCase() === String(env.ONSITE_CODE).trim().toLowerCase()); const ok = network || nav || code; return { ok, ip, signals: { network, device: nav, nav, code } }; } // ---- Resident standing (added 2026-11-20) ---- // Saying "I am a resident" grants nothing. A device is treated as a resident's only when the signs the SERVER holds for it, // kept in a signed cookie the visitor cannot edit, add up to enough (see standing() for the weights): // here — at Park Terrace right now: on the building network, OR the phone's own location check says so // code — the on-site code was entered on this device // days — here on 3 different days (by either means) vouched — a confirmed neighbor vouched for this device // carried — restored with the keep phrase from a backup that a confirmed device made (new or replacement phone) // Once two are met the device is confirmed for 180 days (so a resident's phone still counts when it is away). const RES = "pt_res"; const TZ = "America/Phoenix"; const today = () => new Intl.DateTimeFormat("en-CA", { timeZone: TZ, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date()); const enc = o => b64url(new TextEncoder().encode(JSON.stringify(o))); const dec = s => { try { return JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), c => c.charCodeAt(0)))); } catch (e) { return null; } }; const secret = env => need(env); async function readRes(env, request) { const o = await openCookie(env, request, RES); if (o.value && Array.isArray(o.value.d)) return Object.assign(o.value, { _marks: o.marks, _stale: o.stale, _match: o.match }); return { d: [], locked: o.present, _match: o.match }; // locked: a note is there but too little about this request matches it } async function mintRes(env, request, o) { const c = Object.assign({}, o), prev = c._marks; delete c.locked; delete c._marks; delete c._stale; delete c._match; return sealCookie(env, request, RES, c, DAYS, prev); } /** v = result of verify(). patch = {v:1} vouch claimed, {k:1} restored from a confirmed device, {g:true|false} the phone's own * location check. Returns {resident, signals, score, need, setCookie?} * * Signs are weighed, not counted, and none is required. A device is confirmed when its signs add up to NEED points: * 3 a confirmed neighbor vouched for it (strong: a person who lives here says so) * 2 the on-site code was entered on it (medium: the code is posted inside the building) * 3 restored with the owner's keep phrase from a device that was fully confirmed (strong: a new phone needs nothing else) * 1 it is at Park Terrace right now, by Wi-Fi or by its own location check (weak: visitors and staff are here too) * 1 it has used the Hub on three or more different days (every visit is recorded as a day of use, wherever it is) * Reaching NEED makes a device "resident": its owner can use the Hub for themselves. Seeing OTHER people (the Check-In list, * listings) needs "full", which only a person can give: a vouch, a restore from a full device, or being the first neighbor. * Being here is deliberately a single low-value sign: on its own it opens nothing, and its absence costs nothing. * Presence the device only reports about itself (location, never the network) is worth at most 1 point in total. */ const NEED = 3; export async function standing(request, env, v, patch) { if (!opted(request, "s") && !(patch && patch.optin)) { // no yes from this device: read nothing, write nothing, remember nothing const live = v.signals.network ? 1 : 0; return { resident: false, full: false, onsite: !!v.signals.network, optedIn: false, score: live, need: NEED, count: live, setCookie: null, signals: { wifi: !!v.signals.network, located: false, here: !!v.signals.network, code: false, days: 0, hereDays: 0, daysOk: false, vouched: false, carried: false, points: { here: live, days: 0, code: 0, vouched: 0, carried: 0 } } }; } const r = await readRes(env, request); let ch = false; const t = today(); r.d = r.d || []; r.gd = r.gd || []; r.u = r.u || []; // A note that cannot be opened counts for nothing. It is replaced only by a request from the page itself (it carries the device key). const canWrite = !probing(request) && (!r.locked || !!devKey(request)); // an unopenable note is replaced only by the page itself if (r._stale) ch = true; if (!r.u.includes(t)) { r.u = r.u.concat(t).slice(-14); ch = true; } // every visit adds to the picture: a day this device used the Hub if (r.r && Date.now() - r.r > DAYS * 86400 * 1000) { delete r.r; ch = true; } if (v.signals.network && !r.d.includes(t)) { r.d = r.d.concat(t).slice(-10); ch = true; } const located = !!(patch && patch.g === true); if (located && !r.gd.includes(t)) { r.gd = r.gd.concat(t).slice(-10); ch = true; } if (v.signals.code && !r.c) { r.c = 1; ch = true; } // only a code typed in this very request counts; never a cookie that says so if (!r.i) { r.i = b64u(crypto.getRandomValues(new Uint8Array(9))); ch = true; } // a random number for this note; never shown to anyone if (patch && patch.pid !== undefined && r.pid !== patch.pid) { if (patch.pid) r.pid = patch.pid; else delete r.pid; ch = true; } // which Check-In person this device belongs to (set by the server only) if (patch && patch.kp && r.kp !== patch.kp) { r.kp = patch.kp; ch = true; } // whose backup this device was restored from if (patch && patch.v && !r.v) { r.v = 1; ch = true; } if (patch && patch.k && !r.k) { r.k = 1; ch = true; } if (patch && patch.f && !r.f) { r.f = 1; ch = true; } // the first neighbor, who starts the circle of vouching const days = new Set(r.d.concat(r.gd, r.u)).size, hereDays = new Set(r.d.concat(r.gd)).size, here = !!v.signals.network || located; let presence = (here ? 1 : 0) + (days >= 3 ? 1 : 0); if (!v.signals.network && !r.d.length) presence = Math.min(presence, 1); // only the device's own word for it const signals = { wifi: !!v.signals.network, located, here, code: !!r.c, days, hereDays, daysOk: days >= 3, vouched: !!r.v, carried: !!r.k, points: { here: here ? 1 : 0, days: Math.max(0, presence - (here ? 1 : 0)), code: r.c ? 2 : 0, vouched: r.v ? 3 : 0, carried: r.k ? 3 : 0 } }; const score = presence + (r.c ? 2 : 0) + (r.v ? 3 : 0) + (r.k ? 3 : 0); if (!r.r && score >= NEED) { r.r = Date.now(); ch = true; } // Two levels. "resident" (enough signs) opens a person's OWN use of the Hub. "full" opens other people's names, and it // comes only from a person: a confirmed neighbor's vouch, a restore from a device that had it, or being the first neighbor. // The posted code and being in the building can never reveal anyone else, however often they are repeated. const full = !!r.r && !!(r.v || r.k || r.f); const onsite = !!v.signals.network || (!r.locked && (!!r.c || !!r.r)); // may use the on-site pages: here now, or a note this device can open that holds the code or better return { resident: !!r.r, full, onsite, nid: r.locked ? "" : (r.i || ""), pid: r.locked ? "" : (r.pid || ""), kp: r.locked ? "" : (r.kp || ""), optedIn: true, sealed: !!r.locked, match: r._match || null, signals, score, need: NEED, count: score, setCookie: ch && canWrite ? await mintRes(env, request, r) : null }; } // ---- Family links use the same sealed note. export async function readSigned(env, request, name) { return (await openCookie(env, request, name)).value; } export async function mintSigned(env, name, o, days, request) { return request ? sealCookie(env, request, name, o, days, (await openCookie(env, request, name)).marks) : null; } export function gatePage(ip, wrongCode) { return `Park Terrace — residents only
Park Terrace Resident Hub
This part of the site is for people at Park Terrace.

Enter the on-site code once and this device stays verified. On the community Wi-Fi it opens by itself, but you do not need the Wi-Fi.

Entering the code is your yes to a private note on this device. You can undo that at any time on the “What the Hub knows” page.

${wrongCode ? '
That code did not match.
' : ''}

The code is posted at the front desk. Other ways in, including a neighbor who can confirm you.

`; }