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 <noreply@anthropic.com>
This commit is contained in:
parent
92fcb70aa6
commit
419c5ed082
10 changed files with 841 additions and 21 deletions
25
crates/ghostlight-dungeon/page/index.html
Normal file
25
crates/ghostlight-dungeon/page/index.html
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>Ghostlight Dungeon</title>
|
||||
<link rel="stylesheet" href="page.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="bar">
|
||||
<button id="home" class="brand" type="button" aria-label="Your worlds">Ghostlight</button>
|
||||
<div class="tools">
|
||||
<button id="smaller" class="tool" type="button" aria-label="Smaller text">A−</button>
|
||||
<button id="larger" class="tool" type="button" aria-label="Larger text">A+</button>
|
||||
<button id="theme" class="tool" type="button" aria-label="Change theme">Theme</button>
|
||||
<button id="signout" class="tool" type="button" hidden>Sign out</button>
|
||||
</div>
|
||||
</header>
|
||||
<main id="view" aria-live="polite"><p class="note">Loading…</p></main>
|
||||
<noscript><p class="note">This page needs JavaScript to play.</p></noscript>
|
||||
<script src="page.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
65
crates/ghostlight-dungeon/page/page.css
Normal file
65
crates/ghostlight-dungeon/page/page.css
Normal file
|
|
@ -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; } }
|
||||
330
crates/ghostlight-dungeon/page/page.js
Normal file
330
crates/ghostlight-dungeon/page/page.js
Normal file
|
|
@ -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();
|
||||
|
|
@ -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<AppState>) -> 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<AppState>) -> 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::<std::net::SocketAddr>().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("<script>") && !body.contains(" onclick="), "no inline script in the page");
|
||||
}
|
||||
if uri == "/page.js" {
|
||||
for sink in ["innerHTML", "outerHTML", "insertAdjacentHTML", "document.write", "eval(", "new Function"] {
|
||||
assert!(!body.contains(sink), "the script must not use {sink}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let (status, _, _) = raw(&app, Method::GET, "/page.js", "203.0.113.9:1", None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answer_token_admits_only_two_present_and_equal_tokens() {
|
||||
assert!(answer_token_admits(Some("a"), Some("a")));
|
||||
|
|
@ -1612,7 +1679,7 @@ mod tests {
|
|||
let path = entry.unwrap().path();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let production = text.split("\n#[cfg(test)]").next().unwrap();
|
||||
if production.contains("connector-key") {
|
||||
if production.contains("GHOSTLIGHT_CONNECTOR_KEY_FILE") {
|
||||
files.push(path.file_name().unwrap().to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize};
|
|||
use std::{collections::BTreeMap, path::Path};
|
||||
use uuid::Uuid;
|
||||
|
||||
const STORE_TYPE: &str = "ghostlight.dungeon_catalog.v1";
|
||||
pub(crate) const STORE_TYPE: &str = "ghostlight.dungeon_catalog.v1";
|
||||
const STORE_KEY: &str = "primary";
|
||||
|
||||
/// A world and who may play it. `snapshot_id` is the vault snapshot the world
|
||||
|
|
|
|||
|
|
@ -44,9 +44,9 @@ pub const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT: &str = "GAMECULT_IDUNN_CANDI
|
|||
pub const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT: &str = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE";
|
||||
|
||||
pub(crate) const TARGET: &str = "ghostlight";
|
||||
const STATE_SCHEMA_GENERATION: &str = "world-v3";
|
||||
const STATE_SCHEMA_GENERATION: &str = "dungeon-v1";
|
||||
const STATE_CONTRACT_SHA256: &str =
|
||||
"sha256-4ac3d4ceabedc48b4fc5a3c143ece00ac495d8d756bdc24f10034bcc1231970f";
|
||||
"sha256-f7a7e4206608cb4c47a867b02146f8657201ab10eab3937d1bb8c37fe6d605ef";
|
||||
const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0";
|
||||
const ODIN_CULTMESH_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002;
|
||||
const RUNTIME_PRESENCE_IDENTITY_FD_NAME: &str = "gamecult-runtime-presence-identity";
|
||||
|
|
@ -161,7 +161,7 @@ impl RuntimePresencePublisher {
|
|||
expected.state_schema_generation.as_deref() == Some(STATE_SCHEMA_GENERATION)
|
||||
&& expected.state_contract_sha256.as_deref() == Some(STATE_CONTRACT_SHA256)
|
||||
&& expected.write_lease_required,
|
||||
"Expected does not name Ghostlight's writable world-v3 state"
|
||||
"Expected does not name the Dungeon's writable dungeon-v1 state"
|
||||
);
|
||||
ensure!(
|
||||
activation.expected_projection_sha256 == expected.canonical_sha256()?
|
||||
|
|
@ -1411,7 +1411,7 @@ pub(crate) mod tests {
|
|||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("does not name Ghostlight's writable world-v3 state")
|
||||
.contains("does not name the Dungeon's writable dungeon-v1 state")
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -1829,3 +1829,142 @@ pub(crate) mod tests {
|
|||
assert!(!is_root_read_only_file(0, 4_000, 0o446));
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipe and the binary agree on the state Idunn fences. The recipe's
|
||||
/// `[state]` block is Idunn's input; `STATE_CONTRACT_SHA256` is the digest the
|
||||
/// daemon admits it by. Both are derived here from one typed table, so a slot
|
||||
/// edited in either place, or a schema constant bumped in code, fails a test
|
||||
/// instead of failing a deploy.
|
||||
#[cfg(test)]
|
||||
mod recipe_drift {
|
||||
use super::*;
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const RECIPE_TOML: &str = include_str!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../deployment/idunn/recipe.toml"
|
||||
));
|
||||
|
||||
// Mirrors Idunn's `StateDeclaration` wire shape: field order and the
|
||||
// kebab-case unit variants decide the bytes it hashes.
|
||||
#[derive(Serialize)]
|
||||
struct Declaration {
|
||||
schema_generation: &'static str,
|
||||
slots: Vec<Slot>,
|
||||
migration: Option<()>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Slot {
|
||||
id: &'static str,
|
||||
relative_path: &'static str,
|
||||
kind: &'static str,
|
||||
schema: &'static str,
|
||||
writer: &'static str,
|
||||
recovery: &'static str,
|
||||
startup: &'static str,
|
||||
}
|
||||
|
||||
fn slot(id: &'static str, path: &'static str, kind: &'static str, schema: &'static str, recovery: &'static str) -> Slot {
|
||||
Slot {
|
||||
id,
|
||||
relative_path: path,
|
||||
kind,
|
||||
schema,
|
||||
writer: "process-bound-single-writer",
|
||||
recovery,
|
||||
startup: "create-or-open-after-write-lease",
|
||||
}
|
||||
}
|
||||
|
||||
/// The slots the daemon opens, each schema read from the code that owns it.
|
||||
fn declaration() -> Declaration {
|
||||
Declaration {
|
||||
schema_generation: STATE_SCHEMA_GENERATION,
|
||||
slots: vec![
|
||||
slot("catalog", "catalog.cc", "cultcache-file", crate::catalog::STORE_TYPE, "preserve"),
|
||||
slot("app-sessions", "service/app-sessions-v2.cc", "cultcache-file", crate::app_session::STORE_SCHEMA, "preserve"),
|
||||
slot("snapshots", crate::vaults::SNAPSHOT_DIRECTORY, "external-file", ghostlight::VAULT_SNAPSHOT_SCHEMA, "rebuildable"),
|
||||
slot("timelines", "timelines", "external-file", STATE_SCHEMA, "preserve"),
|
||||
],
|
||||
migration: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn state_text(declaration: &Declaration) -> String {
|
||||
let mut text = format!("[state]\nschema_generation = \"{}\"\n\n", declaration.schema_generation);
|
||||
for slot in &declaration.slots {
|
||||
text += &format!(
|
||||
"[[state.slots]]\nid = \"{}\"\nrelative_path = \"{}\"\nkind = \"{}\"\nschema = \"{}\"\nwriter = \"{}\"\nrecovery = \"{}\"\nstartup = \"{}\"\n\n",
|
||||
slot.id, slot.relative_path, slot.kind, slot.schema, slot.writer, slot.recovery, slot.startup
|
||||
);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn contract_sha256(declaration: &Declaration) -> String {
|
||||
let bytes = rmp_serde::to_vec(declaration).expect("the declaration encodes");
|
||||
let digest = Sha256::digest(bytes);
|
||||
format!("sha256-{}", digest.iter().map(|byte| format!("{byte:02x}")).collect::<String>())
|
||||
}
|
||||
|
||||
/// The recipe's `[state]` through its last slot, line endings folded.
|
||||
fn recipe_state(recipe: &str) -> String {
|
||||
let start = recipe.find("[state]").expect("recipe has a [state] block");
|
||||
let end = recipe.find("[[provides]]").expect("[state] is followed by [[provides]]");
|
||||
recipe[start..end].replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_recipe_state_is_the_contract_the_daemon_admits() {
|
||||
let declaration = declaration();
|
||||
assert_eq!(
|
||||
recipe_state(RECIPE_TOML),
|
||||
state_text(&declaration),
|
||||
"recipe [state] differs from the slots the daemon opens"
|
||||
);
|
||||
assert_eq!(
|
||||
STATE_CONTRACT_SHA256,
|
||||
contract_sha256(&declaration),
|
||||
"STATE_CONTRACT_SHA256 is not the digest of the slots the recipe declares"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edited_slot_or_schema_is_caught() {
|
||||
let declaration = declaration();
|
||||
for (from, to) in [
|
||||
("catalog.cc", "catalog-v2.cc"),
|
||||
("ghostlight.vault_snapshot.v1", "ghostlight.vault_snapshot.v2"),
|
||||
("recovery = \"rebuildable\"", "recovery = \"preserve\""),
|
||||
("dungeon-v1", "dungeon-v2"),
|
||||
] {
|
||||
let drifted = RECIPE_TOML.replacen(from, to, 1);
|
||||
assert_ne!(drifted, RECIPE_TOML, "{from} is not in the recipe");
|
||||
assert_ne!(recipe_state(&drifted), state_text(&declaration), "{from} -> {to} went unseen");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_recipe_provides_what_the_daemon_provides_and_nothing_retired() {
|
||||
let provided = format!(
|
||||
"capability = \"ghostlight.world-service\"\nschema = \"{STATE_SCHEMA}\"\ncompatibility = \"{}\"",
|
||||
state_schema_compatibility_tag()
|
||||
);
|
||||
assert!(RECIPE_TOML.contains(&provided), "recipe [[provides]] disagrees with actual_capabilities()");
|
||||
assert_eq!(RECIPE_TOML.matches("[[provides]]").count(), 1);
|
||||
let odin = format!(
|
||||
"kind = \"shared-infrastructure\"\ncapability = \"{}\"\nschema = \"{}\"\ncompatibility = \"{}\"",
|
||||
ODIN_CAPABILITY.0, ODIN_CAPABILITY.1, ODIN_CAPABILITY.2
|
||||
);
|
||||
assert!(RECIPE_TOML.contains(&odin), "recipe Odin dependency disagrees with ODIN_CAPABILITY");
|
||||
assert_eq!(RECIPE_TOML.matches("[[dependencies]]").count(), 1);
|
||||
let lowered = RECIPE_TOML.to_lowercase();
|
||||
for word in ["eve", "mesh", "codexconnector", "codex-connector", "web-build", "npm"] {
|
||||
assert!(!lowered.split(|c: char| !c.is_alphanumeric() && c != '-').any(|token| token == word), "recipe names {word}");
|
||||
}
|
||||
assert!(!lowered.contains("connection-ghostlight.key"), "the key path belongs to the operator binding");
|
||||
assert!(!lowered.contains("credentials_directory"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ mod catalog;
|
|||
mod heimdall;
|
||||
mod idunn_health;
|
||||
mod invite;
|
||||
mod page;
|
||||
mod play;
|
||||
mod run_ahead;
|
||||
mod runtime;
|
||||
|
|
|
|||
44
crates/ghostlight-dungeon/src/page.rs
Normal file
44
crates/ghostlight-dungeon/src/page.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
//! The play page: three static files compiled into the binary and served from
|
||||
//! the router's root. They hold presentation only and no secret, so there is
|
||||
//! no page directory to resolve at run time and nothing to drift from the
|
||||
//! binary.
|
||||
|
||||
use crate::runtime::AppState;
|
||||
use axum::{
|
||||
Router,
|
||||
http::{HeaderValue, StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
|
||||
const INDEX: &str = include_str!("../page/index.html");
|
||||
const STYLE: &str = include_str!("../page/page.css");
|
||||
const SCRIPT: &str = include_str!("../page/page.js");
|
||||
|
||||
/// The page loads only its own script and style and talks only to its own
|
||||
/// origin, so injected markup has nowhere to run or to send anything.
|
||||
const POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; \
|
||||
img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
||||
|
||||
fn file(content_type: &'static str, body: &'static str) -> Response {
|
||||
(
|
||||
StatusCode::OK,
|
||||
[
|
||||
(header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
|
||||
(header::CACHE_CONTROL, HeaderValue::from_static("no-cache")),
|
||||
(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(POLICY)),
|
||||
(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
|
||||
(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer")),
|
||||
(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")),
|
||||
],
|
||||
body,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub(crate) fn router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/", get(|| async { file("text/html; charset=utf-8", INDEX) }))
|
||||
.route("/page.css", get(|| async { file("text/css; charset=utf-8", STYLE) }))
|
||||
.route("/page.js", get(|| async { file("text/javascript; charset=utf-8", SCRIPT) }))
|
||||
}
|
||||
|
|
@ -45,8 +45,18 @@ use tokio::sync::{Mutex, Semaphore, mpsc};
|
|||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const CULTNET_SNAPSHOT_BODY_LIMIT: usize = 16 * 1024;
|
||||
const PROXY_HEADERS: [&str; 5] = [
|
||||
"x-real-ip",
|
||||
"x-forwarded-for",
|
||||
"x-forwarded-host",
|
||||
"x-forwarded-proto",
|
||||
"forwarded",
|
||||
];
|
||||
const CONNECTOR_ADDRESS_ENVIRONMENT: &str = "GHOSTLIGHT_CONNECTOR_ADDR";
|
||||
const CONNECTOR_KEY_CREDENTIAL: &str = "connector-key";
|
||||
/// The credential path Idunn hands the workload: the operator binding's
|
||||
/// `[workload.secret_files]` entry of this name becomes a systemd credential
|
||||
/// and this variable holds the path of the loaded file, never its bytes.
|
||||
const CONNECTOR_KEY_FILE_ENVIRONMENT: &str = "GHOSTLIGHT_CONNECTOR_KEY_FILE";
|
||||
const CONNECTOR_CALLER: &str = "ghostlight";
|
||||
|
||||
#[derive(Clone)]
|
||||
|
|
@ -74,19 +84,24 @@ struct ProductionAdmission {
|
|||
write_lease: ProcessWriteLeaseGuard,
|
||||
}
|
||||
|
||||
/// The connector binding the Dungeon opens its one inference port with. The
|
||||
/// key is read here and nowhere else, from the systemd credential directory,
|
||||
/// and only its path is handed on.
|
||||
/// The connector binding the Dungeon opens its one inference port with. Only
|
||||
/// the path of the key's credential file is read here; the one connector port
|
||||
/// opens the file.
|
||||
fn connector_binding() -> anyhow::Result<ConnectorBinding> {
|
||||
let endpoint = std::env::var(CONNECTOR_ADDRESS_ENVIRONMENT)
|
||||
.with_context(|| format!("{CONNECTOR_ADDRESS_ENVIRONMENT} is required"))?
|
||||
.parse()
|
||||
.with_context(|| format!("{CONNECTOR_ADDRESS_ENVIRONMENT} is not a socket address"))?;
|
||||
let credentials =
|
||||
std::env::var_os("CREDENTIALS_DIRECTORY").context("CREDENTIALS_DIRECTORY is required")?;
|
||||
let key_path = std::env::var_os(CONNECTOR_KEY_FILE_ENVIRONMENT)
|
||||
.map(PathBuf::from)
|
||||
.with_context(|| format!("{CONNECTOR_KEY_FILE_ENVIRONMENT} is required"))?;
|
||||
ensure!(
|
||||
key_path.is_absolute(),
|
||||
"{CONNECTOR_KEY_FILE_ENVIRONMENT} is not an absolute path"
|
||||
);
|
||||
Ok(ConnectorBinding {
|
||||
endpoint,
|
||||
key_path: PathBuf::from(credentials).join(CONNECTOR_KEY_CREDENTIAL),
|
||||
key_path,
|
||||
caller_runtime_id: CONNECTOR_CALLER.into(),
|
||||
})
|
||||
}
|
||||
|
|
@ -146,6 +161,7 @@ pub(crate) fn service_router(state: AppState) -> Router {
|
|||
post(cultnet_snapshot).layer(DefaultBodyLimit::max(CULTNET_SNAPSHOT_BODY_LIMIT)),
|
||||
)
|
||||
.merge(api::router())
|
||||
.merge(crate::page::router())
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
|
|
@ -290,8 +306,12 @@ async fn cultnet_snapshot(
|
|||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
if !peer.ip().is_loopback() {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
// Idunn's route observation reaches this daemon straight over loopback and
|
||||
// carries no proxy header. nginx sets `X-Real-IP` on every request it
|
||||
// forwards, so a request that carries any of these came from the public
|
||||
// side and finds no route here, whatever its peer address says.
|
||||
if !peer.ip().is_loopback() || PROXY_HEADERS.iter().any(|name| headers.contains_key(*name)) {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
if headers.get(header::CONTENT_TYPE) != Some(&HeaderValue::from_static("application/msgpack")) {
|
||||
return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
|
||||
|
|
@ -804,25 +824,32 @@ mod tests {
|
|||
}
|
||||
|
||||
/// The connector key is a credential path, never a value: the binding
|
||||
/// carries the path under CREDENTIALS_DIRECTORY and the caller id, and
|
||||
/// carries the path Idunn's credential delivered and the caller id, and
|
||||
/// nothing else of it.
|
||||
#[test]
|
||||
fn the_connector_key_is_bound_by_credential_path_only() {
|
||||
// SAFETY: the test sets and clears process env it alone reads.
|
||||
unsafe {
|
||||
std::env::set_var(CONNECTOR_ADDRESS_ENVIRONMENT, "127.0.0.1:7001");
|
||||
std::env::set_var("CREDENTIALS_DIRECTORY", "/run/credentials/ghostlight.service");
|
||||
std::env::set_var(
|
||||
CONNECTOR_KEY_FILE_ENVIRONMENT,
|
||||
"/run/credentials/idunn-ghostlight-x.service/GHOSTLIGHT_CONNECTOR_KEY_FILE",
|
||||
);
|
||||
}
|
||||
let binding = connector_binding().unwrap();
|
||||
assert_eq!(binding.caller_runtime_id, "ghostlight");
|
||||
assert_eq!(
|
||||
binding.key_path,
|
||||
PathBuf::from("/run/credentials/ghostlight.service").join("connector-key")
|
||||
PathBuf::from("/run/credentials/idunn-ghostlight-x.service/GHOSTLIGHT_CONNECTOR_KEY_FILE")
|
||||
);
|
||||
unsafe {
|
||||
std::env::remove_var("CREDENTIALS_DIRECTORY");
|
||||
std::env::set_var(CONNECTOR_KEY_FILE_ENVIRONMENT, "relative/key");
|
||||
}
|
||||
assert!(connector_binding().is_err(), "no credential directory, no binding");
|
||||
assert!(connector_binding().is_err(), "a relative path is no credential");
|
||||
unsafe {
|
||||
std::env::remove_var(CONNECTOR_KEY_FILE_ENVIRONMENT);
|
||||
}
|
||||
assert!(connector_binding().is_err(), "no credential path, no binding");
|
||||
unsafe {
|
||||
std::env::remove_var(CONNECTOR_ADDRESS_ENVIRONMENT);
|
||||
}
|
||||
|
|
|
|||
122
deployment/idunn/recipe.toml
Normal file
122
deployment/idunn/recipe.toml
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
schema = "gamecult.idunn.target_declaration.v1"
|
||||
target = "ghostlight"
|
||||
source_stamp_environment = "GHOSTLIGHT_BUILD_COMMIT"
|
||||
|
||||
# The Dungeon is one binary: the page is compiled into it, so there is no
|
||||
# adjacent artifact. The connector key is not declared here: the operator
|
||||
# binding's [workload.secret_files] entry GHOSTLIGHT_CONNECTOR_KEY_FILE is what
|
||||
# Idunn loads as a systemd credential, and the recipe only names the variable
|
||||
# that then holds the credential's path.
|
||||
|
||||
[[steps]]
|
||||
id = "test-dungeon"
|
||||
phase = "test"
|
||||
runner = "rust-build"
|
||||
required_environment = ["CARGO_HOME", "HOME"]
|
||||
argv = ["cargo", "test", "--locked", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
|
||||
|
||||
[[steps]]
|
||||
id = "build-daemon"
|
||||
phase = "build"
|
||||
runner = "rust-build"
|
||||
required_environment = ["CARGO_HOME", "HOME"]
|
||||
argv = ["cargo", "build", "--locked", "--release", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
|
||||
|
||||
[[artifacts]]
|
||||
id = "ghostlight-dungeon"
|
||||
source_kind = "runner-output"
|
||||
runner = "rust-build"
|
||||
source = "target/release/ghostlight-dungeon"
|
||||
destination = "ghostlight-dungeon"
|
||||
executable = true
|
||||
|
||||
[service]
|
||||
executable_artifact = "ghostlight-dungeon"
|
||||
arguments = [
|
||||
{ kind = "literal", value = "--state-root" },
|
||||
{ kind = "binding", name = "state_root" },
|
||||
]
|
||||
transport = "http"
|
||||
route_required = true
|
||||
required_environment = [
|
||||
"GAMECULT_IDUNN_CANDIDATE_BIND",
|
||||
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
|
||||
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
|
||||
"GHOSTLIGHT_CONNECTOR_ADDR",
|
||||
"GHOSTLIGHT_CONNECTOR_KEY_FILE",
|
||||
"GHOSTLIGHT_DISCORD_GUILD_ID",
|
||||
"GHOSTLIGHT_DISCORD_ROLE_ID",
|
||||
"GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE",
|
||||
"GHOSTLIGHT_HEIMDALL_BASE_URL",
|
||||
"GHOSTLIGHT_PUBLIC_APP_URL",
|
||||
"GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE",
|
||||
]
|
||||
optional_environment = [
|
||||
"GHOSTLIGHT_AUTH_PROVIDERS",
|
||||
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT",
|
||||
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
|
||||
"GHOSTLIGHT_PLAY_MODEL",
|
||||
"RUST_LOG",
|
||||
]
|
||||
|
||||
[service.health]
|
||||
contract = "ghostlight.cultnet-rudp-service-health"
|
||||
|
||||
# Idunn's state kinds are files. The snapshots and timelines slots are
|
||||
# directories the daemon owns; they are declared as opaque process-owned paths
|
||||
# (external-file), which Idunn preserves and never interprets.
|
||||
[state]
|
||||
schema_generation = "dungeon-v1"
|
||||
|
||||
[[state.slots]]
|
||||
id = "catalog"
|
||||
relative_path = "catalog.cc"
|
||||
kind = "cultcache-file"
|
||||
schema = "ghostlight.dungeon_catalog.v1"
|
||||
writer = "process-bound-single-writer"
|
||||
recovery = "preserve"
|
||||
startup = "create-or-open-after-write-lease"
|
||||
|
||||
[[state.slots]]
|
||||
id = "app-sessions"
|
||||
relative_path = "service/app-sessions-v2.cc"
|
||||
kind = "cultcache-file"
|
||||
schema = "ghostlight.app_session_store.v2"
|
||||
writer = "process-bound-single-writer"
|
||||
recovery = "preserve"
|
||||
startup = "create-or-open-after-write-lease"
|
||||
|
||||
[[state.slots]]
|
||||
id = "snapshots"
|
||||
relative_path = "snapshots"
|
||||
kind = "external-file"
|
||||
schema = "ghostlight.vault_snapshot.v1"
|
||||
writer = "process-bound-single-writer"
|
||||
recovery = "rebuildable"
|
||||
startup = "create-or-open-after-write-lease"
|
||||
|
||||
[[state.slots]]
|
||||
id = "timelines"
|
||||
relative_path = "timelines"
|
||||
kind = "external-file"
|
||||
schema = "ghostlight.world_state.consumer.v6"
|
||||
writer = "process-bound-single-writer"
|
||||
recovery = "preserve"
|
||||
startup = "create-or-open-after-write-lease"
|
||||
|
||||
[[provides]]
|
||||
capability = "ghostlight.world-service"
|
||||
schema = "ghostlight.world_state.consumer.v6"
|
||||
compatibility = "consumer-v6"
|
||||
|
||||
# Heimdall is found through Odin at use, not declared as an Idunn dependency.
|
||||
[[dependencies]]
|
||||
kind = "shared-infrastructure"
|
||||
capability = "odin.verse-rendezvous"
|
||||
schema = "odin.verse-topology.v1"
|
||||
compatibility = "v1"
|
||||
startup = "before-promotion"
|
||||
Loading…
Reference in a new issue