Skip to content

Gin

This guide adds Bunkhouse to a server-rendered Gin 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 Gin 1.12.0, server-rendered html/template views, gorilla/securecookie 1.1.2 session cookie
Runtime Go 1.26 (go1.26.10 in the tested image), static binary on Debian bookworm-slim
Example apps/docs/integrations/gin/ 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 uses a signed, encrypted cookie 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
config.go Validates the public Bunkhouse configuration at startup
agent.go GET /api/agent-identity and POST /api/agent-session
csp.go Your Content-Security-Policy with the Bunkhouse sources added
templates/agent-embed-*.html The script tags for one installation mode
public/agent-identity.js, public/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
config.go
// 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.
package main
import (
"encoding/json"
"log"
"net/netip"
"net/url"
"os"
"regexp"
"strconv"
"strings"
)
type AgentConfig struct {
PublicKey string
AllowedOrigins []string
APIBase string
EmbedOrigin string
}
var agentConfig = loadAgentConfig()
func envOr(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
// exactOrigin accepts only an origin already in the form browsers send (what `new URL(value).origin`
// returns): http(s), lowercase ASCII host, canonical IP literals, no default or padded port, and no
// userinfo, path, query or fragment.
func exactOrigin(name, value string) string {
u, err := url.Parse(value)
if err != nil || !canonicalOrigin(u) || u.Scheme+"://"+u.Host != value {
log.Fatalf("%s must be an exact origin like https://app.example.com", name)
}
return value
}
var hostname = regexp.MustCompile(`^[a-z0-9_-]+(\.[a-z0-9_-]+)*\.?$`)
func canonicalOrigin(u *url.URL) bool {
if (u.Scheme != "https" && u.Scheme != "http") || u.User != nil || strings.HasSuffix(u.Host, ":") {
return false
}
host, port := u.Hostname(), u.Port()
labels := strings.Split(strings.TrimSuffix(host, "."), ".")
last := labels[len(labels)-1]
switch {
case strings.HasPrefix(u.Host, "["):
ip, err := netip.ParseAddr(host)
if err != nil || !ip.Is6() || ip.Is4In6() || ip.Zone() != "" || ip.String() != host {
return false
}
case !hostname.MatchString(host):
return false
case strings.HasPrefix(last, "0x") || strings.Trim(last, "0123456789") == "":
// Browsers read a host ending in a number as IPv4 and normalize it (127.1 → 127.0.0.1).
ip, err := netip.ParseAddr(host)
if err != nil || !ip.Is4() || ip.String() != host {
return false
}
}
if port == "" {
return true
}
n, err := strconv.Atoi(port)
defaultPort := (u.Scheme == "https" && n == 443) || (u.Scheme == "http" && n == 80)
return err == nil && n <= 65535 && strconv.Itoa(n) == port && !defaultPort
}
func loadAgentConfig() AgentConfig {
publicKey := os.Getenv("AGENT_PUBLIC_KEY")
if !strings.HasPrefix(publicKey, "pk_") {
log.Fatal("AGENT_PUBLIC_KEY must be the site's public key (pk_...)")
}
var origins []string
if err := json.Unmarshal([]byte(envOr("AGENT_ALLOWED_ORIGINS", "[]")), &origins); err != nil || len(origins) == 0 {
log.Fatal(`AGENT_ALLOWED_ORIGINS must be a JSON array such as ["https://app.example.com"]`)
}
for _, origin := range origins {
exactOrigin("AGENT_ALLOWED_ORIGINS", origin)
}
return AgentConfig{
PublicKey: publicKey,
AllowedOrigins: origins,
APIBase: exactOrigin("AGENT_API_BASE", envOr("AGENT_API_BASE", "https://api.bunkhouse.ai")),
EmbedOrigin: exactOrigin("AGENT_EMBED_ORIGIN", envOr("AGENT_EMBED_ORIGIN", "https://embed.bunkhouse.ai")),
}
}

RegisterAgentRoutes signs a ten-minute HS256 token with the standard library’s crypto/hmac for the user your session already authenticated. It rejects other methods (405 with an Allow header), requests whose Sec-Fetch-Site is not same-origin (403) and signed-out users (401, never a login redirect), and 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.

Gin answers a wrong method with 404 by default, so RegisterAgentRoutes turns on HandleMethodNotAllowed for the whole engine: every route in your app then answers wrong methods with 405 and an Allow header. It also registers the engine’s single NoMethod handler. If your app sets its own NoMethod handler, that handler must keep Cache-Control: no-store on its response, because it now also answers wrong-method requests to the Bunkhouse endpoints.

agent.go
// 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.
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"io"
"log"
"net/http"
"os"
"slices"
"time"
"github.com/gin-gonic/gin"
)
// CurrentUser is your existing authentication: the signed-in user's stable ID for this request, or "".
type CurrentUser func(c *gin.Context) string
func base64url(value any) string {
data, _ := json.Marshal(value)
return base64.RawURLEncoding.EncodeToString(data)
}
// SignIdentityToken returns an HS256 identity token: kid header, sub = stable opaque user ID,
// aud = public key, 10 minutes.
func SignIdentityToken(userID, secret, kid string) string {
iat := time.Now().Unix()
header := base64url(struct {
Alg string `json:"alg"`
Typ string `json:"typ"`
Kid string `json:"kid"`
}{"HS256", "JWT", kid})
payload := base64url(struct {
Sub string `json:"sub"`
Aud string `json:"aud"`
Iat int64 `json:"iat"`
Exp int64 `json:"exp"`
}{userID, agentConfig.PublicKey, iat, iat + 600})
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(header + "." + payload))
return header + "." + payload + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func notConfigured(c *gin.Context, variable string) {
log.Printf("Bunkhouse: %s is not set", variable)
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "not_configured"})
}
var sessionClient = &http.Client{Timeout: 15 * time.Second}
func RegisterAgentRoutes(r *gin.Engine, currentUser CurrentUser) {
// Wrong methods: Gin answers 405 with an Allow header listing the route's methods (its default is 404).
r.HandleMethodNotAllowed = true
r.NoMethod(func(c *gin.Context) {
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "method_not_allowed"})
})
r.GET("/api/agent-identity", func(c *gin.Context) {
c.Header("Cache-Control", "no-store")
if c.GetHeader("Sec-Fetch-Site") != "same-origin" {
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
return
}
userID := currentUser(c)
if userID == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
secret, kid := os.Getenv("AGENT_SIGNING_SECRET"), os.Getenv("AGENT_SIGNING_KID")
if secret == "" {
notConfigured(c, "AGENT_SIGNING_SECRET")
return
}
if kid == "" {
notConfigured(c, "AGENT_SIGNING_KID")
return
}
c.JSON(http.StatusOK, gin.H{"identityToken": SignIdentityToken(userID, secret, kid)})
})
r.POST("/api/agent-session", func(c *gin.Context) {
c.Header("Cache-Control", "no-store")
// The embed's POST carries no CSRF token; these three checks are this route's CSRF defense.
origin := c.GetHeader("Origin")
if !slices.Contains(agentConfig.AllowedOrigins, origin) || c.GetHeader("X-Agent-Embed") != "1" || c.GetHeader("Sec-Fetch-Site") != "same-origin" {
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
return
}
userID := currentUser(c)
if userID == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
key := os.Getenv("AGENT_EMBED_SECRET_KEY")
if key == "" {
notConfigured(c, "AGENT_EMBED_SECRET_KEY")
return
}
status, contentType, upstream, err := createSession(c.Request.Context(), key, userID, origin)
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{"error": "session_service_unavailable"})
return
}
c.Data(status, contentType, upstream)
})
}
// createSession asks the Bunkhouse API for a signed session; the caller forwards its status and body.
func createSession(ctx context.Context, key, userID, origin string) (int, string, []byte, error) {
body, _ := json.Marshal(map[string]string{"publicKey": agentConfig.PublicKey, "mode": "signed", "userId": userID, "origin": origin})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, agentConfig.APIBase+"/v1/embed/sessions", bytes.NewReader(body))
if err != nil {
return 0, "", nil, err
}
req.Header.Set("Authorization", "Bearer "+key)
req.Header.Set("Content-Type", "application/json")
res, err := sessionClient.Do(req)
if err != nil {
return 0, "", nil, err
}
defer res.Body.Close()
upstream, err := io.ReadAll(res.Body)
contentType := res.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/json"
}
return res.StatusCode, contentType, upstream, err
}

Register the routes after your session middleware. currentUser is the seam to your authentication: return the signed-in user’s stable ID from the Gin context your middleware populated, or "".

main.go (excerpt)
// The signed-in user's stable ID for this request (your existing authentication), or "".
currentUser := func(c *gin.Context) string {
s, _ := sessionOf(c)
return s.UserID
}
// Bunkhouse endpoints, registered after the session middleware so they see the signed-in user.
RegisterAgentRoutes(r, currentUser)

In the page head, load the page hooks first (the identity hook, then the auth-headers hook described below), then the loader, all before your application’s own scripts. The hooks are external same-origin scripts, so no inline script needs a CSP exception:

templates/agent-embed-identity.html
{{/* Identity token mode (recommended): the page hooks first, then the loader, before the app's scripts. */}}
<script src="/assets/agent-identity.js" nonce="{{.Nonce}}"></script>
<script src="/assets/agent-auth-headers.js" nonce="{{.Nonce}}"></script>
<script src="{{.Agent.EmbedOrigin}}/embed.js" nonce="{{.Nonce}}"
data-public-key="{{.Agent.PublicKey}}" data-hints-url="/agent-hints.json"></script>
public/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;
},
};
templates/layout.html (excerpt)
{{if .CSRFToken}}<meta name="csrf-token" content="{{.CSRFToken}}" />{{end}}
{{if eq .Mode "mint"}}{{template "agent-embed-mint.html" .}}
{{else if eq .Mode "anonymous"}}{{template "agent-embed-anonymous.html" .}}
{{else}}{{template "agent-embed-identity.html" .}}{{end}}
{{/* The application's own JavaScript comes after the loader. */}}
<script src="/assets/app.js" nonce="{{.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. Do not keep agent-identity.js on the page: when getIdentityToken is defined it takes precedence.

templates/agent-embed-mint.html
{{/* Server mint mode: no identity hook; the embed posts to the same-origin session endpoint. */}}
<script src="/assets/agent-auth-headers.js" nonce="{{.Nonce}}"></script>
<script src="{{.Agent.EmbedOrigin}}/embed.js" nonce="{{.Nonce}}"
data-public-key="{{.Agent.PublicKey}}" data-hints-url="/agent-hints.json"
data-session-endpoint="/api/agent-session"></script>

POST /api/agent-session in agent.go 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.

Gin has no built-in CSRF middleware. If you use one (such as gorilla/csrf), exempt only /api/agent-session: the embed’s POST carries no CSRF token, and the three header checks are that route’s protection.

Anonymous sessions need only the loader; the example keeps its auth-headers hook in front of it, without the identity hook. 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.

templates/agent-embed-anonymous.html
{{/* Anonymous mode (enable it for the site first): no identity hook, the auth-headers hook, then the loader. */}}
<script src="/assets/agent-auth-headers.js" nonce="{{.Nonce}}"></script>
<script src="{{.Agent.EmbedOrigin}}/embed.js" nonce="{{.Nonce}}"
data-public-key="{{.Agent.PublicKey}}" 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 is a gorilla/securecookie cookie (HttpOnly, SameSite=Lax, Secure outside loopback HTTP), replaced with a new CSRF token on every login; a middleware verifies it and puts it on the Gin context:

main.go (excerpt)
// A signed and encrypted cookie session. The middleware puts the verified session on the Gin
// context; a missing, expired or modified cookie is simply no session.
codecs := securecookie.New(derivedKey(secret, "cookie-hash"), derivedKey(secret, "cookie-block"))
codecs.SetSerializer(securecookie.JSONEncoder{})
codecs.MaxAge(8 * 60 * 60)
r.Use(func(c *gin.Context) {
var s Session
if raw, err := c.Cookie(sessionCookie); err == nil && codecs.Decode(sessionCookie, raw, &s) == nil {
c.Set("session", s)
}
c.Next()
})
// Secure everywhere except the loopback HTTP test origin.
setSessionCookie := func(c *gin.Context, value string, maxAge int) {
http.SetCookie(c.Writer, &http.Cookie{Name: sessionCookie, Value: value, Path: "/", MaxAge: maxAge, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: strings.HasPrefix(appOrigin, "https://")})
}

If your Gin 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 layout, not in per-page templates.

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:

public/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 } : {};
},
};

Every installation template loads this hook before the loader. It merges into window.AgentEmbedConfig, so it works with the identity hook in either order. 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’s middleware sets a fresh nonce per response, and the templates put it on their script tags; no 'unsafe-inline' or 'unsafe-eval' is needed:

csp.go
// 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 response (c.GetString("cspNonce"))
// goes on the page's script tags.
package main
import (
"crypto/rand"
"strings"
"github.com/gin-gonic/gin"
)
func ContentSecurityPolicy(c *gin.Context) {
nonce := rand.Text() // 128 random bits
c.Set("cspNonce", nonce)
c.Header("Content-Security-Policy", strings.Join([]string{
"default-src 'self'",
"script-src 'self' 'nonce-" + nonce + "' " + agentConfig.EmbedOrigin,
"style-src 'self' 'nonce-" + nonce + "'",
"frame-src " + agentConfig.EmbedOrigin,
"connect-src 'self' " + agentConfig.APIBase,
"img-src 'self' data:",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'self'",
}, "; "))
c.Next()
}

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

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

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 The routes are registered before your session middleware runs, or currentUser does not find the user on the Gin context.
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 middleware must exempt only /api/agent-session.
404 instead of 405 for a wrong method HandleMethodNotAllowed was reset after RegisterAgentRoutes. A custom NoMethod handler must still set Cache-Control: no-store.
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 the response’s nonce on every script tag.
Startup requests are not discovered The loader must come before your application’s scripts in the head.
Two launchers Render the loader once, in the layout.
A secret in page source Only AGENT_PUBLIC_KEY and origins belong in templates; keep ss_ and sk_ values in server environment variables.