Tokens, CSP, approvals, PathGuard, SSRF and prompt injection: how Haris keeps a language model on a short leash.
Part 2 of 3 in "Building Haris". Part 1: “I built an open-source AI assistant for Windows that asks before it opens an app, writes a file or shuts down your PC”.
Before launch, a request to /%61pi/memory walked straight past my assistant's session-token check and reached the memory API. The filter checked the raw URL; Spring routed on the decoded one. That bug is why "canonical" is now step 3 of every request in Haris, and it's a good way into the whole question this article is about: how do you let a language model touch your PC when you don't trust it?
Haris is an open-source desktop AI assistant for Windows. It can open apps, write files, read web pages, take a screenshot and lock your PC. That makes it a juicy target, so its design starts from one assumption: the model is not trusted. Not because models are evil, but because they read text written by strangers, and because anything running on your PC can try to talk to the assistant too.
This article walks through the layers, from the outside in. The code is from the repository, version 0.6.0.
The threat model in one table
| Threat | Defence |
|---|---|
| Other devices on the network | The server binds to 127.0.0.1 only. No firewall rules, no admin rights. |
| Other programs or web pages on this PC | Per-launch 256-bit session token on every request except the HUD's static files; non-canonical paths refused. |
| DNS rebinding, cross-site requests | Host must be the loopback address; state-changing calls must carry this server's Origin. |
| Script injection in the HUD | Strict CSP, model output rendered as text only. |
| Leaked API keys | Windows Credential Manager; the UI can write keys but never read them back. |
| Running model-written code | No shell, exec or script tool. |
| The model approving its own actions | Approvals only by a click in the HUD: never by voice, never by another AI model, and no setting turns them off. |
| Prompt injection | Reduced, not solved: outside content is fenced and flags the conversation. |
| Files outside what you chose | PathGuard. |
SSRF from fetch_page | Public addresses on 80/443 only, DNS pinned, redirects re-checked. |
Out of scope, stated in THREAT_MODEL.md: an attacker who already runs code as your Windows user (they can read your Credential Manager anyway) and what a cloud provider you chose does with your data. SECURITY.md, which is about reporting vulnerabilities, adds denial of service against your own machine.
Layer 1: loopback is not a boundary — add a token
Binding to 127.0.0.1 keeps the LAN out. It does nothing against another program on the same PC, or against a web page in your everyday browser firing requests at http://127.0.0.1:<port>. So the core mints a secret on every launch:
public SessionToken() { byte[] bytes = new byte[32]; new SecureRandom().nextBytes(bytes); this.value = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); } /** Constant-time comparison, so response timing reveals nothing about the token. */ public boolean matches(String candidate) { if (candidate == null) { return false; } return MessageDigest.isEqual( value.getBytes(StandardCharsets.US_ASCII), candidate.getBytes(StandardCharsets.US_ASCII)); } The token reaches the HUD exactly once, in the URL fragment of the app window the core opens itself. Fragments are never sent in an HTTP request, so they never reach a server log.
Every request then goes through LocalAccessFilter, which runs before anything else:
- the client must be on the loopback interface;
- the
Hostheader must name this server (127.0.0.1:<port>orlocalhost:<port>) — that defeats DNS rebinding; - the path must be canonical;
- unless it's a
GET/HEADfor one of the HUD's own static files, it must carry the token, and state-changing calls must carry this server'sOrigin.
The bug that taught me "canonical"
Step 3 came out of a security scan before launch. The filter used to decide with getRequestURI().startsWith("/api/") on the raw, undecoded URI. Spring MVC routes on the decoded path with path parameters stripped. So /api;x/memory and /%61pi/memory skipped the token check and still reached the controller.
The fix wasn't a smarter prefix check. It was default-deny plus refusing anything Spring would rewrite:
/** No path parameters, escapes, backslashes, empty or dot segments: nothing Spring would rewrite. */ static boolean isCanonical(String uri) { return uri != null && uri.startsWith("/") && !uri.contains(";") && !uri.contains("%") && !uri.contains("\\") && !uri.contains("//") && !uri.contains("/./") && !uri.contains("/../") && !uri.endsWith("/.") && !uri.endsWith("/.."); } /** A read of one of the HUD's own files, which the page needs before it can present the token. */ static boolean isStaticFile(String method, String uri) { return STATIC_READS.contains(method) && (STATIC_PAGES.contains(uri) || STATIC_ASSET.matcher(uri).matches()); } No legitimate Haris URL needs any of those characters, so a weird URI gets a 400 and a log line. And because the default is now "token required", any future disagreement between the filter and the framework produces a token check, not a bypass.
WebSockets get the same treatment. Browsers can't add custom headers to a WebSocket handshake, so the token travels as the requested sub-protocol, and the Origin (which browsers always send on a handshake) must be this server's.
Layer 2: the HUD can't run what it didn't ship with
The same filter sets a strict Content-Security-Policy on every response:
private static final String CSP = String.join("; ", "default-src 'self'", "script-src 'self'", "style-src 'self'", "img-src 'self' data: blob:", "font-src 'self' data:", "connect-src 'self'", "media-src 'self' blob:", "object-src 'none'", "base-uri 'none'", "form-action 'none'", "frame-ancestors 'none'"); No inline scripts, no remote scripts, no fetching anywhere but the core. On top of that, model output is always rendered as text, never as HTML. CSP is the seatbelt; never using innerHTML for model output is the brakes. A Permissions-Policy header allows the camera and microphone only for the page itself, and nothing else.
Layer 3: the gate
Every tool declares a risk, and the agent loop asks one question before running a call: who has to approve this?
/** Returns how the action was authorised, or null if it was not. */ private String decide(Tool tool, JsonNode input, String summary, Risk risk, Conversation conversation, AgentListener listener, String preview, String destination) { boolean external = conversation.hasExternalContent(); // Outside content may carry instructions to leak data through a query, link or message: // from then on, anything that sends arguments off the machine is shown to the user first. boolean exfiltrationRisk = external && tool.sendsDataOut(); if (risk == Risk.SAFE && !exfiltrationRisk) { return "auto"; } if (risk == Risk.CONFIRM && !external && tool.sessionApprovable() && conversation.approvedForSession(tool.name())) { return "session"; } boolean offerSession = risk == Risk.CONFIRM && !external && tool.sessionApprovable(); ConfirmationBroker.Decision d = confirmations.ask(tool.name(), summary, risk, offerSession, external, prettyArgs(input), preview, destination, listener::onConfirm); // ... DENY -> null, ALLOW_ONCE -> "approved", ALLOW_SESSION -> remember for this conversation } A few properties fall out of this small function:
- SAFE tools (weather, system status, volume, reminders) run and are logged.
- Reading inside the folders you granted (
read_file,list_folder,search_files) is SAFE too: no click. The result is fenced as outside content, and if you use a cloud engine it goes to that provider like the rest of the conversation. - CONFIRM tools need a click, either once or for the session — unless the tool opts out of session approval (reading the clipboard does: every read is a fresh decision).
- CRITICAL tools never get a session option. Delete goes to the Recycle Bin; restart and shutdown wait 60 seconds and can be cancelled.
- Once outside content is in the conversation, the session shortcut disappears for everything.
The broker waits for the human with a hard limit — TIMEOUT_SECONDS = 120 — and a timeout is a denial.
On the HUD side, the card is built so you can't approve by accident: the buttons stay disabled for 700 ms, Deny has focus, and Esc denies. There is deliberately no voice path to approval, and no other model is ever asked to approve on your behalf. The microphone is an input that any speaker in the room can use, including a video.
Layer 4: prompt injection is handled by consequences, not detection
You can't reliably detect a malicious instruction hidden in a web page. Haris doesn't try. Instead, it tracks where text came from and changes what's allowed afterwards.
Every tool declares whether its output can carry text that someone other than the user chose:
/** * Whether this tool's output can carry text that someone other than the user chose: * file and folder names, web pages, app names, place names, screen contents. * Such output — and any error such a tool reports — is fenced off for the model and * marks the conversation as holding outside content. */ default boolean readsOutsideContent() { return false; } Ten tools say yes: read_file, clipboard_read, web_search, fetch_page, look_at_screen, look_through_camera, list_folder, search_files, list_apps and weather. The scan caught two of the last four: folder listings and file-search results carry names that whoever created the files chose. Going through every tool after that added list_apps (app names are chosen by installers) and weather (place names come from a remote API). Even a tool's error message gets fenced — the scan flagged fetch_page's error path: a malicious server can put words in a status line.
A test now scans every class implementing Tool and fails unless it's listed as either "outside content" or "trusted output", so a future tool can't forget to decide.
When such output arrives, three things happen: it's wrapped in an <external_content> envelope with a note that it's data; the conversation is flagged; and from then on, any tool with sendsDataOut() — web search, opening a URL, drafting a message — needs approval and shows the exact data, even if it's normally SAFE. An injected page can still ask to smuggle your data into a search query. It just can't do it without you reading the query first.
Layer 5: PathGuard — a file system with walls
File tools only see folders you grant in Settings. Every path is resolved to its real path and checked:
private Path interpret(String raw) throws ToolException { String cleaned = raw.strip(); // ... if (cleaned.startsWith("\\\\") || cleaned.startsWith("//")) { throw new ToolException("Network paths are not allowed."); } if (cleaned.contains(":") && cleaned.indexOf(':') != 1) { throw new ToolException("Alternate data streams and device paths are not allowed."); } // ... } Beyond that: no .., symlink or junction escapes (real-path checks, and no writing through a symbolic link); dot-files and dot-folders (like .git) can't be modified; and secrets are unreadable wherever they sit — .env files, SSH keys, .pem, .pfx, .kdbx, anything named like a credential, plus folders such as .ssh, .aws and .docker.
Writes are narrower still, because a file is also a way to run code later:
/** The only types write_file creates: it writes text, so nothing else is needed. */ private static final Set<String> TEXT_TYPES = Set.of( "txt", "md", "markdown", "csv", "tsv", "json", "log", "yaml", "yml", "xml", "srt"); A rename must keep the file's type (or stay within text types), and nothing may be created or renamed to an executable type — a list that includes exe, ps1, lnk, py, pyw, msc, chm, macro-enabled Office files and disk images. Folder names ending in .{CLSID} are refused too, because Windows turns those into shell objects.
Layer 6: SSRF — the web tools only see the public web
fetch_page is a classic server-side request forgery risk: an injected instruction could point it at your router's admin page, a cloud metadata service, or Haris's own local engines. (web_search can't be aimed anywhere: it only queries the local SearXNG on a fixed port.) NetGuard allows only http/https, ports 80 and 443, no embedded credentials, and no local names (localhost, .local, .lan, .internal, .home.arpa, bare hostnames). Literal IPs must be public:
public static boolean isPublic(InetAddress a) { if (a.isAnyLocalAddress() || a.isLoopbackAddress() || a.isLinkLocalAddress() || a.isSiteLocalAddress() || a.isMulticastAddress()) { return false; } // ... plus 0/8, carrier-grade NAT, 192.0.0/24, 198.18/15, 224+/4, fc00::/7, 2001:db8::/32 // and IPv4-mapped IPv6 addresses } Checking the URL isn't enough, because DNS can answer with a private address. So the check also lives inside the resolver the HTTP client uses, and the client is told not to use a proxy (a proxy would resolve names itself):
/** Resolver that refuses any answer pointing into a private or local network. */ static final Dns PUBLIC_ONLY = hostname -> { List<InetAddress> all = Arrays.asList(InetAddress.getAllByName(hostname)); for (InetAddress a : all) { if (!NetGuard.isPublic(a)) { throw new UnknownHostException(hostname + " points into a private network; blocked"); } } return all; }; Redirects are never followed automatically; each hop (at most three) goes back through the same checks.
Layer 7: secrets and memory
API keys go into Windows Credential Manager. The settings endpoint can write a key, remove it, and report whether one is stored, but no endpoint returns it. Memory is a file encrypted with AES-256-GCM whose key also lives in the vault. Saving a fact needs your approval, and facts that look like passwords, codes, keys or card numbers are refused. The plain-text audit log never stores private content (clipboard text, message bodies, memory facts): a clipboard write is logged as "Copy 42 characters to clipboard", not the text.
What I'd tell anyone building an agent
- Make the dangerous thing impossible, not discouraged. No shell tool beats any prompt that says "don't run commands".
- Put a human click in the path, and make it hard to click through. Arm delays, deny-by-default focus, timeouts.
- Track provenance. You can't detect injection, but you can know that untrusted text entered the conversation and tighten the rules from there.
- Default-deny at every boundary — HTTP paths, file types, network addresses.
- Write a test that forces future code to decide. The tool-trust test has already paid for itself.
The full version of this table is THREAT_MODEL.md in the repo. It maps every layer above to the OWASP Top 10 for Agentic Applications (2026), from ASI01 goal hijack to ASI10 rogue agents, and it states the residual risks plainly: prompt injection is reduced, not solved; remote engines see your conversation; read-only file tools run without a click; the installer isn't code-signed yet. It also lists the Stop button under ASI08 (cascading failures): while a reply runs, Send becomes a red Stop that ends the reply, nothing new runs, and a tool that is already running finishes. If an approval card is open, the window is locked, and Deny (or Esc) declines that action.
Haris is MIT-licensed: https://github.com/TENMATECH-DIGITAL-SOLUTIONS/haris. If you can break any of this, please use the repository's Security → Report a vulnerability — fixes are released before details are published.

