Skip to content

Flask

This guide adds Bunkhouse to a server-rendered Flask application. Every file shown below is part of a runnable example app that is tested end to end against the real Bunkhouse API and embed.

Framework Flask 3.1.3, Jinja templates, Flask’s signed-cookie session, served by gunicorn 26.2.0
Runtime Python 3.14 (3.14.10 in the tested image)
Example apps/docs/integrations/flask/ in the Bunkhouse repository

You need:

  • Your application’s exact origin registered on the site (for example https://app.example.com).
  • The site’s public key (pk_...).
  • For identity tokens (recommended): a signing secret (ss_...) and its key ID from the site’s Keys page.
  • For server mint instead: a mint key (sk_...).
  • Existing sign-in. The example stores the user’s ID in Flask’s session with two demo users; your own authentication takes its place. Bunkhouse only needs one thing from it: the signed-in user’s stable ID on the server.
File Purpose
app/config.py Validates the public Bunkhouse configuration at startup
app/agent.py Blueprint with GET /api/agent-identity and POST /api/agent-session
app/csp.py Your Content-Security-Policy with the Bunkhouse sources added
app/templates/agent-embed-*.html The page hooks and loader for one installation mode
app/static/agent-identity.js, app/static/agent-auth-headers.js Page hooks, loaded before the loader

Set the server environment. Only AGENT_PUBLIC_KEY and the origins ever reach the browser:

Terminal window
AGENT_PUBLIC_KEY=pk_...
AGENT_SIGNING_SECRET=ss_... # server only
AGENT_SIGNING_KID=... # key ID shown with the signing secret
AGENT_ALLOWED_ORIGINS='["https://app.example.com"]'
# AGENT_API_BASE and AGENT_EMBED_ORIGIN default to https://api.bunkhouse.ai and https://embed.bunkhouse.ai
app/config.py
# Bunkhouse public configuration, validated once at startup. Signing and mint credentials are read
# only by the endpoints that use them, so each mode needs only its own secret.
import ipaddress
import json
import os
import re
from dataclasses import dataclass
from urllib.parse import urlsplit
DEFAULT_PORTS = {"http": 80, "https": 443}
def exact_origin(name: str, value: str) -> str:
"""The value must be its own serialized origin, like JavaScript's new URL(value).origin === value."""
url = urlsplit(value)
try:
host, port = url.hostname or "", url.port
if ":" in host:
valid = "%" not in host and str(ipaddress.IPv6Address(host)) == host
host = f"[{host}]"
elif re.fullmatch(r"0x[0-9a-f]*|\d+", host.rstrip(".").rsplit(".", 1)[-1]):
valid = str(ipaddress.IPv4Address(host)) == host
else:
valid = re.fullmatch(r"[a-z0-9-]+(\.[a-z0-9-]+)*\.?", host) is not None
except ValueError:
valid = False
if not valid or url.scheme not in DEFAULT_PORTS or value != f"{url.scheme}://{host}{'' if port in (None, DEFAULT_PORTS[url.scheme]) else f':{port}'}":
raise ValueError(f"{name} must be an exact origin like https://app.example.com")
return value
@dataclass(frozen=True)
class AgentConfig:
public_key: str
allowed_origins: tuple[str, ...]
api_base: str
embed_origin: str
def load_agent_config() -> AgentConfig:
public_key = os.environ.get("AGENT_PUBLIC_KEY", "")
if not public_key.startswith("pk_"):
raise ValueError("AGENT_PUBLIC_KEY must be the site's public key (pk_...)")
origins = json.loads(os.environ.get("AGENT_ALLOWED_ORIGINS", "[]"))
if not isinstance(origins, list) or not origins:
raise ValueError('AGENT_ALLOWED_ORIGINS must be a JSON array such as ["https://app.example.com"]')
return AgentConfig(
public_key=public_key,
allowed_origins=tuple(exact_origin("AGENT_ALLOWED_ORIGINS", str(o)) for o in origins),
api_base=exact_origin("AGENT_API_BASE", os.environ.get("AGENT_API_BASE", "https://api.bunkhouse.ai")),
embed_origin=exact_origin("AGENT_EMBED_ORIGIN", os.environ.get("AGENT_EMBED_ORIGIN", "https://embed.bunkhouse.ai")),
)
agent_config = load_agent_config()

The blueprint signs a ten-minute HS256 token with the standard library’s hmac for the user your session already authenticated. It rejects other methods (405 with Allow), requests whose Sec-Fetch-Site is not same-origin (403) and signed-out users (401, never a login redirect), and its after_request hook marks every response Cache-Control: no-store. The subject comes only from the server session, never from the query, body or headers. The same file contains the server mint endpoint used by the alternative below.

app/agent.py
# Bunkhouse endpoints: GET /api/agent-identity (identity token mode) and POST /api/agent-session
# (server mint mode). Both vouch only for the user your existing session already authenticated,
# which this blueprint reads from g.user (see load_logged_in_user in app/__init__.py).
import base64
import hashlib
import hmac
import http.client
import json
import os
import time
import urllib.error
import urllib.request
from flask import Blueprint, Response, current_app, g, jsonify, request
from .config import agent_config
bp = Blueprint("agent", __name__)
# Listing every method (OPTIONS too) lets the views answer wrong methods with 405 and no-store.
ALL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
def base64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def sign_identity_token(user_id: str, secret: str, kid: str) -> str:
"""HS256 identity token: kid header, sub = stable opaque user ID, aud = public key, 10 minutes."""
iat = int(time.time())
header = base64url(json.dumps({"alg": "HS256", "typ": "JWT", "kid": kid}, separators=(",", ":")).encode())
payload = base64url(json.dumps({"sub": user_id, "aud": agent_config.public_key, "iat": iat, "exp": iat + 600}, separators=(",", ":")).encode())
signature = base64url(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
return f"{header}.{payload}.{signature}"
@bp.after_request
def no_store(response: Response) -> Response:
response.headers["Cache-Control"] = "no-store"
return response
def error(status: int, code: str, headers: dict[str, str] | None = None):
return jsonify(error=code), status, headers or {}
def not_configured(variable: str):
current_app.logger.error("Bunkhouse: %s is not set", variable)
return error(503, "not_configured")
@bp.route("/api/agent-identity", methods=ALL_METHODS)
def agent_identity():
if request.method not in ("GET", "HEAD"):
return error(405, "method_not_allowed", {"Allow": "GET"})
if request.headers.get("Sec-Fetch-Site") != "same-origin":
return error(403, "forbidden")
if g.user is None:
return error(401, "unauthorized")
secret, kid = os.environ.get("AGENT_SIGNING_SECRET"), os.environ.get("AGENT_SIGNING_KID")
if not secret:
return not_configured("AGENT_SIGNING_SECRET")
if not kid:
return not_configured("AGENT_SIGNING_KID")
return jsonify(identityToken=sign_identity_token(str(g.user["id"]), secret, kid))
@bp.route("/api/agent-session", methods=ALL_METHODS)
def agent_session():
if request.method != "POST":
return error(405, "method_not_allowed", {"Allow": "POST"})
# The embed's POST carries no CSRF token; these three checks are this route's CSRF defense.
origin = request.headers.get("Origin")
if (
origin not in agent_config.allowed_origins
or request.headers.get("X-Agent-Embed") != "1"
or request.headers.get("Sec-Fetch-Site") != "same-origin"
):
return error(403, "forbidden")
if g.user is None:
return error(401, "unauthorized")
key = os.environ.get("AGENT_EMBED_SECRET_KEY")
if not key:
return not_configured("AGENT_EMBED_SECRET_KEY")
upstream = urllib.request.Request(
f"{agent_config.api_base}/v1/embed/sessions",
method="POST",
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
data=json.dumps({"publicKey": agent_config.public_key, "mode": "signed", "userId": str(g.user["id"]), "origin": origin}).encode(),
)
try:
try:
res = urllib.request.urlopen(upstream, timeout=15)
except urllib.error.HTTPError as http_error: # Non-2xx answers are forwarded unchanged too.
res = http_error
with res:
body = res.read()
except (OSError, http.client.HTTPException):
return error(502, "session_service_unavailable")
return Response(body, res.status, content_type=res.headers.get("Content-Type", "application/json"))

Register it in your application factory. The blueprint reads g.user, which the example loads from session["user_id"] in a before_request hook, the pattern of Flask’s tutorial. That hook is the seam to your authentication: set g.user to a mapping with the signed-in user’s stable "id", or None. With Flask-Login: g.user = {"id": current_user.get_id()} if current_user.is_authenticated else None.

app/__init__.py (excerpt)
@app.before_request
def load_logged_in_user() -> None:
"""Your existing authentication: g.user is the signed-in user of this request, or None."""
g.user = USERS.get(session.get("user_id"))
# Bunkhouse endpoints, which read g.user.
app.register_blueprint(agent_bp)

In the page head, load the identity hook, then the auth-headers hook (see Auth headers), then the loader, all before your application’s own scripts. window.AgentEmbedConfig must be defined before the loader runs. The hooks are external same-origin scripts, so no inline script needs a CSP exception:

app/templates/agent-embed-identity.html
{# Identity token mode (recommended): both page hooks, then the loader, before the app's scripts. #}
<script src="{{ url_for('static', filename='agent-identity.js') }}" nonce="{{ g.csp_nonce }}"></script>
<script src="{{ url_for('static', filename='agent-auth-headers.js') }}" nonce="{{ g.csp_nonce }}"></script>
<script src="{{ agent.embed_origin }}/embed.js" nonce="{{ g.csp_nonce }}"
data-public-key="{{ agent.public_key }}" data-hints-url="/agent-hints.json"></script>
app/static/agent-identity.js
// Identity token mode: the embed calls this hook whenever it starts a session for the signed-in user.
window.AgentEmbedConfig = {
...window.AgentEmbedConfig,
getIdentityToken: async () => {
const res = await fetch("/api/agent-identity", { credentials: "same-origin", cache: "no-store" });
if (!res.ok) throw new Error("Not signed in");
return (await res.json()).identityToken;
},
};
app/templates/base.html (excerpt)
{% if g.user %}<meta name="csrf-token" content="{{ session.csrf_token }}">{% endif %}
{# Page hooks, then the loader: one installation mode's complete fragment. #}
{% include "agent-embed-" ~ mode ~ ".html" %}
<!-- The application's own JavaScript comes after the loader. -->
<script src="{{ url_for('static', filename='app.js') }}" nonce="{{ g.csp_nonce }}" defer></script>

The example layout includes one of the three agent-embed-* templates, selected by a test-only ?mode= switch. Your application uses exactly one.

Instead of the identity hook, add data-session-endpoint to the loader; the auth-headers hook still loads first. Do not keep agent-identity.js on the page: when getIdentityToken is defined it takes precedence.

app/templates/agent-embed-mint.html
{# Server mint mode: no identity hook; the embed posts to the same-origin session endpoint. #}
<script src="{{ url_for('static', filename='agent-auth-headers.js') }}" nonce="{{ g.csp_nonce }}"></script>
<script src="{{ agent.embed_origin }}/embed.js" nonce="{{ g.csp_nonce }}"
data-public-key="{{ agent.public_key }}" data-hints-url="/agent-hints.json"
data-session-endpoint="{{ url_for('agent.agent_session') }}"></script>

POST /api/agent-session in app/agent.py above accepts only requests with an Origin from AGENT_ALLOWED_ORIGINS, X-Agent-Embed: 1 and Sec-Fetch-Site: same-origin (403 otherwise), authenticates the session (401), then creates the session with the mint key and returns the API’s status and body unchanged with Cache-Control: no-store. If the API is unreachable it returns 502 without details. Set AGENT_EMBED_SECRET_KEY=sk_... on the server; the identity endpoint does not need it.

Flask has no built-in CSRF protection. If you use Flask-WTF’s CSRFProtect, exempt only this view with csrf.exempt(agent_session) (imported from app.agent): the embed’s POST carries no CSRF token, and the three header checks are that route’s protection.

Anonymous sessions need no identity hook or session endpoint: only the loader, after the auth-headers hook if your API needs one. Enable anonymous access for the site in the dashboard first and set its monthly token and spend limits; usage is charged to your account’s credit and stops at a limit. Anyone who can load your page can start one, so it is not proof of identity.

app/templates/agent-embed-anonymous.html
{# Anonymous mode (enable it for the site first): no session hook or endpoint, just the loader. #}
<script src="{{ url_for('static', filename='agent-auth-headers.js') }}" nonce="{{ g.csp_nonce }}"></script>
<script src="{{ agent.embed_origin }}/embed.js" nonce="{{ g.csp_nonce }}"
data-public-key="{{ agent.public_key }}" data-hints-url="/agent-hints.json"></script>

The example signs in and out with ordinary form posts that redirect back to the same page. Every account change therefore loads a new document, and a new document starts a new embed with no session, so the previous user’s session can never carry over. The session cookie is HttpOnly and SameSite, and the example’s login view calls session.clear() before storing the new user ID and a fresh CSRF token:

app/__init__.py (excerpt)
app.config.update(
SECRET_KEY=secret,
SESSION_COOKIE_NAME="example_session",
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
# Secure everywhere except the loopback HTTP test origin.
SESSION_COOKIE_SECURE=APP_ORIGIN.startswith("https://"),
)

If your Flask app changes the signed-in user without a full page load (a fetch login, a single-page frontend), call window.AgentEmbed?.resetSession() right after the login, logout or account switch succeeds and before the new user’s requests. Render the loader once in the base template, not in templates that extend it.

The assistant calls your API with the page’s cookies; supply any extra header your API requires with getAuthHeaders. The example’s session owns a random CSRF token, rendered into a <meta> tag for signed-in users and checked as X-CSRF-Token on every write. With Flask-WTF, render csrf_token() into the tag instead; it accepts the same header:

app/static/agent-auth-headers.js
// The app's own CSRF token (rendered by the server for the signed-in session) for the assistant's calls
// to this app's API. Values never reach the model or the sandbox.
window.AgentEmbedConfig = {
...window.AgentEmbedConfig,
getAuthHeaders: () => {
const token = document.querySelector('meta[name="csrf-token"]')?.content;
return token ? { "X-CSRF-Token": token } : {};
},
};

The hook merges into window.AgentEmbedConfig, so it works alongside the identity hook; each mode’s template loads it before the loader. Its values never reach the model or the sandbox.

Send a stable, opaque user ID (the example’s fixture-alice), not a name or email address.

Add the Bunkhouse sources to your existing policy rather than replacing it. The example creates a fresh nonce per request in g.csp_nonce, puts it on its script tags and sets the header in after_request; no 'unsafe-inline' or 'unsafe-eval' is needed:

app/csp.py
# The app's existing Content-Security-Policy with the Bunkhouse sources added: the embed origin to
# script-src and frame-src, the API to connect-src. A fresh nonce per request (g.csp_nonce) goes on
# the page's script tags.
import base64
import secrets
from flask import Flask, Response, g
from .config import agent_config
def init_csp(app: Flask) -> None:
@app.before_request
def make_nonce() -> None:
g.csp_nonce = base64.b64encode(secrets.token_bytes(16)).decode()
@app.after_request
def content_security_policy(response: Response) -> Response:
nonce = g.csp_nonce
response.headers["Content-Security-Policy"] = "; ".join(
[
"default-src 'self'",
f"script-src 'self' 'nonce-{nonce}' {agent_config.embed_origin}",
f"style-src 'self' 'nonce-{nonce}'",
f"frame-src {agent_config.embed_origin}",
f"connect-src 'self' {agent_config.api_base}",
"img-src 'self' data:",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'self'",
]
)
return response

From a checkout of the Bunkhouse repository, with Docker and local Supabase running:

Terminal window
node tests/framework-integrations/run.ts flask

The run builds the example image, starts it against a fresh local site and drives the real pane in Chromium: identity, mint and anonymous sessions, endpoint guards, sign-out and account switches, discovery of the page’s startup request, a CSRF-protected write through getAuthHeaders, CSP and secret checks. In your own app, sign in and open the Assistant launcher: the first message creates a signed session.

Symptom Check
/api/agent-identity returns 401 g.user is None: the before_request hook did not find the signed-in user.
403 from either endpoint The request is cross-site or missing Sec-Fetch-Site; for mint, Origin must exactly match AGENT_ALLOWED_ORIGINS and the loader must carry data-session-endpoint. A CSRF extension must exempt only agent_session.
503 The signing secret, key ID or mint key for the mode you use is not set.
The pane reports a CSP block Add the embed origin to script-src and frame-src and the API to connect-src, and put g.csp_nonce on every script tag.
Startup requests are not discovered The page hooks and loader must come before your application’s scripts in the head.
Two launchers Render the loader once, in the base template.
A secret in page source Only AGENT_PUBLIC_KEY and origins belong in templates; keep ss_ and sk_ values in server environment variables.