mooncak397 Claude Opus 5.5 commited on
Commit ·
d49e34a
1
Parent(s): 9a61b20
web: Turnstile gate before /session, chat locked until a session exists
Browse filesThe gate widget sends turnstile_token to /session on load and again on a 401 renewal.
No site key (dev): no widget, no lock. Message labels follow the language switch.
fake_api.py --turnstile mimics a backend with TURNSTILE_SECRET set.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- web/README.md +11 -6
- web/app.js +59 -20
- web/dev/fake_api.py +10 -2
- web/index.html +6 -1
- web/style.css +4 -1
web/README.md
CHANGED
|
@@ -24,23 +24,28 @@ The backend must allow the page's origin in `ALLOWED_ORIGIN` (for local use: `ht
|
|
| 24 |
The fake API reacts to a few test words in the chat: `!401`, `!409`, `!429`, `!500`, and
|
| 25 |
"contact" or "erreichen" to open the form. `python web/dev/fake_api.py 6` gives only 6 turns, so
|
| 26 |
the turns-left hint shows at once. In the form, a message with `!503` gives the "not set up" error.
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
## Config
|
| 29 |
|
| 30 |
Edit `config.js`. Both values are public by design; never put a secret here.
|
| 31 |
|
| 32 |
- `API_BASE`: the backend URL without a trailing slash, for example the Hugging Face Space URL.
|
| 33 |
-
- `TURNSTILE_SITE_KEY`: the Cloudflare Turnstile site key.
|
| 34 |
-
|
| 35 |
-
`
|
| 36 |
|
| 37 |
## How it talks to the backend
|
| 38 |
|
| 39 |
1. Page load: `GET /health`, which wakes a sleeping Space. A note shows if it takes longer than 1.5 s.
|
| 40 |
-
2.
|
| 41 |
-
The
|
|
|
|
|
|
|
| 42 |
3. `POST /chat` with `Authorization: Bearer <token>` and `{"message": "..."}`. A 401 gets a new
|
| 43 |
-
session, one retry, and a note to the user.
|
| 44 |
4. When a reply has `show_form: true`, the form shows. It posts `{email, message, turnstile_token}`
|
| 45 |
to `/contact` with the same token.
|
| 46 |
|
|
|
|
| 24 |
The fake API reacts to a few test words in the chat: `!401`, `!409`, `!429`, `!500`, and
|
| 25 |
"contact" or "erreichen" to open the form. `python web/dev/fake_api.py 6` gives only 6 turns, so
|
| 26 |
the turns-left hint shows at once. In the form, a message with `!503` gives the "not set up" error.
|
| 27 |
+
`--turnstile` makes `/session` and `/contact` need a Turnstile token, like a backend with
|
| 28 |
+
`TURNSTILE_SECRET` set. Use it together with a Cloudflare test site key in `config.js`:
|
| 29 |
+
`1x00000000000000000000AA` always passes, `2x00000000000000000000AB` always fails (the chat stays locked).
|
| 30 |
|
| 31 |
## Config
|
| 32 |
|
| 33 |
Edit `config.js`. Both values are public by design; never put a secret here.
|
| 34 |
|
| 35 |
- `API_BASE`: the backend URL without a trailing slash, for example the Hugging Face Space URL.
|
| 36 |
+
- `TURNSTILE_SITE_KEY`: the Cloudflare Turnstile site key. With a key, the page shows a security
|
| 37 |
+
check on load and keeps the chat locked until a session exists. Empty means no widget and no lock,
|
| 38 |
+
which only works while the backend has no `TURNSTILE_SECRET` (local dev).
|
| 39 |
|
| 40 |
## How it talks to the backend
|
| 41 |
|
| 42 |
1. Page load: `GET /health`, which wakes a sleeping Space. A note shows if it takes longer than 1.5 s.
|
| 43 |
+
2. Session: with a site key, the page shows the Turnstile widget at once and sends its token as
|
| 44 |
+
`POST /session` with `{"turnstile_token": "..."}`. The question field and chips stay locked until
|
| 45 |
+
the reply `{token, expires_in, turns_left}` arrives. Without a site key it sends `{}` on the first
|
| 46 |
+
question. The token stays in memory only.
|
| 47 |
3. `POST /chat` with `Authorization: Bearer <token>` and `{"message": "..."}`. A 401 gets a new
|
| 48 |
+
session (the widget runs again for a fresh token), one retry, and a note to the user.
|
| 49 |
4. When a reply has `show_form: true`, the form shows. It posts `{email, message, turnstile_token}`
|
| 50 |
to `/contact` with the same token.
|
| 51 |
|
web/app.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
| 15 |
chatTitle: "Conversation",
|
| 16 |
chipsLabel: "Try a question",
|
| 17 |
chips: ["What is his current role?", "Which programming languages does he use?", "What projects has he built?", "How can I reach him?"],
|
|
|
|
| 18 |
inputLabel: "Your question",
|
| 19 |
placeholder: "Type your question",
|
| 20 |
send: "Send",
|
|
@@ -24,6 +25,7 @@
|
|
| 24 |
turns: (n) => n === 0 ? "No questions left. Reload the page to start a new chat."
|
| 25 |
: n === 1 ? "1 question left in this chat." : `${n} questions left in this chat.`,
|
| 26 |
newSession: "Your chat session expired, so a new session has started. Earlier messages are no longer known to the assistant.",
|
|
|
|
| 27 |
err409: "The assistant is still answering your last message. Please wait a moment.",
|
| 28 |
err413: "Your message is too long. Please keep it under 1,000 characters.",
|
| 29 |
err429: "Too many messages right now. Please wait a minute and try again.",
|
|
@@ -53,6 +55,7 @@
|
|
| 53 |
chatTitle: "Unterhaltung",
|
| 54 |
chipsLabel: "Beispielfragen",
|
| 55 |
chips: ["Was ist seine aktuelle Rolle?", "Welche Programmiersprachen nutzt er?", "Welche Projekte hat er gebaut?", "Wie kann ich ihn erreichen?"],
|
|
|
|
| 56 |
inputLabel: "Ihre Frage",
|
| 57 |
placeholder: "Ihre Frage eingeben",
|
| 58 |
send: "Senden",
|
|
@@ -62,6 +65,7 @@
|
|
| 62 |
turns: (n) => n === 0 ? "Keine Fragen mehr. Laden Sie die Seite neu, um einen neuen Chat zu starten."
|
| 63 |
: n === 1 ? "Noch 1 Frage in diesem Chat." : `Noch ${n} Fragen in diesem Chat.`,
|
| 64 |
newSession: "Ihre Chat-Sitzung ist abgelaufen. Eine neue Sitzung wurde gestartet; der Assistent kennt frühere Nachrichten nicht mehr.",
|
|
|
|
| 65 |
err409: "Der Assistent beantwortet noch Ihre letzte Nachricht. Bitte warten Sie einen Moment.",
|
| 66 |
err413: "Ihre Nachricht ist zu lang. Bitte schreiben Sie weniger als 1000 Zeichen.",
|
| 67 |
err429: "Gerade zu viele Nachrichten. Bitte warten Sie eine Minute und versuchen Sie es erneut.",
|
|
@@ -85,13 +89,16 @@
|
|
| 85 |
const $ = (id) => document.getElementById(id);
|
| 86 |
const log = $("log"), ask = $("ask"), q = $("q"), sendBtn = ask.querySelector("button");
|
| 87 |
const chips = $("chips"), notice = $("notice"), typing = $("typing");
|
| 88 |
-
const form = $("contact"), cStatus = $("c-status"), cBtn = form.querySelector("button");
|
| 89 |
|
| 90 |
let lang = (navigator.language || "en").toLowerCase().startsWith("de") ? "de" : "en";
|
| 91 |
let token = null; // session token, kept in memory only, gone on reload
|
| 92 |
let turnsLeft = null;
|
| 93 |
let noticeKey = null; // so a language switch re-renders the current notice
|
| 94 |
-
let widgetId = null;
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
const t = (k) => T[lang][k];
|
| 97 |
|
|
@@ -112,9 +119,11 @@
|
|
| 112 |
const b = document.createElement("button");
|
| 113 |
b.type = "button";
|
| 114 |
b.textContent = text;
|
|
|
|
| 115 |
b.addEventListener("click", () => send(text));
|
| 116 |
chips.append(b);
|
| 117 |
});
|
|
|
|
| 118 |
if (!$("wake").hidden) $("wake").textContent = t("waking");
|
| 119 |
setNotice(noticeKey, notice.classList.contains("error"));
|
| 120 |
}
|
|
@@ -124,6 +133,7 @@
|
|
| 124 |
li.className = `msg ${who}`;
|
| 125 |
const label = document.createElement("span");
|
| 126 |
label.className = "who";
|
|
|
|
| 127 |
label.textContent = t(who);
|
| 128 |
const body = document.createElement("p");
|
| 129 |
body.textContent = text; // plain text only
|
|
@@ -139,9 +149,35 @@
|
|
| 139 |
body: JSON.stringify(body),
|
| 140 |
});
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
async function newSession() {
|
| 143 |
token = null;
|
| 144 |
-
const
|
|
|
|
| 145 |
if (!res.ok) throw res; // the caller maps the status to a text
|
| 146 |
token = (await res.json()).token;
|
| 147 |
}
|
|
@@ -156,7 +192,7 @@
|
|
| 156 |
return [await post(path, body), true];
|
| 157 |
}
|
| 158 |
|
| 159 |
-
const errorKey = (status) => ({ 409: "err409", 413: "err413", 429: "err429" })[status] || "err5xx";
|
| 160 |
|
| 161 |
async function send(text) {
|
| 162 |
text = text.trim();
|
|
@@ -181,29 +217,24 @@
|
|
| 181 |
}
|
| 182 |
}
|
| 183 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
function setBusy(busy) {
|
| 185 |
typing.hidden = !busy;
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
q.disabled = done;
|
| 189 |
-
if (!busy && !done && !form.contains(document.activeElement)) q.focus(); // keep focus in a just-opened form
|
| 190 |
}
|
| 191 |
|
| 192 |
function showForm() {
|
| 193 |
if (!form.hidden) return;
|
| 194 |
form.hidden = false;
|
| 195 |
$("contact-title").focus();
|
| 196 |
-
if (SITE_KEY)
|
| 197 |
-
}
|
| 198 |
-
|
| 199 |
-
function loadTurnstile() {
|
| 200 |
-
window.onTurnstileLoad = () => {
|
| 201 |
-
widgetId = window.turnstile.render("#turnstile", { sitekey: SITE_KEY, language: lang });
|
| 202 |
-
};
|
| 203 |
-
const s = document.createElement("script");
|
| 204 |
-
s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onTurnstileLoad";
|
| 205 |
-
s.async = true;
|
| 206 |
-
document.head.append(s);
|
| 207 |
}
|
| 208 |
|
| 209 |
form.addEventListener("submit", async (e) => {
|
|
@@ -223,7 +254,7 @@
|
|
| 223 |
// a 401 is checked before Turnstile on the server, so the retry inside authed() can reuse tsToken
|
| 224 |
const [res] = await authed("/contact", { email: $("c-email").value.trim(), message: $("c-msg").value.trim(), turnstile_token: tsToken });
|
| 225 |
if (!res.ok) { fail(({ 429: "formErr429", 503: "formErr503" })[res.status] || "formErr"); return; }
|
| 226 |
-
form.querySelectorAll("label, input, textarea, button, .hint, #
|
| 227 |
cStatus.textContent = t("sent");
|
| 228 |
cStatus.classList.add("ok");
|
| 229 |
} catch (err) {
|
|
@@ -244,6 +275,14 @@
|
|
| 244 |
}));
|
| 245 |
|
| 246 |
applyLang();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
// Wake the sleeping backend early; show a note only if it takes longer than a moment.
|
| 249 |
const wake = $("wake");
|
|
|
|
| 15 |
chatTitle: "Conversation",
|
| 16 |
chipsLabel: "Try a question",
|
| 17 |
chips: ["What is his current role?", "Which programming languages does he use?", "What projects has he built?", "How can I reach him?"],
|
| 18 |
+
gateHint: "Please complete the short security check to start the chat.",
|
| 19 |
inputLabel: "Your question",
|
| 20 |
placeholder: "Type your question",
|
| 21 |
send: "Send",
|
|
|
|
| 25 |
turns: (n) => n === 0 ? "No questions left. Reload the page to start a new chat."
|
| 26 |
: n === 1 ? "1 question left in this chat." : `${n} questions left in this chat.`,
|
| 27 |
newSession: "Your chat session expired, so a new session has started. Earlier messages are no longer known to the assistant.",
|
| 28 |
+
err403: "The security check failed. Please reload the page and try again.",
|
| 29 |
err409: "The assistant is still answering your last message. Please wait a moment.",
|
| 30 |
err413: "Your message is too long. Please keep it under 1,000 characters.",
|
| 31 |
err429: "Too many messages right now. Please wait a minute and try again.",
|
|
|
|
| 55 |
chatTitle: "Unterhaltung",
|
| 56 |
chipsLabel: "Beispielfragen",
|
| 57 |
chips: ["Was ist seine aktuelle Rolle?", "Welche Programmiersprachen nutzt er?", "Welche Projekte hat er gebaut?", "Wie kann ich ihn erreichen?"],
|
| 58 |
+
gateHint: "Bitte schliessen Sie die kurze Sicherheitsprüfung ab, um den Chat zu starten.",
|
| 59 |
inputLabel: "Ihre Frage",
|
| 60 |
placeholder: "Ihre Frage eingeben",
|
| 61 |
send: "Senden",
|
|
|
|
| 65 |
turns: (n) => n === 0 ? "Keine Fragen mehr. Laden Sie die Seite neu, um einen neuen Chat zu starten."
|
| 66 |
: n === 1 ? "Noch 1 Frage in diesem Chat." : `Noch ${n} Fragen in diesem Chat.`,
|
| 67 |
newSession: "Ihre Chat-Sitzung ist abgelaufen. Eine neue Sitzung wurde gestartet; der Assistent kennt frühere Nachrichten nicht mehr.",
|
| 68 |
+
err403: "Die Sicherheitsprüfung ist fehlgeschlagen. Bitte laden Sie die Seite neu und versuchen Sie es erneut.",
|
| 69 |
err409: "Der Assistent beantwortet noch Ihre letzte Nachricht. Bitte warten Sie einen Moment.",
|
| 70 |
err413: "Ihre Nachricht ist zu lang. Bitte schreiben Sie weniger als 1000 Zeichen.",
|
| 71 |
err429: "Gerade zu viele Nachrichten. Bitte warten Sie eine Minute und versuchen Sie es erneut.",
|
|
|
|
| 89 |
const $ = (id) => document.getElementById(id);
|
| 90 |
const log = $("log"), ask = $("ask"), q = $("q"), sendBtn = ask.querySelector("button");
|
| 91 |
const chips = $("chips"), notice = $("notice"), typing = $("typing");
|
| 92 |
+
const gate = $("gate"), form = $("contact"), cStatus = $("c-status"), cBtn = form.querySelector("button");
|
| 93 |
|
| 94 |
let lang = (navigator.language || "en").toLowerCase().startsWith("de") ? "de" : "en";
|
| 95 |
let token = null; // session token, kept in memory only, gone on reload
|
| 96 |
let turnsLeft = null;
|
| 97 |
let noticeKey = null; // so a language switch re-renders the current notice
|
| 98 |
+
let widgetId = null; // Turnstile widget in the contact form
|
| 99 |
+
let gateWidget = null; // Turnstile widget that guards /session
|
| 100 |
+
let tsReady = null, tsWaiter = null;
|
| 101 |
+
let locked = !!SITE_KEY; // no chat until the first session exists
|
| 102 |
|
| 103 |
const t = (k) => T[lang][k];
|
| 104 |
|
|
|
|
| 119 |
const b = document.createElement("button");
|
| 120 |
b.type = "button";
|
| 121 |
b.textContent = text;
|
| 122 |
+
b.disabled = locked;
|
| 123 |
b.addEventListener("click", () => send(text));
|
| 124 |
chips.append(b);
|
| 125 |
});
|
| 126 |
+
log.querySelectorAll(".who").forEach((el) => { el.textContent = t(el.dataset.who); });
|
| 127 |
if (!$("wake").hidden) $("wake").textContent = t("waking");
|
| 128 |
setNotice(noticeKey, notice.classList.contains("error"));
|
| 129 |
}
|
|
|
|
| 133 |
li.className = `msg ${who}`;
|
| 134 |
const label = document.createElement("span");
|
| 135 |
label.className = "who";
|
| 136 |
+
label.dataset.who = who; // so a language switch can relabel it
|
| 137 |
label.textContent = t(who);
|
| 138 |
const body = document.createElement("p");
|
| 139 |
body.textContent = text; // plain text only
|
|
|
|
| 149 |
body: JSON.stringify(body),
|
| 150 |
});
|
| 151 |
|
| 152 |
+
const turnstileReady = () => tsReady ??= new Promise((resolve, reject) => {
|
| 153 |
+
window.onTurnstileLoad = resolve;
|
| 154 |
+
const s = document.createElement("script");
|
| 155 |
+
s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onTurnstileLoad";
|
| 156 |
+
s.async = true;
|
| 157 |
+
s.onerror = reject;
|
| 158 |
+
document.head.append(s);
|
| 159 |
+
});
|
| 160 |
+
|
| 161 |
+
// A fresh Turnstile token from the gate widget (tokens are single use). No site key (dev): null.
|
| 162 |
+
function freshToken() {
|
| 163 |
+
if (!SITE_KEY) return Promise.resolve(null);
|
| 164 |
+
return new Promise((resolve, reject) => {
|
| 165 |
+
tsWaiter = resolve;
|
| 166 |
+
gate.hidden = false;
|
| 167 |
+
turnstileReady().then(() => {
|
| 168 |
+
if (gateWidget !== null) return window.turnstile.reset(gateWidget);
|
| 169 |
+
gateWidget = window.turnstile.render("#ts-start", {
|
| 170 |
+
sitekey: SITE_KEY, language: lang,
|
| 171 |
+
callback: (tok) => { if (!tsWaiter) return; gate.hidden = true; tsWaiter(tok); tsWaiter = null; },
|
| 172 |
+
});
|
| 173 |
+
}).catch(reject);
|
| 174 |
+
});
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
async function newSession() {
|
| 178 |
token = null;
|
| 179 |
+
const ts = await freshToken();
|
| 180 |
+
const res = await post("/session", ts ? { turnstile_token: ts } : {});
|
| 181 |
if (!res.ok) throw res; // the caller maps the status to a text
|
| 182 |
token = (await res.json()).token;
|
| 183 |
}
|
|
|
|
| 192 |
return [await post(path, body), true];
|
| 193 |
}
|
| 194 |
|
| 195 |
+
const errorKey = (status) => ({ 403: "err403", 409: "err409", 413: "err413", 429: "err429" })[status] || "err5xx";
|
| 196 |
|
| 197 |
async function send(text) {
|
| 198 |
text = text.trim();
|
|
|
|
| 217 |
}
|
| 218 |
}
|
| 219 |
|
| 220 |
+
function updateControls(busy = false) {
|
| 221 |
+
const done = turnsLeft === 0;
|
| 222 |
+
sendBtn.disabled = busy || done || locked;
|
| 223 |
+
q.disabled = done || locked;
|
| 224 |
+
chips.querySelectorAll("button").forEach((b) => { b.disabled = locked; });
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
function setBusy(busy) {
|
| 228 |
typing.hidden = !busy;
|
| 229 |
+
updateControls(busy);
|
| 230 |
+
if (!busy && !q.disabled && !form.contains(document.activeElement)) q.focus(); // keep focus in a just-opened form
|
|
|
|
|
|
|
| 231 |
}
|
| 232 |
|
| 233 |
function showForm() {
|
| 234 |
if (!form.hidden) return;
|
| 235 |
form.hidden = false;
|
| 236 |
$("contact-title").focus();
|
| 237 |
+
if (SITE_KEY) turnstileReady().then(() => { widgetId = window.turnstile.render("#ts-form", { sitekey: SITE_KEY, language: lang }); });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
}
|
| 239 |
|
| 240 |
form.addEventListener("submit", async (e) => {
|
|
|
|
| 254 |
// a 401 is checked before Turnstile on the server, so the retry inside authed() can reuse tsToken
|
| 255 |
const [res] = await authed("/contact", { email: $("c-email").value.trim(), message: $("c-msg").value.trim(), turnstile_token: tsToken });
|
| 256 |
if (!res.ok) { fail(({ 429: "formErr429", 503: "formErr503" })[res.status] || "formErr"); return; }
|
| 257 |
+
form.querySelectorAll("label, input, textarea, button, .hint, #ts-form").forEach((el) => el.remove());
|
| 258 |
cStatus.textContent = t("sent");
|
| 259 |
cStatus.classList.add("ok");
|
| 260 |
} catch (err) {
|
|
|
|
| 275 |
}));
|
| 276 |
|
| 277 |
applyLang();
|
| 278 |
+
updateControls();
|
| 279 |
+
|
| 280 |
+
// Production: pass the Turnstile gate and open a session before the first question.
|
| 281 |
+
if (SITE_KEY) {
|
| 282 |
+
newSession()
|
| 283 |
+
.catch((err) => setNotice(err instanceof Response ? errorKey(err.status) : "errNet", true))
|
| 284 |
+
.finally(() => { locked = false; updateControls(); }); // after a failure the next question retries
|
| 285 |
+
}
|
| 286 |
|
| 287 |
// Wake the sleeping backend early; show a note only if it takes longer than a moment.
|
| 288 |
const wake = $("wake");
|
web/dev/fake_api.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""Fake backend for testing web/ locally. Stdlib only, no model calls. Mirrors the contract of app/main.py.
|
| 2 |
|
| 3 |
-
Run: python web/dev/fake_api.py [turns] (
|
|
|
|
| 4 |
|
| 5 |
Test triggers inside a chat message:
|
| 6 |
!409 / !429 / !500 -> that status !401 -> forget the session (next call gets 401 session_expired)
|
|
@@ -14,7 +15,8 @@ import sys
|
|
| 14 |
import time
|
| 15 |
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 16 |
|
| 17 |
-
TURNS = int(sys.argv[1]
|
|
|
|
| 18 |
sessions: dict[str, int] = {} # token -> user turns used
|
| 19 |
|
| 20 |
|
|
@@ -43,6 +45,10 @@ class Handler(BaseHTTPRequestHandler):
|
|
| 43 |
def do_POST(self):
|
| 44 |
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
| 45 |
if self.path == "/session":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
token = secrets.token_urlsafe(16)
|
| 47 |
sessions[token] = 0
|
| 48 |
return self._send(200, {"token": token, "expires_in": 1800, "turns_left": TURNS})
|
|
@@ -92,6 +98,8 @@ class Handler(BaseHTTPRequestHandler):
|
|
| 92 |
time.sleep(0.6)
|
| 93 |
if not set(body) <= {"email", "message", "turnstile_token"}:
|
| 94 |
return self._send(422, {"detail": "extra fields"})
|
|
|
|
|
|
|
| 95 |
for code in (500, 503):
|
| 96 |
if f"!{code}" in str(body.get("message", "")):
|
| 97 |
return self._send(code, {"detail": "test"})
|
|
|
|
| 1 |
"""Fake backend for testing web/ locally. Stdlib only, no model calls. Mirrors the contract of app/main.py.
|
| 2 |
|
| 3 |
+
Run: python web/dev/fake_api.py [turns] [--turnstile] (http://localhost:8787, default 20 turns)
|
| 4 |
+
--turnstile: /session and /contact need a turnstile_token (like a backend with TURNSTILE_SECRET set)
|
| 5 |
|
| 6 |
Test triggers inside a chat message:
|
| 7 |
!409 / !429 / !500 -> that status !401 -> forget the session (next call gets 401 session_expired)
|
|
|
|
| 15 |
import time
|
| 16 |
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 17 |
|
| 18 |
+
TURNS = next((int(a) for a in sys.argv[1:] if a.isdigit()), 20) # e.g. 6 to see the turns-left hint at once
|
| 19 |
+
TURNSTILE = "--turnstile" in sys.argv
|
| 20 |
sessions: dict[str, int] = {} # token -> user turns used
|
| 21 |
|
| 22 |
|
|
|
|
| 45 |
def do_POST(self):
|
| 46 |
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
| 47 |
if self.path == "/session":
|
| 48 |
+
if not set(body) <= {"turnstile_token"}:
|
| 49 |
+
return self._send(422, {"detail": "extra fields"})
|
| 50 |
+
if TURNSTILE and not body.get("turnstile_token"):
|
| 51 |
+
return self._send(403, {"detail": "turnstile_failed"})
|
| 52 |
token = secrets.token_urlsafe(16)
|
| 53 |
sessions[token] = 0
|
| 54 |
return self._send(200, {"token": token, "expires_in": 1800, "turns_left": TURNS})
|
|
|
|
| 98 |
time.sleep(0.6)
|
| 99 |
if not set(body) <= {"email", "message", "turnstile_token"}:
|
| 100 |
return self._send(422, {"detail": "extra fields"})
|
| 101 |
+
if TURNSTILE and not body.get("turnstile_token"):
|
| 102 |
+
return self._send(403, {"detail": "turnstile_failed"})
|
| 103 |
for code in (500, 503):
|
| 104 |
if f"!{code}" in str(body.get("message", "")):
|
| 105 |
return self._send(code, {"detail": "test"})
|
web/index.html
CHANGED
|
@@ -42,13 +42,18 @@
|
|
| 42 |
<input id="c-email" name="email" type="email" autocomplete="email" required maxlength="254">
|
| 43 |
<label for="c-msg" data-i18n="message"></label>
|
| 44 |
<textarea id="c-msg" name="message" rows="4" required maxlength="2000"></textarea>
|
| 45 |
-
<div id="
|
| 46 |
<p id="c-status" class="status" role="status"></p>
|
| 47 |
<button type="submit" class="primary" data-i18n="submit"></button>
|
| 48 |
</form>
|
| 49 |
|
| 50 |
<p id="notice" class="notice" role="status"></p>
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
<form id="ask" class="ask">
|
| 53 |
<label for="q" class="sr-only" data-i18n="inputLabel">Your question</label>
|
| 54 |
<textarea id="q" rows="1" maxlength="1000" required></textarea>
|
|
|
|
| 42 |
<input id="c-email" name="email" type="email" autocomplete="email" required maxlength="254">
|
| 43 |
<label for="c-msg" data-i18n="message"></label>
|
| 44 |
<textarea id="c-msg" name="message" rows="4" required maxlength="2000"></textarea>
|
| 45 |
+
<div id="ts-form"></div>
|
| 46 |
<p id="c-status" class="status" role="status"></p>
|
| 47 |
<button type="submit" class="primary" data-i18n="submit"></button>
|
| 48 |
</form>
|
| 49 |
|
| 50 |
<p id="notice" class="notice" role="status"></p>
|
| 51 |
|
| 52 |
+
<div id="gate" class="gate" hidden>
|
| 53 |
+
<p data-i18n="gateHint"></p>
|
| 54 |
+
<div id="ts-start"></div>
|
| 55 |
+
</div>
|
| 56 |
+
|
| 57 |
<form id="ask" class="ask">
|
| 58 |
<label for="q" class="sr-only" data-i18n="inputLabel">Your question</label>
|
| 59 |
<textarea id="q" rows="1" maxlength="1000" required></textarea>
|
web/style.css
CHANGED
|
@@ -100,6 +100,9 @@ h2 { font-size: 1.125rem; margin: 0 0 0.25rem; }
|
|
| 100 |
}
|
| 101 |
.chips button:hover { border-color: var(--accent); }
|
| 102 |
|
|
|
|
|
|
|
|
|
|
| 103 |
.notice { margin: 0; font-size: 0.9375rem; color: var(--muted); }
|
| 104 |
.notice:empty { display: none; }
|
| 105 |
.notice.error, .status.error { color: var(--error); }
|
|
@@ -131,7 +134,7 @@ textarea { resize: vertical; }
|
|
| 131 |
font: inherit; font-weight: 600; padding: 0.5rem 1.125rem; min-height: 2.75rem;
|
| 132 |
border: 0; border-radius: var(--radius); background: var(--accent); color: var(--accent-text); cursor: pointer;
|
| 133 |
}
|
| 134 |
-
.primary:disabled { opacity: 0.55; cursor: not-allowed; }
|
| 135 |
|
| 136 |
@media (max-width: 30rem) {
|
| 137 |
.page { padding: 1rem 0.75rem; }
|
|
|
|
| 100 |
}
|
| 101 |
.chips button:hover { border-color: var(--accent); }
|
| 102 |
|
| 103 |
+
.gate { display: flex; flex-direction: column; gap: 0.5rem; }
|
| 104 |
+
.gate p { margin: 0; font-size: 0.9375rem; color: var(--muted); }
|
| 105 |
+
|
| 106 |
.notice { margin: 0; font-size: 0.9375rem; color: var(--muted); }
|
| 107 |
.notice:empty { display: none; }
|
| 108 |
.notice.error, .status.error { color: var(--error); }
|
|
|
|
| 134 |
font: inherit; font-weight: 600; padding: 0.5rem 1.125rem; min-height: 2.75rem;
|
| 135 |
border: 0; border-radius: var(--radius); background: var(--accent); color: var(--accent-text); cursor: pointer;
|
| 136 |
}
|
| 137 |
+
.chips button:disabled, .primary:disabled { opacity: 0.55; cursor: not-allowed; }
|
| 138 |
|
| 139 |
@media (max-width: 30rem) {
|
| 140 |
.page { padding: 1rem 0.75rem; }
|