From fdd67dc1ce0730fb214aae398fb0c7c67c070738 Mon Sep 17 00:00:00 2001 From: "prompt.ac/@jeffrey" Date: Mon, 12 Oct 2026 17:01:30 -0700 Subject: [PATCH] Let `choir` find your @handle on a sibling account, and keep a live trail An email-code sign-in is its own Auth0 account; with the same verified email choir now posts as the account that holds the handle. Web and server write choir-events (30-day TTL); admins read them at /api/choir?events=1. Co-Authored-By: Claude --- system/backend/authorization.mjs | 21 +++++++++++++ system/backend/choir-events.mjs | 31 +++++++++++++++++++ system/netlify/functions/choir.mjs | 49 ++++++++++++++++++++++++++---- system/public/choir/index.html | 20 ++++++++---- 4 files changed, 109 insertions(+), 12 deletions(-) create mode 100644 system/backend/choir-events.mjs diff --git a/system/backend/authorization.mjs b/system/backend/authorization.mjs index feffdc700e..f590bf981a 100644 --- a/system/backend/authorization.mjs +++ b/system/backend/authorization.mjs @@ -682,3 +682,24 @@ async function getAccessToken(got, tenant = "aesthetic") { return token; } + +// Passwordless email sign-in makes its own `email|…` account, apart from the +// password or social account that already holds a person's @handle. Same +// tenant, same verified email: find the sibling that owns the handle. +// Returns { sub, handle } or null. Both accounts must have a verified email. +export async function handleBySharedEmail(user, database) { + if (!user?.email || !user.email_verified) return null; + const { got } = await import("got"); + const token = await getAccessToken(got); + const siblings = (await got(`${aestheticBaseURI}/api/v2/users-by-email`, { + searchParams: { email: user.email, fields: "user_id,email_verified", include_fields: true }, + headers: { Authorization: `Bearer ${token}` }, responseType: "json", + })).body; + const handles = database.db.collection("@handles"); + for (const s of siblings) { + if (s.user_id === user.sub || !s.email_verified) continue; + const row = await handles.findOne({ _id: s.user_id }); + if (row?.handle) return { sub: s.user_id, handle: row.handle }; + } + return null; +} diff --git a/system/backend/choir-events.mjs b/system/backend/choir-events.mjs new file mode 100644 index 0000000000..e9fb2edad4 --- /dev/null +++ b/system/backend/choir-events.mjs @@ -0,0 +1,31 @@ +// choir events, 26.10.12 +// A live trail of what people do in choir, so a stuck sign-in or a refused +// post shows up while it is happening. Web and app send client events; the +// server adds its own at each door. Kept 30 days. +export const EVENT_COLLECTION = "choir-events"; +const NAME = /^[a-z][a-z0-9:_-]{1,40}$/; + +export function cleanEvent(raw, server = {}) { + if (!raw || !NAME.test(raw.name || "")) return null; + const props = {}; + for (const [k, v] of Object.entries(raw.props || {}).slice(0, 12)) { + if (!/^[a-zA-Z0-9_]{1,24}$/.test(k)) continue; + if (typeof v === "string") props[k] = v.slice(0, 160); + else if (typeof v === "number" || typeof v === "boolean") props[k] = v; + } + const session = typeof raw.session === "string" && /^[a-zA-Z0-9-]{8,64}$/.test(raw.session) ? raw.session : null; + const surface = ["web", "ios", "server"].includes(raw.surface) ? raw.surface : "web"; + return { name: raw.name, props, session, surface, ...server }; +} + +export async function record(db, event) { + if (!event) return; + const c = db.collection(EVENT_COLLECTION); + record.ready ??= c.createIndex({ at: 1 }, { expireAfterSeconds: 30 * 86400 }).catch(() => (record.ready = null)); + await c.insertOne({ ...event, at: new Date() }); +} + +export async function recent(db, { since, limit = 200 } = {}) { + const q = since ? { at: { $gt: new Date(since) } } : {}; + return db.collection(EVENT_COLLECTION).find(q, { projection: { _id: 0 } }).sort({ at: -1 }).limit(Math.min(limit, 500)).toArray(); +} diff --git a/system/netlify/functions/choir.mjs b/system/netlify/functions/choir.mjs index 240dd04524..dd276bb2c4 100644 --- a/system/netlify/functions/choir.mjs +++ b/system/netlify/functions/choir.mjs @@ -8,11 +8,14 @@ // POST /api/choir {text,tags,replyTo} a post or a reply (Bearer) // DELETE /api/choir?id= your own post (Bearer) // PUT /api/choir?prefs=1 {notifications} (Bearer) +// POST /api/choir?event=1 {name,props,session,surface} a trail event +// GET /api/choir?events=1&since= the trail (admin) // // Sign-in is the aesthetic tenant's: the client uses lib/auth0-otp.mjs // (email + six digits) and the token is the one `authorize()` already reads. import { connect } from "../../backend/database.mjs"; -import { authorize } from "../../backend/authorization.mjs"; +import { authorize, handleBySharedEmail, hasAdmin } from "../../backend/authorization.mjs"; +import { cleanEvent, record, recent } from "../../backend/choir-events.mjs"; import { respond } from "../../backend/http.mjs"; import { mongoChoirStore, publicPost } from "../../backend/choir.mjs"; @@ -22,12 +25,24 @@ export const choirStore = () => pending ??= (async () => { return mongoChoirStore(db.collection("choir-posts"), { tags: db.collection("choir-tags"), prefs: db.collection("choir-prefs") }); })().catch((e) => { pending = null; throw e; }); +// The owner is whichever account holds the @handle. An email-code sign-in is +// often a second account beside the one that has it (see handleBySharedEmail). +const linked = new Map(); // sub → { sub, handle } for this process. async function whoami(headers, db) { const user = await authorize(headers); if (!user?.sub) return null; + const at = (h) => (h ? "@" + h.replace(/^@/, "") : null); const row = await db.collection("@handles").findOne({ _id: user.sub }); - return { sub: user.sub, handle: row?.handle ? "@" + row.handle.replace(/^@/, "") : null }; + if (row?.handle) return { sub: user.sub, handle: at(row.handle), user }; + let sibling = linked.get(user.sub); + if (!sibling) { + try { sibling = await handleBySharedEmail(user, { db }); } catch { sibling = null; } + if (sibling) linked.set(user.sub, sibling); + } + return sibling ? { sub: sibling.sub, handle: at(sibling.handle), user, via: user.sub } : { sub: user.sub, handle: null, user }; } +const trail = (db, name, props, headers) => record(db, cleanEvent( + { name, props, surface: "server", session: headers?.["x-choir-session"] }, {})).catch(() => {}); const ok = (v, cache = "no-store") => respond(200, v, { "Cache-Control": cache, "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS" }); const no = (code, error) => respond(code, { error }, { "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS" }); @@ -43,9 +58,16 @@ export async function handler(event) { if (event.httpMethod === "GET") { if (q.me) { const me = await whoami(event.headers || {}, db); - if (!me) return no(401, "Sign in"); + if (!me) { trail(db, "me:anonymous", {}, event.headers); return no(401, "Sign in"); } + trail(db, me.handle ? (me.via ? "me:linked" : "me:handle") : "me:no-handle", + { handle: me.handle || "", conn: me.user.sub.split("|")[0] }, event.headers); return ok({ handle: me.handle, prefs: await store.prefsOf(me.sub) }); } + if (q.events) { + const me = await whoami(event.headers || {}, db); + if (!me || !(await hasAdmin(me.user))) return no(401, "Admins only"); + return ok({ events: await recent(db, { since: q.since, limit: Number(q.limit) || 200 }) }); + } if (q.tags) return ok({ tags: await store.tagList() }, "public, max-age=30"); if (q.thread) { const t = await store.thread(q.thread); @@ -55,15 +77,30 @@ export async function handler(event) { return ok({ posts: rows.map(publicPost), next: rows.length ? rows.at(-1).when : null }, "public, max-age=5"); } + if (event.httpMethod === "POST" && q.event) { + let body; + try { body = JSON.parse(event.body || "{}"); } catch { return no(400, "Send JSON"); } + const e = cleanEvent(body); + if (!e) return no(400, "Bad event"); + await record(db, e); + return ok({ ok: true }); + } + const me = await whoami(event.headers || {}, db); if (!me) return no(401, "Sign in"); if (event.httpMethod === "POST") { let body; try { body = JSON.parse(event.body || "{}"); } catch { return no(400, "Send JSON"); } - if (!me.handle) return no(403, "Choose your @name first"); - const row = await store.post(me.sub, me.handle, body); - return ok({ post: publicPost(row) }); + if (!me.handle) { trail(db, "post:no-handle", {}, event.headers); return no(403, "Choose your @name first"); } + try { + const row = await store.post(me.sub, me.handle, body); + trail(db, body.replyTo ? "post:reply" : "post:root", { handle: me.handle, tags: (row.tags || []).join(",") }, event.headers); + return ok({ post: publicPost(row) }); + } catch (error) { + trail(db, "post:refused", { handle: me.handle, why: error.message }, event.headers); + throw error; + } } if (event.httpMethod === "DELETE") { return (await store.remove(me.sub, q.id || "")) ? ok({ deleted: true }) : no(404, "Not yours, or not there"); diff --git a/system/public/choir/index.html b/system/public/choir/index.html index e272f90a9c..ab4efabe06 100644 --- a/system/public/choir/index.html +++ b/system/public/choir/index.html @@ -127,6 +127,7 @@ +