From 419c5ed082eec45e067837700a5e8135fb1de8a9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 21:02:38 +0100 Subject: [PATCH] Dungeon: the Deru play page, the Idunn recipe and a state contract the test derives - page/: phone-first static page (sign-in with invite and provider buttons, Begin top to bottom with vault picker and Seeding state, timelines, turn view with stream, draft that survives reconnects, refusal and fault lines with Retry and Edit-and-resend), compiled into the binary and served from / under a strict CSP. - deployment/idunn/recipe.toml: one binary, the dungeon crate only; no Eve, mesh, CodexConnector or web steps. The connector key arrives as the binding's secret file GHOSTLIGHT_CONNECTOR_KEY_FILE (a systemd credential Idunn loads); the daemon reads only that path. - idunn_health: generation dungeon-v1, STATE_CONTRACT_SHA256 recomputed (checked against Idunn's canonical_state_contract_sha256 on the same recipe); the recipe drift test is restored and derives the recipe text and digest from one typed slot table whose schemas come from the code that owns them. - /cultnet/snapshot answers 404 to anything carrying a proxy header or a non-loopback peer: nginx forwards from loopback, so the peer address alone admitted the internet. - /api/me names the providers the daemon offers. Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight-dungeon/page/index.html | 25 ++ crates/ghostlight-dungeon/page/page.css | 65 ++++ crates/ghostlight-dungeon/page/page.js | 330 ++++++++++++++++++ crates/ghostlight-dungeon/src/api.rs | 71 +++- crates/ghostlight-dungeon/src/catalog.rs | 2 +- crates/ghostlight-dungeon/src/idunn_health.rs | 147 +++++++- crates/ghostlight-dungeon/src/main.rs | 1 + crates/ghostlight-dungeon/src/page.rs | 44 +++ crates/ghostlight-dungeon/src/runtime.rs | 55 ++- deployment/idunn/recipe.toml | 122 +++++++ 10 files changed, 841 insertions(+), 21 deletions(-) create mode 100644 crates/ghostlight-dungeon/page/index.html create mode 100644 crates/ghostlight-dungeon/page/page.css create mode 100644 crates/ghostlight-dungeon/page/page.js create mode 100644 crates/ghostlight-dungeon/src/page.rs create mode 100644 deployment/idunn/recipe.toml diff --git a/crates/ghostlight-dungeon/page/index.html b/crates/ghostlight-dungeon/page/index.html new file mode 100644 index 0000000..d71103e --- /dev/null +++ b/crates/ghostlight-dungeon/page/index.html @@ -0,0 +1,25 @@ + + + + + + + +Ghostlight Dungeon + + + +
+ +
+ + + + +
+
+

Loading…

+ + + + diff --git a/crates/ghostlight-dungeon/page/page.css b/crates/ghostlight-dungeon/page/page.css new file mode 100644 index 0000000..bd901a3 --- /dev/null +++ b/crates/ghostlight-dungeon/page/page.css @@ -0,0 +1,65 @@ +/* Presentation only. Text size and theme are the two variables below. */ +:root { + --fs: 1.125rem; + --bg: #07111a; --panel: #16212c; --line: #263646; --muted: #8fa1b5; + --text: #eef5ff; --accent: #ff8a2a; --link: #59b7ff; + --bad: #ff6b5e; --badbg: #2a1614; --ok: #6fd08c; --focus: #59b7ff; + --head: Montserrat, "Segoe UI", system-ui, sans-serif; + --body: Georgia, "Iowan Old Style", "Palatino Linotype", serif; +} +:root[data-theme="light"] { + --bg: #f7f4ee; --panel: #ffffff; --line: #d8d2c4; --muted: #5d6a78; + --text: #17202a; --accent: #b4510a; --link: #0b5fa8; + --bad: #a3231a; --badbg: #fdeceb; --ok: #1d7a3c; --focus: #0b5fa8; +} +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { margin: 0; background: var(--bg); color: var(--text); font: var(--fs)/1.65 var(--body); overflow-wrap: anywhere; } +.bar { position: sticky; top: 0; z-index: 5; display: flex; justify-content: space-between; align-items: center; gap: .5rem; + padding: .4rem max(.75rem, env(safe-area-inset-left)); background: var(--bg); border-bottom: 1px solid var(--line); } +.brand { background: none; border: 0; color: var(--accent); font: 600 1.05rem var(--head); letter-spacing: .06em; text-transform: uppercase; min-height: 44px; padding: 0 .25rem; cursor: pointer; } +.tools { display: flex; gap: .25rem; flex-wrap: wrap; justify-content: flex-end; } +.tool { background: none; border: 1px solid var(--line); color: var(--muted); font: 500 .8rem var(--head); border-radius: .5rem; min-height: 44px; min-width: 44px; padding: 0 .6rem; cursor: pointer; } +main { max-width: 44rem; margin: 0 auto; padding: .75rem max(.75rem, env(safe-area-inset-left)) 9rem; } +h1, h2 { font-family: var(--head); font-weight: 300; line-height: 1.2; margin: .5rem 0 .75rem; } +h1 { font-size: 1.6rem; } h2 { font-size: 1.25rem; } +.note, .small { color: var(--muted); font-size: .9rem; line-height: 1.5; } +a { color: var(--link); } +button, input, textarea { font: inherit; color: inherit; } +:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .9rem 1rem; margin: .75rem 0; } +.row { display: flex; gap: .6rem; flex-wrap: wrap; align-items: center; } +.btn { background: var(--accent); color: #07111a; border: 0; border-radius: .6rem; min-height: 48px; padding: 0 1.1rem; font: 600 1rem var(--head); cursor: pointer; } +.btn.alt { background: none; color: var(--text); border: 1px solid var(--line); } +.btn[disabled] { opacity: .5; cursor: default; } +.btn.wide { width: 100%; } +label { display: block; font: 600 .85rem var(--head); letter-spacing: .04em; margin: 1rem 0 .3rem; color: var(--muted); text-transform: uppercase; } +input[type=text], textarea { width: 100%; background: var(--bg); border: 1px solid var(--line); border-radius: .6rem; padding: .7rem .8rem; min-height: 48px; } +textarea { resize: vertical; line-height: 1.5; } +.choice { display: flex; gap: .7rem; align-items: center; min-height: 48px; padding: .4rem .6rem; border: 1px solid var(--line); border-radius: .6rem; margin: .4rem 0; cursor: pointer; background: var(--bg); } +.choice input { width: 1.4rem; height: 1.4rem; accent-color: var(--accent); flex: none; } +.chip { font: 600 .72rem var(--head); text-transform: uppercase; letter-spacing: .06em; padding: .15rem .5rem; border-radius: 1rem; border: 1px solid var(--line); color: var(--muted); } +.chip.ready { color: var(--ok); border-color: var(--ok); } .chip.seeding { color: var(--accent); border-color: var(--accent); } .chip.failed { color: var(--bad); border-color: var(--bad); } +.tl { display: block; width: 100%; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .8rem 1rem; margin: .5rem 0; min-height: 56px; cursor: pointer; } +.tl.current { border-color: var(--accent); } +.tl .t { font: 600 1.05rem var(--head); display: block; } +.line { border-left: 4px solid var(--bad); background: var(--badbg); border-radius: .4rem; padding: .6rem .8rem; margin: .75rem 0; } +.line.info { border-color: var(--accent); background: var(--panel); } +.turn { margin: 1.4rem 0; } +.you { color: var(--muted); font-style: italic; border-left: 3px solid var(--line); padding-left: .8rem; margin: 0 0 .7rem; white-space: pre-wrap; } +.story { white-space: pre-wrap; margin: 0; } +.ask { border: 1px solid var(--accent); border-radius: .6rem; padding: .6rem .8rem; margin: .8rem 0; } +.status { color: var(--muted); font: 500 .85rem var(--head); } +.pulse::after { content: ""; display: inline-block; width: .5rem; height: .5rem; margin-left: .5rem; border-radius: 50%; background: var(--accent); animation: p 1.2s ease-in-out infinite; } +@keyframes p { 50% { opacity: .2; } } +@media (prefers-reduced-motion: reduce) { .pulse::after { animation: none; } } +.bar2 { height: .4rem; background: var(--line); border-radius: .3rem; overflow: hidden; margin: .6rem 0; } +.bar2 i { display: block; height: 100%; width: 40%; background: var(--accent); animation: s 1.6s ease-in-out infinite alternate; } +@keyframes s { to { margin-left: 60%; } } +@media (prefers-reduced-motion: reduce) { .bar2 i { animation: none; width: 100%; } } +.compose { position: fixed; left: 0; right: 0; bottom: 0; background: var(--bg); border-top: 1px solid var(--line); padding: .5rem max(.75rem, env(safe-area-inset-left)) max(.5rem, env(safe-area-inset-bottom)); } +.compose .in { max-width: 44rem; margin: 0 auto; } +.compose textarea { min-height: 3.2rem; max-height: 40vh; } +.compose .row { margin-top: .4rem; } +.compose .btn { flex: 1 1 8rem; } +@media (min-width: 700px) { :root { --fs: 1.2rem; } main { padding-top: 1.25rem; } } diff --git a/crates/ghostlight-dungeon/page/page.js b/crates/ghostlight-dungeon/page/page.js new file mode 100644 index 0000000..3dfae55 --- /dev/null +++ b/crates/ghostlight-dungeon/page/page.js @@ -0,0 +1,330 @@ +// Presentation only. The daemon owns every command and every fact; this page +// shows what the API returns and sends what the player types. The only state it +// keeps on the device is the unsent draft, the text size and the theme. The +// turns on screen are a display cache of what the stream delivered in this +// visit; a reload shows the open turn again from the server. +"use strict"; + +const $view = document.getElementById("view"); +const LS = { + get(k) { try { return localStorage.getItem(k); } catch { return null; } }, + set(k, v) { try { if (v === null || v === "") localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* storage may be blocked */ } }, +}; +const uuid = () => (crypto.randomUUID ? crypto.randomUUID() + : "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16))); + +function el(tag, attrs, ...kids) { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (k === "class") node.className = v; + else if (k.startsWith("on")) node.addEventListener(k.slice(2), v); + else if (v === true) node.setAttribute(k, ""); + else if (v !== false && v != null) node.setAttribute(k, v); + } + for (const kid of kids.flat()) if (kid != null) node.append(kid); + return node; +} + +async function api(path, options) { + let response; + try { + response = await fetch("api/" + path, { credentials: "same-origin", ...options, + headers: options && options.body ? { "content-type": "application/json" } : undefined }); + } catch { + return { status: 0, body: { error: "The server could not be reached." } }; + } + let body = null; + try { body = await response.json(); } catch { body = null; } + return { status: response.status, body: body || {} }; +} +const post = (path, body) => api(path, { method: "POST", body: JSON.stringify(body) }); + +// ---- text size and theme ------------------------------------------------- +const root = document.documentElement; +function applySize(rem) { root.style.setProperty("--fs", rem + "rem"); LS.set("fs", String(rem)); } +const savedSize = parseFloat(LS.get("fs")); +if (savedSize >= 0.9 && savedSize <= 1.9) root.style.setProperty("--fs", savedSize + "rem"); +function currentSize() { return parseFloat(getComputedStyle(root).getPropertyValue("--fs")) || 1.125; } +document.getElementById("smaller").onclick = () => applySize(Math.max(0.9, +(currentSize() - 0.1).toFixed(2))); +document.getElementById("larger").onclick = () => applySize(Math.min(1.9, +(currentSize() + 0.1).toFixed(2))); +function applyTheme(name) { + if (name === "light" || name === "dark") root.dataset.theme = name; else delete root.dataset.theme; +} +applyTheme(LS.get("theme")); +document.getElementById("theme").onclick = () => { + const next = root.dataset.theme === "light" ? "dark" : "light"; + applyTheme(next); LS.set("theme", next); +}; + +// ---- state --------------------------------------------------------------- +const S = { me: null, timeline: null, log: [], nextYou: null, lastText: "", keyed: null, stream: null, poll: null, signIn: null }; + +function stopLive() { + if (S.stream) { S.stream.close(); S.stream = null; } + if (S.poll) { clearTimeout(S.poll); S.poll = null; } +} +function show(...nodes) { $view.replaceChildren(...nodes.flat()); window.scrollTo(0, 0); } +function inviteFromHash() { + const m = /(?:^#|&)invite=([A-Za-z0-9_\-]{8,200})/.exec(location.hash); + return m ? m[1] : ""; +} + +async function boot() { + stopLive(); + const { status, body } = await api("me"); + if (status !== 200) return show(el("h1", {}, "Ghostlight"), errorLine(body.error || "The server answered with an error (" + status + ")."), retryButton(boot)); + S.me = body; + document.getElementById("signout").hidden = !body.signedIn; + if (!body.signedIn) return signInView(); + if (body.currentTimeline) return openTimeline(body.currentTimeline); + return listView(); +} +function errorLine(text) { return el("p", { class: "line", role: "alert" }, text); } +function retryButton(fn) { return el("button", { class: "btn", type: "button", onclick: fn }, "Try again"); } + +// ---- sign in ------------------------------------------------------------- +function signInView(message) { + stopLive(); + const providers = (S.me && S.me.providers) || []; + const invite = el("input", { type: "text", id: "invite", autocomplete: "off", autocapitalize: "off", spellcheck: "false", value: inviteFromHash() }); + const out = el("div", {}); + if (message) out.append(errorLine(message)); + const buttons = providers.map((name) => el("button", { class: "btn wide", type: "button", style: "margin:.4rem 0", onclick: () => beginSignIn(name, invite.value.trim(), out) }, + "Sign in with " + name[0].toUpperCase() + name.slice(1))); + show(el("h1", {}, "Sign in"), + el("p", { class: "note" }, "Only people on the allowlist can play. A first sign-in needs the invite you were given; after that, signing in is enough."), + el("div", { class: "card" }, + el("label", { for: "invite" }, "Invite (first time only)"), invite, + el("p", { class: "small" }, "A link that ends in #invite=… fills this in."), + providers.length ? buttons : el("p", { class: "line" }, "This server offers no sign-in provider.")), + out); + if (S.signIn && S.signIn.until > Date.now()) resumeSignIn(out, invite); +} + +async function beginSignIn(provider, invite, out) { + out.replaceChildren(el("p", { class: "note pulse" }, "Asking " + provider + " for a sign-in")); + const { status, body } = await post("auth/begin", { key: uuid(), provider }); + if (status !== 200) return out.replaceChildren(errorLine(body.error || "Sign-in could not begin (" + status + ").")); + let target = null; + try { + const url = new URL(body.url, location.href); + if ((body.allowedOrigins || []).includes(url.origin) && url.protocol === "https:") target = url.href; + } catch { target = null; } + if (!target) return out.replaceChildren(errorLine("The sign-in address was not one this page will open.")); + S.signIn = { handle: body.handle, invite, target, until: Date.now() + 9 * 60 * 1000 }; + window.open(target, "_blank", "noopener"); + resumeSignIn(out); +} + +async function resumeSignIn(out) { + const attempt = S.signIn; + out.replaceChildren( + el("p", { class: "note pulse" }, "Waiting for you to finish signing in on the other tab."), + el("p", {}, el("a", { href: attempt.target, target: "_blank", rel: "noopener noreferrer" }, "Open the sign-in page again"))); + while (S.signIn === attempt && Date.now() < attempt.until) { + await new Promise((r) => setTimeout(r, 2500)); + if (S.signIn !== attempt) return; + const { status, body } = await post("auth/complete", { handle: attempt.handle, key: uuid(), invite: attempt.invite || null }); + if (status === 202) continue; + S.signIn = null; + if (status === 200 && body.status === "authenticated") { history.replaceState(null, "", location.pathname); return boot(); } + if (status === 429) return out.replaceChildren(errorLine(body.error || "Too many attempts; wait a minute.")); + return out.replaceChildren(errorLine(body.error || "Sign-in was refused (" + status + ").")); + } + if (S.signIn === attempt) { S.signIn = null; out.replaceChildren(errorLine("The sign-in expired. Start again.")); } +} + +document.getElementById("signout").onclick = async () => { + stopLive(); + const { status, body } = await post("auth/logout", {}); + if (status !== 200) return show(errorLine(body.error || "Sign-out was not confirmed."), retryButton(boot)); + S.log = []; S.timeline = null; + boot(); +}; +document.getElementById("home").onclick = () => { if (S.me && S.me.signedIn) listView(); }; + +// ---- timelines ----------------------------------------------------------- +async function listView() { + stopLive(); + S.timeline = null; + const { status, body } = await api("timelines"); + if (status === 401) return boot(); + if (status !== 200) return show(el("h1", {}, "Your worlds"), errorLine(body.error || "Could not list your worlds."), retryButton(listView)); + const rows = body.timelines || []; + const seeding = rows.some((r) => r.status === "seeding"); + show(el("h1", {}, "Your worlds"), + el("button", { class: "btn wide", type: "button", onclick: beginView }, "Begin a new world"), + rows.length ? rows.map(timelineRow) : el("p", { class: "note" }, "No worlds yet."), + el("p", { class: "small" }, "Each fork of a world is its own timeline. Older timelines stay.")); + if (seeding) S.poll = setTimeout(listView, 4000); +} +function timelineRow(row) { + const when = row.createdAt ? new Date(row.createdAt).toLocaleString() : ""; + return el("button", { class: "tl" + (row.current ? " current" : ""), type: "button", onclick: () => openTimeline(row.timeline) }, + el("span", { class: "t" }, row.title || "Untitled"), + el("span", { class: "chip " + row.status }, row.status), " ", + row.parent ? el("span", { class: "small" }, "fork") : "", + el("span", { class: "small", style: "display:block" }, (row.current ? "Current. " : "") + when), + row.status === "failed" ? el("span", { class: "small", style: "display:block;color:var(--bad)" }, row.reason || "Seeding failed.") : ""); +} + +// ---- begin --------------------------------------------------------------- +let beginKey = null; +async function beginView() { + stopLive(); + beginKey = beginKey || uuid(); + const { status, body } = await api("vaults"); + if (status === 401) return boot(); + const vaults = status === 200 ? body.vaults || [] : []; + const msg = el("div", {}); + if (status !== 200) msg.append(errorLine(body.error || "The lore list could not be read.")); + let vault = vaults.length ? vaults[0] : ""; + const choices = vaults.map((name, i) => el("label", { class: "choice", style: "text-transform:none;letter-spacing:0;font:inherit;color:var(--text);margin:.4rem 0" }, + el("input", { type: "radio", name: "vault", value: name, checked: i === 0, onchange: () => { vault = name; } }), name)); + const title = el("input", { type: "text", id: "title", autocomplete: "off", value: LS.get("begin-title") || "" }); + const name = el("input", { type: "text", id: "name", autocomplete: "off", value: LS.get("begin-name") || "" }); + const brief = el("textarea", { id: "brief", rows: "3" }); + const go = el("button", { class: "btn wide", type: "button", style: "margin-top:1.2rem" }, "Begin"); + go.onclick = async () => { + if (!title.value.trim() || !name.value.trim()) return msg.replaceChildren(errorLine("A world needs a title and your name in it.")); + go.disabled = true; msg.replaceChildren(el("p", { class: "note pulse" }, "Starting the world")); + const { status: s, body: b } = await post("begin", { key: beginKey, title: title.value.trim(), name: name.value.trim(), brief: brief.value.trim() || null, vault: vault || null }); + go.disabled = false; + if (s === 200) { beginKey = null; LS.set("begin-title", title.value.trim()); LS.set("begin-name", name.value.trim()); return openTimeline(b.timeline); } + const unknown = b.outcome === "unknown" || s === 0; + msg.replaceChildren(errorLine((b.error || "The world could not begin (" + s + ").") + (b.step ? " (step: " + b.step + ")" : "") + + (unknown ? " The outcome is unknown: check Your worlds before beginning again. Pressing Begin again is safe; it carries the same request key." : ""))); + }; + show(el("h1", {}, "Begin a world"), + el("label", {}, "1. Lore"), + vaults.length ? choices : el("p", { class: "line info" }, "No vault has been imported on this server, so a world would start with no lore. Ask the host to import one."), + el("label", { for: "title" }, "2. Name the world"), title, + el("label", { for: "name" }, "3. What you are called in it"), name, + el("label", { for: "brief" }, "4. Anything the storyteller should know (optional)"), brief, + go, msg, + el("p", { class: "small" }, "A world seeded from lore takes a few minutes. You can leave this page; it carries on.")); +} + +// ---- play ---------------------------------------------------------------- +async function openTimeline(id) { + stopLive(); + S.timeline = id; S.log = []; S.nextYou = null; S.lastText = ""; S.keyed = null; + const { status, body } = await api("timelines"); + if (status !== 200) return show(errorLine(body.error || "Could not open that world."), retryButton(() => openTimeline(id))); + const row = (body.timelines || []).find((r) => r.timeline === id); + if (!row) return listView(); + if (row.status === "seeding") { + show(el("h1", {}, row.title), el("p", { class: "status pulse" }, "Seeding the world from the lore"), + el("div", { class: "bar2" }, el("i", {})), + el("p", { class: "note" }, "Elaborators are writing the people and places. You can leave and come back; this updates by itself.")); + S.poll = setTimeout(() => openTimeline(id), 4000); + return; + } + if (row.status === "failed") { + return show(el("h1", {}, row.title), errorLine("Seeding failed: " + (row.reason || "no reason was recorded.")), + el("button", { class: "btn", type: "button", onclick: beginView }, "Begin another world")); + } + playView(row); +} + +let $log, $status, $text, $send, $retryRow, $fresh; +function playView(row) { + $log = el("div", { id: "log" }); + $status = el("p", { class: "status", role: "status" }); + $retryRow = el("div", { class: "row" }); + show(el("h1", {}, row.title), el("p", { class: "small" }, "Earlier turns stay on screen while this page is open; after a reload the open turn is shown again."), $log, $status, $retryRow); + document.querySelector(".compose")?.remove(); + $text = el("textarea", { id: "say", rows: "2", "aria-label": "What do you do?", placeholder: "What do you do?" }); + $text.value = LS.get("draft:" + S.timeline) || ""; + $text.addEventListener("input", () => LS.set("draft:" + S.timeline, $text.value)); + $send = el("button", { class: "btn", type: "button", onclick: () => send($text.value) }, "Send"); + document.body.append(el("div", { class: "compose" }, el("div", { class: "in" }, $text, el("div", { class: "row" }, $send, + el("button", { class: "btn alt", type: "button", onclick: () => send("") }, "Continue")) + , el("p", { class: "small", id: "sendnote", style: "margin:.3rem 0 0" }, "Leave the box empty and press Send or Continue to carry on an unfinished turn.")))); + connect(); +} +const leavePlay = () => document.querySelector(".compose")?.remove(); +for (const id of ["home", "signout"]) document.getElementById(id).addEventListener("click", leavePlay); + +function connect() { + const id = S.timeline; + if (S.stream) S.stream.close(); + const stream = new EventSource("api/turn/" + encodeURIComponent(id) + "/stream"); + S.stream = stream; + stream.addEventListener("turn", (event) => { if (S.timeline === id) { try { onTurn(JSON.parse(event.data)); } catch { /* ignore a torn event */ } } }); + stream.onerror = () => { if (S.timeline === id && $status) $status.textContent = "Reconnecting…"; }; +} +document.addEventListener("visibilitychange", async () => { + if (document.hidden || !S.timeline || !$log) return; + const { status, body } = await api("turn/" + encodeURIComponent(S.timeline)); + if (status === 200 && body.timeline === S.timeline) onTurn(body); + if (S.stream && S.stream.readyState === 2) connect(); +}); + +function onTurn(view) { + const turn = view.turn; + if (!turn) { + $log.replaceChildren(el("p", { class: "note" }, "The world is ready. Say what you do.")); + $status.className = "status"; $status.textContent = ""; $retryRow.replaceChildren(); + return; + } + let entry = S.log.find((e) => e.id === turn.id); + if (!entry) { entry = { id: turn.id, you: S.nextYou }; S.nextYou = null; S.log.push(entry); } + Object.assign(entry, { state: turn.state, narration: turn.narration, question: turn.question, refusal: turn.refusal, fault: turn.fault }); + renderLog(); + const last = S.log[S.log.length - 1]; + $retryRow.replaceChildren(); + $status.className = "status"; + if (turn.state === "running") { + if (turn.resolving) { $status.className = "status pulse"; $status.textContent = "The storyteller is resolving your turn"; } + else $status.textContent = turn.continue_hint || "This turn is unfinished."; + } else if (turn.state === "awaiting_player") { + $status.textContent = "The storyteller is waiting for your answer."; + } else { $status.textContent = ""; } + if (turn.fault) { + $retryRow.append( + el("button", { class: "btn", type: "button", onclick: () => send(S.lastText, null, true), disabled: !S.lastText }, "Retry"), + el("button", { class: "btn alt", type: "button", onclick: editAgain, disabled: !S.lastText }, "Edit and resend")); + if (!S.lastText) $retryRow.append(el("p", { class: "small" }, "This page does not hold what you sent before the reload. Write your turn again.")); + } else if (turn.refusal) { + $retryRow.append(el("button", { class: "btn alt", type: "button", onclick: editAgain, disabled: !S.lastText }, "Edit and resend")); + } + last.node?.scrollIntoView?.({ block: "end", behavior: "smooth" }); +} + +function renderLog() { + $log.replaceChildren(...S.log.map((entry) => { + const parts = []; + if (entry.you) parts.push(el("p", { class: "you" }, entry.you)); + if (entry.narration) parts.push(el("p", { class: "story" }, entry.narration)); + if (entry.refusal) parts.push(el("p", { class: "line", role: "alert" }, entry.refusal)); + if (entry.fault) parts.push(el("p", { class: "line", role: "alert" }, entry.fault)); + if (entry.question) parts.push(el("div", { class: "ask" }, el("strong", {}, "The storyteller asks"), el("p", { class: "story" }, entry.question.text))); + const node = el("section", { class: "turn" }, parts); + entry.node = node; + return node; + })); +} + +function editAgain() { $text.value = S.lastText; LS.set("draft:" + S.timeline, $text.value); $text.focus(); } + +async function send(text, _unused, isRetry) { + if (!S.timeline) return; + const last = S.log[S.log.length - 1]; + const answers = last && last.state === "awaiting_player" && last.question ? last.question.token : null; + // The same text resent after a lost reply reuses its key, so it cannot play twice. + if (!S.keyed || S.keyed.text !== text || isRetry) S.keyed = { text, key: uuid() }; + $send.disabled = true; + const { status, body } = await post("play", { timeline: S.timeline, key: S.keyed.key, text, answers }); + $send.disabled = false; + if (status === 202 || status === 200) { + S.lastText = text || S.lastText; S.nextYou = text || null; S.keyed = null; + $text.value = ""; LS.set("draft:" + S.timeline, ""); + $status.className = "status pulse"; $status.textContent = "Sent"; + return; + } + $status.className = "status"; + $retryRow.replaceChildren(errorLine(status === 0 ? "The server could not be reached. Your text is kept; Send resends it safely." : (body.error || "The turn was refused (" + status + ")."))); +} + +boot(); diff --git a/crates/ghostlight-dungeon/src/api.rs b/crates/ghostlight-dungeon/src/api.rs index 96786e2..a0449ce 100644 --- a/crates/ghostlight-dungeon/src/api.rs +++ b/crates/ghostlight-dungeon/src/api.rs @@ -152,9 +152,18 @@ async fn authenticated_principal( } } +/// The sign-in providers this daemon offers, for the page's buttons. +fn offered_providers(state: &AppState) -> Vec<&'static str> { + ["discord", "google", "twitch"] + .into_iter() + .filter(|name| state.heimdall.offered(name).is_some()) + .collect() +} + async fn me(headers: HeaderMap, State(state): State) -> Response { + let providers = offered_providers(&state); let Some(principal) = authenticated_principal(&headers, &state).await else { - return reply(StatusCode::OK, json!({"signedIn": false})); + return reply(StatusCode::OK, json!({"signedIn": false, "providers": providers})); }; let catalog = state.catalog.lock().await; let player = catalog.player(principal.account_subject_hash()); @@ -162,6 +171,7 @@ async fn me(headers: HeaderMap, State(state): State) -> Response { StatusCode::OK, json!({ "signedIn": true, + "providers": providers, "currentTimeline": player.and_then(|player| player.timeline.as_deref()), "destination": player.and_then(|player| player.destination.as_deref()), }), @@ -1568,6 +1578,63 @@ mod tests { } } + async fn raw(app: &App, method: Method, uri: &str, peer: &str, proxy_header: Option<(&str, &str)>) -> (StatusCode, HeaderMap, String) { + let mut request = Request::builder().method(method).uri(uri); + if let Some((name, value)) = proxy_header { + request = request.header(name, value); + } + let mut request = request.body(Body::empty()).unwrap(); + request + .extensions_mut() + .insert(axum::extract::ConnectInfo(peer.parse::().unwrap())); + let response = app.router.clone().oneshot(request).await.unwrap(); + let (status, headers) = (response.status(), response.headers().clone()); + let bytes = to_bytes(response.into_body(), 1 << 20).await.unwrap(); + (status, headers, String::from_utf8_lossy(&bytes).into_owned()) + } + + /// `/cultnet/snapshot` is Idunn's route observation: it answers a direct + /// loopback caller and finds no route for anything that came through the + /// reverse proxy, which reaches the daemon from loopback too. + #[tokio::test] + async fn the_route_observation_is_not_reachable_through_the_proxy() { + let app = app(vec![], &[]).await; + for header in ["x-real-ip", "x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", "forwarded"] { + let (status, _, _) = + raw(&app, Method::POST, "/cultnet/snapshot", "127.0.0.1:1", Some((header, "203.0.113.9"))).await; + assert_eq!(status, StatusCode::NOT_FOUND, "{header} from the proxy on loopback"); + } + let (status, _, _) = raw(&app, Method::POST, "/cultnet/snapshot", "203.0.113.9:1", None).await; + assert_eq!(status, StatusCode::NOT_FOUND, "a non-loopback peer"); + let (status, _, _) = raw(&app, Method::POST, "/cultnet/snapshot", "127.0.0.1:1", None).await; + assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE, "a direct loopback caller reaches the handler"); + } + + /// The page is three embedded files with a script-free policy. Its script + /// renders server text only as text, and no file names the connector key. + #[tokio::test] + async fn the_page_is_served_unauthenticated_under_a_strict_policy() { + let app = app(vec![], &[]).await; + for (uri, kind) in [("/", "text/html"), ("/page.css", "text/css"), ("/page.js", "text/javascript")] { + let (status, headers, body) = raw(&app, Method::GET, uri, "203.0.113.9:1", Some(("x-real-ip", "203.0.113.9"))).await; + assert_eq!(status, StatusCode::OK, "{uri}"); + assert!(headers[header::CONTENT_TYPE].to_str().unwrap().starts_with(kind), "{uri}"); + let policy = headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap(); + assert!(policy.contains("script-src 'self'") && !policy.contains("unsafe-"), "{policy}"); + assert!(!body.contains("connection-ghostlight") && !body.contains("CREDENTIALS_DIRECTORY"), "{uri}"); + if uri == "/" { + assert!(!body.contains("