okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
1"""serve/test_web_start_question.py - /?q= fills in the question and never sends it (#4221). 2 3Opening /?q=<text> used to put the text in the box and call send() on load, so any web page could link to 4http://127.0.0.1:<port>/?q=... and make the model answer, with the API key and the MCP tools saved in that browser, 5without the person pressing Send. The page's own start() runs here under Node against a fake page and a fake credentialed 6backend with a request spy: after navigation and after a reload there are zero generation, tool or chat requests, the 7question is in the box and the box has focus; only an explicit Send (the composer's own handler) reaches the backend. 8Skipped without node. 9 10python -m unittest serve.test_web_start_question -v 11""" 12from __future__import annotations 13 14import json 15import re 16import shutil 17import subprocess 18import unittest 19from pathlib import Path 20 21APP = Path (__file__ ).resolve ().parent / "web" / "app.js" 22 23 24def between (src :str ,start :str ,end :str )-> str : 25a = src .index (start ) 26return src [a :src .index (end ,a )] 27 28 29HARNESS = r""" 30const calls = []; // every request the page makes to its backend, in order 31const sends = []; // every time the page's send() runs 32const focus = []; 33const input = {value: "", style: {}, scrollHeight: 40, focus() { focus.push("input"); }}; 34const page = {url: new URL(%(url)s), hash: ""}; 35const location = { 36get search() { return page.url.search; }, 37get pathname() { return page.url.pathname; }, 38get hash() { return page.hash; }, 39}; 40const history = {replaceState(_s, _t, url) { page.url = new URL(url, page.url); }}; 41const innerHeight = 800; 42const $ = (id) => (id === "input" ? input : {focus() {}, set value(v) {}, get value() { return ""; }}); 43// a credentialed backend: the saved API key and the MCP tools are what a send would use 44async function fetch(path, opts) { calls.push({path: String(path), method: (opts && opts.method) || "GET", auth: !!(opts && opts.headers && opts.headers.Authorization)}); return {ok: true, json: async () => ({})}; } 45const StrataI18n = {lang: "en", setLanguage: async () => {}}; 46const store = {get: (_k, d) => d}; 47const settings = {chatList: false}; 48const urlLang = null; 49const tab = "chat"; 50function renderEmptyChat() {} 51function initChats() {} 52async function setChatList() {} 53function setBusy() {} 54function renderChat() {} 55function poll() {} 56function fitHeader() {} 57const requestAnimationFrame = () => {}; 58async function loadHealth() { await fetch("health"); } 59async function loadMcp() { await fetch("v1/mcp"); } 60function showTab(name) { focus.push("tab:" + (name || "chat")); } 61async function send() { sends.push(input.value); await fetch("v1/chat/completions", {method: "POST", headers: {Authorization: "Bearer saved-key"}}); } 62%(autosize)s 63%(start)s 64(async () => { 65await start(); 66await new Promise((r) => setTimeout(r, 20)); // let the health and tool-list fetches settle 67const first = {input: input.value, url: page.url.pathname + page.url.search, calls: calls.slice(), sends: sends.length, focus: focus.slice()}; 68// reload: the browser asks for the address it now has (the ?q= was removed from it by the first start) 69input.value = ""; calls.length = 0; sends.length = 0; focus.length = 0; 70await start(); 71await new Promise((r) => setTimeout(r, 20)); 72const second = {input: input.value, calls: calls.slice(), sends: sends.length}; 73console.log(JSON.stringify({first, second})); 74})(); 75""" 76 77 78@ unittest . skipUnless ( shutil . which ( "node" ), "node is not installed" ) 79class StartQuestion (unittest .TestCase ): 80@classmethod 81def setUpClass (cls ): 82cls .src = APP .read_text (encoding = "utf-8" ) 83cls .start = between (cls .src ,"async function start() {" ,"\nstart();" ) 84m = re .search (r"function autosize\(\)[^\n]*" ,cls .src ) 85assert m ,"autosize() is gone" 86cls .autosize = m .group (0 ) 87 88def run_page (self ,url ): 89js = HARNESS % {"url" :json .dumps (url ),"start" :self .start ,"autosize" :self .autosize } 90out = subprocess .run (["node" ,"-e" ,js ],capture_output = True ,text = True ,timeout = 60 ) 91self .assertEqual (out .returncode ,0 ,out .stderr ) 92return json .loads (out .stdout ) 93 94def test_navigation_fills_the_question_and_sends_nothing (self ): 95r = self .run_page ("http://127.0.0.1:8080/?q=Delete%20my%20files" )["first" ] 96self .assertEqual (r ["input" ],"Delete my files" ) 97self .assertEqual (r ["sends" ],0 ) 98generation = [c for c in r ["calls" ]if c ["method" ]!= "GET" or "chat" in c ["path" ]or "completions" in c ["path" ]or "tool" in c ["path" ]] 99self .assertEqual (generation , [],"no model or tool request fires on navigation" ) 100self .assertFalse ([c for c in r ["calls" ]if c ["auth" ]],"nothing went out with the saved key" ) 101self .assertIn ("input" ,r ["focus" ],"the box is focused" ) 102self .assertEqual (r ["url" ],"/" ,"the question is taken out of the address" ) 103 104def test_reload_after_that_sends_nothing_and_does_not_refill (self ): 105r = self .run_page ("http://127.0.0.1:8080/?q=hello" )["second" ] 106self .assertEqual (r ["sends" ],0 ) 107self .assertEqual (r ["input" ],"" ) 108self .assertEqual ([c for c in r ["calls" ]if c ["method" ]!= "GET" ], []) 109 110def test_no_question_in_the_address_changes_nothing (self ): 111r = self .run_page ("http://127.0.0.1:8080/" )["first" ] 112self .assertEqual (r ["input" ],"" ) 113self .assertEqual (r ["sends" ],0 ) 114 115def test_long_and_odd_questions_are_filled_as_text (self ): 116for q in ["%3Cscript%3Ealert(1)%3C%2Fscript%3E" ,"a" * 5000 ,"%E4%B8%AD%E6%96%87%20x" ]: 117r = self .run_page (f"http://127.0.0.1:8080/?q= { q } " )["first" ] 118self .assertEqual (r ["sends" ],0 ) 119self .assertTrue (r ["input" ]) 120 121def test_the_page_never_calls_send_from_the_address (self ): 122# the only things that call send() are the composer's own submit and the Enter key 123text = self .src .splitlines () 124lines = [n for n ,line in enumerate (text ,1 )if re .search (r"\bsend\(\)" ,line .split ("//" )[0 ])] 125self .assertTrue (lines ) 126for n in lines : 127line = text [n - 1 ] 128self .assertTrue ("onsubmit" in line or "preventDefault" in line ,f"app.js: { n } calls send() outside a person's action: { line . strip () } " ) 129self .assertNotIn ("startQuestion) { $(\"input\").value = startQuestion; send()" ,self .src ) 130 131 132if __name__ == "__main__" : 133unittest .main ()