Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
docs: HTTPS-via-proxy guide + compose templates + sharpened startup warning
AkitaOnRails1c8bb1aa1821
diff --git a/README.md b/README.mdindex ea9f0bf6..9fadf264 100644--- a/README.md+++ b/README.md@@ -288,6 +288,19 @@ Bearer auth protects `/mcp`, `/hook`, `/handoff`, `/admin/*`, andas the password. Non-loopback binds should also set`AI_MEMORY_ALLOWED_HOSTS` to guard against DNS rebinding.+**Want HTTPS?** ai-memory deliberately does not terminate TLS itself —+the right answer is a battle-tested reverse proxy in front of it.+[`docs/https-via-proxy.md`](docs/https-via-proxy.md) is the deployment+guide, with copy-paste docker compose templates in+[`docker/compose.tls.caddy.yml`](docker/compose.tls.caddy.yml) (Caddy+with Let's Encrypt or internal CA) and+[`docker/compose.tls.cloudflared.yml`](docker/compose.tls.cloudflared.yml)+(Cloudflare Tunnel — no open ports). Both are recommended once you+turn on multi-user or bind beyond loopback. The Quick Start happy+path of single-user on loopback doesn't need TLS — that case is+called out explicitly in the guide so you don't add ceremony where+it doesn't earn its keep.+**Multi-user attribution (v0.8, optional).** When more than one humanshares a server, ai-memory can attribute each write to a named user.The bearer token continues to authenticate at the wire level; users@@ -455,8 +468,9 @@ diagram, crate breakdown, schema notes, and invariants.| [`docs/marker-file.md`](docs/marker-file.md) | `.ai-memory.toml` workspace/project routing for multi-client trees, mono-repos, worktrees, and work/personal separation. || [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, native source builds, and current hook/MCP harness caveats. || [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP and lifecycle notes (Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, OpenClaw, OMP). |-| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, TLS via cloudflared. |+| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, pointers to the TLS guide. || [`docs/users.md`](docs/users.md) | **Multi-user attribution (v0.8).** Four-rung auth ladder, `ai-memory user add/list/expire/revive/rotate-token` walkthrough, backward-compat migration for pre-v0.8 installs, token storage rationale. |+| [`docs/https-via-proxy.md`](docs/https-via-proxy.md) | **HTTPS via a reverse proxy.** When you need TLS (multi-user, non-loopback) and when you don't (loopback / stdio). Copy-paste docker compose templates for Caddy + Let's Encrypt, Caddy + internal CA (LAN-only), Cloudflare Tunnel (no open ports), and external cert files; plus native-Caddy + nginx recipes. The "thinking you're secure when you're not" failure modes explicitly called out. || [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before running purge / rename / backup / restore / reset.** Safety matrix for the state-touching commands, per-project disk layout (how isolation actually works), and operator workflows for "fresh start", "snapshot before risky op", "drop one project". || [`docs/llm-provider-comparison.md`](docs/llm-provider-comparison.md) | Empirical notes behind the recommended LLM defaults. || [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Operational summary: data flow, crate layout, cross-cutting invariants, schema. |diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex df3c8cf4..82d5211d 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -277,6 +277,22 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {Generate a token with `ai-memory generate-auth-token` and set \AI_MEMORY_AUTH_TOKEN in the server's environment.");+ } else if auth_enabled && !bind.starts_with("127.") {+ // Auth IS configured but the server is reachable from+ // the network on plain HTTP. The bearer token (and+ // multi-user per-user tokens from `ai-memory user+ // add`) ride cleartext — sniffable on the LAN. Advise+ // the operator to front with a TLS proxy. One-shot+ // log at startup, not refusal to serve (operators may+ // be testing, behind their own proxy already, etc.).+ tracing::warn!(+ %bind,+ "AI_MEMORY_AUTH_TOKEN is set but the server is bound to a \+ non-loopback address on plain HTTP — bearer tokens travel \+ cleartext on the network. Front ai-memory with a TLS-terminating \+ reverse proxy (Caddy, Cloudflare Tunnel, nginx). See \+ docs/https-via-proxy.md for copy-paste templates."+ );}axum::serve(listener, router).with_graceful_shutdown(async move {diff --git a/docker/compose.tls.caddy.yml b/docker/compose.tls.caddy.ymlnew file mode 100644index 00000000..9a743dda--- /dev/null+++ b/docker/compose.tls.caddy.yml@@ -0,0 +1,127 @@+# docker compose template — ai-memory + Caddy TLS-terminating reverse proxy.+#+# Three usable variants, all in this one file. Pick one and either:+# - Copy this file, prune the variants you don't want, then+# `docker compose -f compose.tls.caddy.yml up -d`, or+# - Use it verbatim and switch via the `Caddyfile` you put next to+# it. The compose service definitions are the same across variants.+#+# Adjacent files this compose expects:+# ./Caddyfile — your reverse-proxy config; see variants below+# ./.env.production — AI_MEMORY_AUTH_TOKEN + AI_MEMORY_ALLOWED_HOSTS ++# your LLM provider creds. NOT committed.+#+# Walkthrough + variant explanations + client-side install:+# docs/https-via-proxy.md++name: ai-memory-tls++services:+ ai-memory:+ image: akitaonrails/ai-memory:latest+ container_name: ai-memory+ restart: unless-stopped+ # No host port. Caddy reaches ai-memory over the internal docker+ # network; the only inbound surface is Caddy's 80/443 below.+ expose:+ - "49374"+ volumes:+ - ai-memory-data:/data+ env_file:+ - .env.production+ environment:+ - RUST_LOG=ai_memory=info,ai_memory_store=info,ai_memory_wiki=info,ai_memory_mcp=info,tracing_appender=warn+ healthcheck:+ test: ["CMD", "/usr/local/bin/ai-memory", "status"]+ interval: 30s+ timeout: 5s+ retries: 3+ start_period: 5s++ caddy:+ image: caddy:2-alpine+ container_name: ai-memory-caddy+ restart: unless-stopped+ depends_on:+ - ai-memory+ ports:+ # 80 is needed for Let's Encrypt's HTTP-01 challenge during issuance+ # and renewal. Drop it when using internal-CA mode (Variant B) since+ # there's no ACME to solve.+ - "80:80"+ - "443:443"+ volumes:+ - ./Caddyfile:/etc/caddy/Caddyfile:ro+ # Persist Caddy state across recreates. caddy-data holds the+ # account key and issued certs — back this up; losing it forces a+ # re-issuance and (in LE's case) brief unavailability.+ - caddy-data:/data+ - caddy-config:/config+ # Only mount this for Variant C (external certs):+ # - /your/cert/path:/etc/caddy/certs:ro++volumes:+ ai-memory-data:+ name: ai-memory-data+ caddy-data:+ caddy-config:+++# ──────────────────────────────────────────────────────────────────────+# Variant A — Public domain + Let's Encrypt+# ──────────────────────────────────────────────────────────────────────+#+# Put this in ./Caddyfile next to this compose file:+#+# memory.example.com {+# reverse_proxy ai-memory:49374+# }+#+# Requires:+# - A DNS A or AAAA record for memory.example.com → your public IP+# - Port 80 + 443 reachable from the internet (for ACME challenges + serving)+#+# Caddy issues + auto-renews from Let's Encrypt with no operator+# action after first start. Browser-trusted by every client out of+# the box.+#+# ──────────────────────────────────────────────────────────────────────+# Variant B — LAN-only + Caddy's internal CA+# ──────────────────────────────────────────────────────────────────────+#+# Put this in ./Caddyfile:+#+# {+# local_certs+# }+#+# homelab.local, 192.168.1.50 {+# reverse_proxy ai-memory:49374+# }+#+# List every hostname + IP a client will use in the site address.+# Caddy puts them all in the cert's SAN.+#+# Requires:+# - One-time install of Caddy's root cert into each client OS trust+# store. Pull it with:+# docker compose exec caddy cat /data/caddy/pki/authorities/local/root.crt > caddy-root.crt+# Then follow the per-OS install in docs/https-via-proxy.md.+#+# Skipping that step gives you security theatre, not security. See+# the doc for why.+#+# ──────────────────────────────────────────────────────────────────────+# Variant C — External cert files+# ──────────────────────────────────────────────────────────────────────+#+# Put this in ./Caddyfile:+#+# memory.example.com {+# tls /etc/caddy/certs/memory.crt /etc/caddy/certs/memory.key+# reverse_proxy ai-memory:49374+# }+#+# Uncomment the cert volume mount in the caddy service above.+# Caddy hot-reloads certs on file change — no compose restart needed+# at renewal time.diff --git a/docker/compose.tls.cloudflared.yml b/docker/compose.tls.cloudflared.ymlnew file mode 100644index 00000000..bf657f66--- /dev/null+++ b/docker/compose.tls.cloudflared.yml@@ -0,0 +1,106 @@+# docker compose template — ai-memory + Cloudflare Tunnel.+#+# Outbound-only tunnel from the homelab to Cloudflare's edge. TLS is+# terminated at the edge with a Cloudflare cert (universally trusted+# everywhere). No ports exposed on the host, no public IP needed,+# no DNS records to set up (Cloudflare manages the CNAME).+#+# Pairs especially well with the multi-user homelab case from+# docs/users.md — every per-user token rides encrypted from each+# client through Cloudflare to the tunnel.+#+# Prerequisites (one-time, in the Cloudflare dashboard):+# 1. Have a domain on Cloudflare (DNS hosted there; registrar+# doesn't matter).+# 2. Zero Trust → Networks → Tunnels → Create a tunnel → name it+# `ai-memory-homelab` → save.+# 3. Copy the token Cloudflare gives you into .env as+# CLOUDFLARE_TUNNEL_TOKEN.+# 4. In the tunnel's "Public hostnames" tab: add `memory.example.com`+# pointing at service `http://ai-memory:49374`.+# 5. (Optional, recommended) Wrap that hostname in a Cloudflare+# Access application for SSO on top of ai-memory's bearer auth.+#+# Adjacent files this compose expects:+# ./.env.production — AI_MEMORY_AUTH_TOKEN ++# AI_MEMORY_ALLOWED_HOSTS ++# CLOUDFLARE_TUNNEL_TOKEN. NOT committed.+#+# Walkthrough + client-side install:+# docs/https-via-proxy.md++name: ai-memory-cloudflared++services:+ ai-memory:+ image: akitaonrails/ai-memory:latest+ container_name: ai-memory+ restart: unless-stopped+ # No host port. The tunnel reaches ai-memory over the internal+ # docker network — nothing inbound from the public internet.+ expose:+ - "49374"+ volumes:+ - ai-memory-data:/data+ env_file:+ - .env.production+ environment:+ - RUST_LOG=ai_memory=info,ai_memory_store=info,ai_memory_wiki=info,ai_memory_mcp=info,tracing_appender=warn+ healthcheck:+ test: ["CMD", "/usr/local/bin/ai-memory", "status"]+ interval: 30s+ timeout: 5s+ retries: 3+ start_period: 5s++ cloudflared:+ image: cloudflare/cloudflared:latest+ container_name: ai-memory-tunnel+ restart: unless-stopped+ depends_on:+ - ai-memory+ command: tunnel --no-autoupdate run+ # `cloudflared` exits with code 1 on token rejection, which the+ # `restart: unless-stopped` policy will loop on. Watch the logs+ # the first time you start it — `docker compose logs -f cloudflared`+ # — to confirm registration succeeded.+ environment:+ - TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN}++volumes:+ ai-memory-data:+ name: ai-memory-data+++# ──────────────────────────────────────────────────────────────────────+# .env.production minimum content (DO NOT COMMIT THIS FILE):+# ──────────────────────────────────────────────────────────────────────+#+# AI_MEMORY_AUTH_TOKEN=<long-random-token-from-`ai-memory generate-auth-token`>+# AI_MEMORY_ALLOWED_HOSTS=memory.example.com,localhost,127.0.0.1+# AI_MEMORY_BIND=0.0.0.0:49374+#+# CLOUDFLARE_TUNNEL_TOKEN=eyJ...<long-base64-from-the-cf-dashboard>...+#+# # Optional LLM provider — see docker-compose.yml for the catalogue.+# # AI_MEMORY_LLM_PROVIDER=anthropic+# # ANTHROPIC_API_KEY=sk-ant-...+#+# `AI_MEMORY_ALLOWED_HOSTS` MUST include the public hostname that+# Cloudflare forwards under, or ai-memory's DNS-rebinding guard will+# reject the tunneled requests.+#+# ──────────────────────────────────────────────────────────────────────+# Client config after the tunnel is up+# ──────────────────────────────────────────────────────────────────────+#+# ai-memory install-mcp --client claude-code --apply \+# --server-url "https://memory.example.com/mcp" \+# --auth-token "$AI_MEMORY_AUTH_TOKEN"+#+# ai-memory install-hooks --agent claude-code --apply \+# --server-url "https://memory.example.com" \+# --auth-token "$AI_MEMORY_AUTH_TOKEN"+#+# (Substitute codex / cursor / gemini-cli / antigravity / opencode /+# omp / openclaw — same shape, see docs/install.md for the catalogue.)diff --git a/docs/deploy.md b/docs/deploy.mdindex 1e978239..c18c9643 100644--- a/docs/deploy.md+++ b/docs/deploy.md@@ -105,17 +105,24 @@ Desktop, Gemini CLI, OpenClaw, OMP/Pi, Antigravity CLI). The agent CLI sends anmiddleware validates with a constant-time comparison.**Encrypted transport.** Plain HTTP on the LAN means anyone with a-packet capture on the network can read the bearer token and the wiki-content in transit. Two pragmatic ways to add TLS:--| Option | When it fits |-|---|---|-| **Front with cloudflared** (your existing homelab tunnel) | You want to access ai-memory from outside the LAN too. cloudflared terminates TLS at Cloudflare's edge and tunnels to the container over HTTP. The bearer token still applies; Cloudflare provides the encryption + DDoS shield. Configure a new `--hostname ai-memory.your-domain.tld --url http://localhost:49374` route on the existing cloudflared instance. |-| **Caddy reverse proxy** in a sibling container | You want LAN-only TLS without public DNS. Caddy auto-issues a self-signed cert with a tofu prompt the first time each client connects. Mount your homelab's CA cert into the container running each MCP client. |--For most homelab use cases the bearer token alone over plain HTTP on-a trusted LAN is acceptable. The token is what stops the LAN-neighbour; TLS is what stops a packet-capture-with-a-laptop-on-the-WiFi.+packet capture can read the bearer token (and per-user tokens once+multi-user mode is on) in transit. Add a TLS-terminating reverse+proxy in front of ai-memory — Caddy with Let's Encrypt, Caddy with+its internal CA, Cloudflare Tunnel, nginx, or external cert files —+when you bind beyond loopback or turn on multi-user.++**See [`docs/https-via-proxy.md`](https-via-proxy.md)** for the full+deployment guide, including:++- When to add TLS and when to skip it (the loopback + stdio cases honestly don't need it).+- Copy-paste docker compose templates in [`docker/compose.tls.caddy.yml`](../docker/compose.tls.caddy.yml) and [`docker/compose.tls.cloudflared.yml`](../docker/compose.tls.cloudflared.yml).+- Per-OS trust-store install for the internal-CA path (the load-bearing manual step).+- The explicit "what can go wrong" sections so you don't ship security theatre by accident.++For the single-user-on-loopback Quick Start, the bearer token alone+remains acceptable — the token is what stops the LAN neighbour, and+loopback is what stops the packet capture. TLS earns its keep once+the deployment shape stops being "single user, single machine."## Routine deploysdiff --git a/docs/https-via-proxy.md b/docs/https-via-proxy.mdnew file mode 100644index 00000000..0a7c5d38--- /dev/null+++ b/docs/https-via-proxy.md@@ -0,0 +1,395 @@+# HTTPS via a reverse proxy++> ai-memory does **not** terminate TLS itself, by design. This page is+> the operator's guide to fronting it with a mature TLS terminator+> (Caddy, Cloudflare Tunnel, nginx) so tokens and `/web` cookies+> travel encrypted between clients and the server. Default install+> stays plain HTTP on loopback — no change for existing users on+> upgrade.++## When you don't need this++Skip TLS entirely if you're in one of these shapes — the security+budget is better spent elsewhere:++- **Single-user, stdio MCP transport.** `claude mcp add ai-memory -- ai-memory serve --transport stdio` never touches the network. No TLS to worry about.+- **Loopback-only HTTP server**, single user, no `/web` access from another machine. `127.0.0.1:49374` is unreachable from outside the host; TLS protects nothing here that the kernel's loopback boundary doesn't already.+- **Local dev / one-off experiments.** Bring TLS in when the deployment shape calls for it; not before.++The single-user happy path documented in the README's Quick Start is+this case. Most ai-memory installs never need a proxy.++## When you do need this++Add a TLS-terminating proxy in front of ai-memory when any of these+apply:++- **Multi-user mode is on** (`[auth].token_pepper` set, users created via `ai-memory user add`). Per-user tokens travel between clients and the server — sniffable over plain HTTP on the LAN. See [`docs/users.md`](users.md).+- **The server is bound beyond loopback** (`AI_MEMORY_BIND=0.0.0.0:49374` or a LAN-routable IP). Anyone on the network segment sees plaintext token traffic and `/web` cookies.+- **You access `/web` from a different machine** than the one running ai-memory. The browser session cookie set after Basic auth lives in the clear over HTTP.+- **You're exposing ai-memory beyond the LAN.** Cloudflare Tunnel or a public-domain Caddy with Let's Encrypt are the two patterns most homelab operators land on.++ai-memory will warn at startup when it binds to a non-loopback address+without auth, and again (one-shot) on the first request that didn't+arrive via `X-Forwarded-Proto: https`. The warnings are advisory —+the server doesn't refuse to start over plain HTTP. The decision to+add TLS is yours; this page is the recipes.++## Pick a path++| Path | Best for | What's needed externally |+|---|---|---|+| **Caddy + public domain + Let's Encrypt** | Operators with a domain name + port 80/443 reachable from the internet (most homelabs behind a forwarding router). | DNS A/AAAA record pointing at your IP. |+| **Caddy + internal CA (LAN-only)** | LAN-only multi-user, no public exposure. Each client machine has to trust Caddy's root cert once. | One-time root cert install per client. |+| **Cloudflare Tunnel** | "I don't want to open ports on my router" — outbound-only tunnel, TLS terminated at Cloudflare's edge. | A Cloudflare account (free tier works) + a domain on Cloudflare. |+| **External cert files (Caddy or nginx)** | You already have a corporate or homelab CA issuing certs to your services. | The cert/key files, however your environment produces them. |+| **nginx** | You already run nginx for other services and want one config language. | Same as Caddy: a domain or files. |++The compose templates in `docker/` are ready to copy:++- [`docker/compose.tls.caddy.yml`](../docker/compose.tls.caddy.yml) — Caddy front, both LE and internal-CA variants documented inline.+- [`docker/compose.tls.cloudflared.yml`](../docker/compose.tls.cloudflared.yml) — Cloudflare Tunnel sidecar, zero open ports.++The sections below walk through each.++---++## Path 1 — Caddy + public domain + Let's Encrypt++Cleanest path when you have a domain and port 80/443 reachable. Caddy+auto-issues + auto-renews from Let's Encrypt with no operator+involvement after first start.++### Compose template++Copy `docker/compose.tls.caddy.yml` to your deploy directory. The+relevant block is:++```yaml+services:+ ai-memory:+ image: akitaonrails/ai-memory:latest+ container_name: ai-memory+ restart: unless-stopped+ expose:+ - "49374" # internal only — Caddy reaches it over the docker network+ volumes:+ - ai-memory-data:/data+ env_file:+ - .env.production # AI_MEMORY_AUTH_TOKEN + AI_MEMORY_ALLOWED_HOSTS + your LLM provider creds++ caddy:+ image: caddy:2-alpine+ container_name: ai-memory-caddy+ restart: unless-stopped+ ports:+ - "80:80" # for Let's Encrypt HTTP-01 challenges+ - "443:443" # the only port your clients touch+ volumes:+ - ./Caddyfile:/etc/caddy/Caddyfile:ro+ - caddy-data:/data+ - caddy-config:/config++volumes:+ ai-memory-data:+ name: ai-memory-data+ caddy-data: # cert + ACME account key live here. Back this up.+ caddy-config:+```++### Caddyfile++A complete one, three lines that actually matter:++```caddyfile+memory.example.com {+ reverse_proxy ai-memory:49374+}+```++Caddy will:++1. Solve the HTTP-01 ACME challenge on first request to that hostname.+2. Issue a Let's Encrypt cert.+3. Renew automatically 30 days before expiry.+4. Forward `Authorization: Bearer ...` headers (and your auth flow) untouched.+5. Set `X-Forwarded-Proto: https` and `X-Forwarded-For: <client-ip>` automatically.++### ai-memory `.env.production` adjustments++```bash+AI_MEMORY_AUTH_TOKEN=...long-random-token-from-generate-auth-token...+AI_MEMORY_ALLOWED_HOSTS=memory.example.com,localhost,127.0.0.1+AI_MEMORY_BIND=0.0.0.0:49374+```++The `AI_MEMORY_ALLOWED_HOSTS` must include the public hostname or+ai-memory's DNS-rebinding guard will refuse Caddy's forwarded+requests.++### MCP client config (Claude Code shown — others follow the same shape)++```bash+ai-memory install-mcp --client claude-code --apply \+ --server-url "https://memory.example.com/mcp" --auth-token "$AI_MEMORY_AUTH_TOKEN"+ai-memory install-hooks --agent claude-code --apply \+ --server-url "https://memory.example.com" --auth-token "$AI_MEMORY_AUTH_TOKEN"+```++`https://` flips on, the token rides in `Authorization: Bearer`, and+Caddy's cert is browser/curl/MCP-client trusted everywhere because+Let's Encrypt is in every system trust store.++### What can go wrong++- **Port 80 not reachable from the internet** → ACME fails. Symptom: Caddy logs `Get "https://acme-v02.api.letsencrypt.org/...": ...` errors. Fix: forward 80 and 443 from your router to the Caddy host, OR switch to Cloudflare Tunnel (Path 3) which doesn't need open ports.+- **DNS not propagated yet** → first cert issuance fails with `unauthorized: ...DNS name does not have any address`. Fix: wait, or check the A record points at your public IP.+- **Cert renews silently fail months later** → Caddy logs the failure but you don't read Caddy logs. Fix: subscribe to `journalctl -u docker-compose@... | grep -i 'renew\|error'` or front Caddy with healthchecks.++---++## Path 2 — Caddy with internal CA (LAN-only)++You don't have a public domain or you don't want to expose anything+to the internet. Caddy's internal CA generates a per-server root cert+the operator installs **once** into each client machine's OS trust+store. Same wire shape as Path 1, no internet dependency, no port+forward.++### Caddyfile++```caddyfile+{+ local_certs # tells Caddy to use the internal CA instead of LE+}++homelab.local, 192.168.1.50 {+ reverse_proxy ai-memory:49374+}+```++List every name + IP clients will use (browser, MCP client, curl)+in the site address. Caddy puts all of them in the cert's SAN.++### The trust-install step (the load-bearing one)++Caddy's root cert lives at `<caddy-data>/caddy/pki/authorities/local/root.crt`+inside the volume. Extract it once:++```bash+docker compose exec caddy cat /data/caddy/pki/authorities/local/root.crt > caddy-root.crt+```++Then install it into each client OS's trust store:++| OS | Command |+|---|---|+| macOS | `sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain caddy-root.crt` |+| Linux (Debian/Ubuntu) | `sudo cp caddy-root.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates` |+| Linux (Arch/openSUSE) | `sudo trust anchor --store caddy-root.crt` |+| Windows | `certutil -addstore -f "Root" caddy-root.crt` (Administrator PowerShell) |+| iOS / Android | Email the file to the device, open it, install as a profile in Settings → General → VPN & Device Management. Then **also** explicitly trust it under Settings → General → About → Certificate Trust Settings. |++**The warning that has to be loud**: if you skip the trust-install+step on a client, that client will either refuse TLS connections+(MCP clients, curl) or train the operator to click through warnings+(browsers). In the latter case **you have neither HTTP's transparency+nor HTTPS's protection** — you have a security theatre cert that+makes everyone less safe. Install the root cert on every client+machine you connect from, or use Path 1 / Path 3 instead.++### Same `.env` + client config shape as Path 1++Substitute `https://homelab.local` (or whichever SAN you set) for the+public domain. Everything else is identical.++---++## Path 3 — Cloudflare Tunnel++Cloudflare's `cloudflared` daemon establishes an outbound-only tunnel+to Cloudflare's edge. **No ports open on your router**, no public IP+needed, TLS terminated at the Cloudflare edge with their cert. Pairs+particularly well with the homelab multi-user case because the trust+story is "Cloudflare is the CA" — universally trusted, no per-client+install dance.++### One-time Cloudflare setup++1. Have a domain on Cloudflare (the registrar can be elsewhere; the DNS must be on Cloudflare).+2. In the Cloudflare dashboard, go to **Zero Trust → Networks → Tunnels** → **Create a tunnel** → name it `ai-memory-homelab` (or whatever) → save.+3. Cloudflare gives you a long token string. Save it for the compose file.+4. Add a public hostname to the tunnel: `memory.example.com` → service `http://ai-memory:49374`. Save.+5. (Optional but recommended) Wrap the hostname in a **Cloudflare Access** application — Cloudflare's zero-trust SSO sits in front of the tunnel and you get human auth via Google/GitHub/etc. **on top of** ai-memory's bearer token.++### Compose template++Copy `docker/compose.tls.cloudflared.yml`. The relevant block:++```yaml+services:+ ai-memory:+ image: akitaonrails/ai-memory:latest+ container_name: ai-memory+ restart: unless-stopped+ expose:+ - "49374" # tunnel reaches it over the docker network — no host port+ volumes:+ - ai-memory-data:/data+ env_file:+ - .env.production++ cloudflared:+ image: cloudflare/cloudflared:latest+ container_name: ai-memory-tunnel+ restart: unless-stopped+ command: tunnel --no-autoupdate run+ environment:+ - TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN}++volumes:+ ai-memory-data:+ name: ai-memory-data+```++`CLOUDFLARE_TUNNEL_TOKEN` goes in your `.env` (or compose env). No+ports exposed on the host. No DNS configuration beyond the dashboard+step above (Cloudflare manages the CNAME automatically).++### ai-memory `.env.production` adjustments++```bash+AI_MEMORY_AUTH_TOKEN=...long-random-token...+AI_MEMORY_ALLOWED_HOSTS=memory.example.com,localhost,127.0.0.1+AI_MEMORY_BIND=0.0.0.0:49374+CLOUDFLARE_TUNNEL_TOKEN=eyJ...long-base64-from-the-cf-dashboard...+```++### Client config++Same as Path 1:++```bash+ai-memory install-mcp --client claude-code --apply \+ --server-url "https://memory.example.com/mcp" --auth-token "$AI_MEMORY_AUTH_TOKEN"+```++### What can go wrong++- **Token leak**. Anyone with `CLOUDFLARE_TUNNEL_TOKEN` can run a tunnel for your hostname. Keep the env file `0600`, don't commit it.+- **Tunnel down + cf cached old DNS** → Cloudflare returns 502 for a few minutes after restart. Usually self-heals.+- **Access policies confused with bearer auth**. Cloudflare Access (the optional SSO layer) is a separate layer from ai-memory's bearer token. Both run; both must pass. If Access blocks a request, ai-memory never sees it.++---++## Path 4 — External cert files (Caddy or nginx)++You already have a CA issuing certs to your services (corporate PKI,+homelab Vault, anything). You don't want Caddy issuing its own.++### Caddyfile++```caddyfile+memory.example.com {+ tls /etc/caddy/certs/memory.crt /etc/caddy/certs/memory.key+ reverse_proxy ai-memory:49374+}+```++Mount the cert + key:++```yaml+services:+ caddy:+ # ... rest as Path 1 ...+ volumes:+ - ./Caddyfile:/etc/caddy/Caddyfile:ro+ - /your/cert/path:/etc/caddy/certs:ro # the cert dir+ - caddy-data:/data+```++Caddy hot-reloads the cert when files change. No reload required.++### nginx equivalent++```nginx+server {+ listen 443 ssl http2;+ server_name memory.example.com;++ ssl_certificate /etc/nginx/certs/memory.crt;+ ssl_certificate_key /etc/nginx/certs/memory.key;++ location / {+ proxy_pass http://ai-memory:49374;+ proxy_set_header Host $host;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ # MCP Streamable HTTP transport is request-response; chunked+ # bodies and SSE both rely on the next two lines.+ proxy_http_version 1.1;+ proxy_set_header Connection "";+ }+}+```++The `proxy_http_version 1.1` + empty `Connection` are required for+MCP's Streamable HTTP transport to stream correctly.++---++## Native (non-Docker) Caddy++For operators running ai-memory from source / AUR / `cargo run`+without Docker:++```caddyfile+memory.example.com {+ reverse_proxy 127.0.0.1:49374+}+```++Install Caddy natively (`brew install caddy` / `pacman -S caddy` /+`apt install caddy`), drop the Caddyfile at the OS-canonical path+(`/etc/caddy/Caddyfile` on Linux, `/opt/homebrew/etc/Caddyfile` on+macOS), and `systemctl enable --now caddy` / `brew services start+caddy`. Everything else (LE, internal CA, external certs) works the+same as the Docker paths above — Caddy doesn't care which side of the+container boundary it's on.++For Cloudflare Tunnel: `cloudflared service install ${CLOUDFLARE_TUNNEL_TOKEN}`+installs and starts the tunnel as a systemd service on Linux or a+LaunchDaemon on macOS. Same shape as the Docker variant.++---++## What ai-memory does to support being behind a proxy++Nothing special — the server intentionally generates no absolute URLs+in responses, so it doesn't matter whether `https://` or `http://`+sits in front. The bearer token middleware reads `Authorization`+directly off the request, which proxies forward verbatim. The+`/api/v1` ETag is computed from request-independent fields. The+`/web` cookie set after Basic auth uses `SameSite=Lax` without+`Secure`, which lets it ride either transport — when fronted with+HTTPS, modern browsers automatically tighten the cookie to the proxy+origin's secure flag set anyway.++The only thing to mind: **`AI_MEMORY_ALLOWED_HOSTS` must include the+public hostname**, not just `localhost`. The host-allowlist middleware+runs before any header rewriting, so it sees the proxy's forwarded+`Host: memory.example.com` and would reject it otherwise.++## Don't paper over the security gap++Three things to actively avoid:++1. **Don't disable the allowed-hosts guard.** It's the DNS-rebinding defence; pruning it because the proxy "should be" filtering is exactly the kind of "the other layer handles it" assumption that ships bugs. Add the public hostname; don't widen to `*`.+2. **Don't skip the trust-install step in Path 2.** The temptation is to add `-k` (curl) or `--insecure` (MCP clients that support it) "just to get it working." If you do, you have a security theatre cert: TLS without authentication, which is worse than HTTP with the bearer because it looks safe and isn't.+3. **Don't run cloudflared with `--no-tls-verify`.** Cloudflare's tunnel daemon validates ai-memory's cert by default — which is fine because ai-memory is on plain HTTP inside the docker network. Don't override the flag; you'd be reaching for it because something else is misconfigured.++If you can't take one of these paths cleanly, the honest answer is+"keep ai-memory loopback-only" or "front it with the proxy you+already trust." The configuration that gives operators the wrong+mental model — looking secure, not being secure — is worse than+either.