# SeeThrough — backend setup

**Clarity before every move.** This is the operator guide for the self-hosted backend. The public website is one informational page, not a trading dashboard. Daily operation happens on **Even G2 glasses** and in the separate **SeeThrough News** Telegram chat.

The Even Realities App must host the SDK bridge on the phone. Its SeeThrough webview only pairs the device, shows connection/setup status, hands off Telegram pairing and forgets the session. It is not another trading frontend. All broker keys, model/search/Telegram credentials, transcription, policy and durable state remain on the server.

## 1. Prerequisites

- Ubuntu 24.04 LTS VPS, Docker Engine with Compose, a DNS name pointing to it, and inbound TCP 80/443. Restrict SSH. The included Gateway deployment selects **linux/arm64**; use an architecture-compatible host and actually reviewed images.
- Bun **1.4.4** for source builds, the repository and its single `bun.lock`. Use `bun install --frozen-lockfile`; do not replace the lockfile.
- An actual OKX **demo-issued** read/trade key, secret and passphrase for the supported `global-demo` profile.
- A genuine funded/entitled **IBKR PAPER** account, supervised Gateway login/2FA and exact account binding. Neither a DU account prefix nor port 4002 proves PAPER mode.
- Your configured Swiss AI load-balancer endpoint, API key and one tool-capable model. A failed compatibility probe blocks model requests; there is no alternate-model fallback.
- A private Speaches-compatible STT service and the exact installed transcription model.
- Optional news: a BotFather-created private bot, numeric owner user ID, webhook secret, Brave Search key and an explicit source-host allowlist.

Missing provider access is a readiness error, not a reason to show fixture balances, fabricated history or sample news. Building the app does not prove any broker order, transcription, Telegram acceptance or physical-device behavior.

## 2. Protect server configuration

Create an owner-only directory outside the checkout, for example `/etc/headsup`, and a mode-0600 `/etc/headsup/app.env` based on `.env.example`. Do not commit or serve this file. Set actual values privately:

| Variables                                                                                          | Purpose                                                                                                                                                                                          |
| -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `PUBLIC_ORIGIN=https://your-host`                                                                  | Exact public backend origin; no path or trailing application prefix.                                                                                                                             |
| `CORS_ORIGINS`                                                                                     | Comma-separated exact origins used by the installed SDK webview. HTTPS only in production. Include the actual hosted app origin; verify the installed Even App's Origin instead of allowing `*`. |
| `SWISSAI_BASE_URL`, `SWISSAI_API_KEY`, `SWISSAI_MODEL`                                             | One configured model provider.                                                                                                                                                                   |
| `STT_BASE_URL=http://stt:8000/v1`, `STT_MODEL`, optional `STT_API_KEY`                             | Private transcription adapter. `localhost` in a container is that container, not the VPS.                                                                                                        |
| `OKX_PROFILE=global-demo`, `OKX_API_KEY`, `OKX_API_SECRET`, `OKX_API_PASSPHRASE`                   | Demo-only broker authentication.                                                                                                                                                                 |
| `IBKR_HOST=ib-gateway`, `IBKR_PORT=4004`, `IBKR_CLIENT_ID=17`, `IBKR_ACCOUNT`                      | Application-side binding to the private Gateway bridge. Never choose the first returned account automatically.                                                                                   |
| `IBKR_PAPER_VERIFIED`, `IBKR_READ_WRITE_VERIFIED`                                                  | Leave false until a human verifies the real PAPER interface and Read-Only API is disabled. Then explicitly set true.                                                                             |
| `NEWS_ENABLED=false`                                                                               | Leave the scheduler disabled until news setup and separate consent are verified.                                                                                                                 |
| `NEWS_CRON_TOKEN`                                                                                  | A dedicated random token for private minute-cron requests.                                                                                                                                       |
| `BRAVE_SEARCH_API_KEY`, `NEWS_SOURCE_HOSTS`                                                        | Genuine search credentials and comma-separated permitted publisher hosts.                                                                                                                        |
| `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`, `TELEGRAM_OWNER_USER_ID`, `TELEGRAM_BOT_USERNAME` | Server-only bot credentials, numeric private-chat owner and username without `@`.                                                                                                                |

`VITE_API_BASE_URL` is the only SDK build-time public configuration: the exact HTTPS backend origin, never a key. The Compose build derives it from `APP_DOMAIN`. Changing the backend hostname requires rebuilding/repacking the SDK assets and checking both the network whitelist and server CORS origins.

Do not enable Sentry replay, PostHog autocapture or account/message/audio analytics on product surfaces. Raw audio and voice transcripts must not be persisted for personalization.

## 3. Prepare the private Gateway and STT services

### IBKR PAPER Gateway

Inspect a real compatible upstream IBC image manifest and set its immutable digest. The repository intentionally supplies no invented digest or certified Gateway build. The current Compose file expects a reviewed ARM64 IBC image and its documented password-file/socat configuration; do not substitute an incompatible image.

Set these Compose inputs in your operator shell or a protected Compose environment file, **not** in frontend configuration:

```sh
export IBKR_GATEWAY_DIGEST='<verified 64 hexadecimal characters after sha256:>'
export TWS_USERID='<actual PAPER login username>'
export IBKR_PASSWORD_FILE='/etc/headsup/ibkr-password'
```

Store the password in that owner-only file, not in the command line. Run from repository root:

```sh
docker compose -f infra/ibkr/compose.yaml up -d
```

Complete login/2FA and inspect the actual PAPER session. Enable socket clients, disable Read-Only API, verify the configured account and use the fixed nonzero client ID. The private application connects to `ib-gateway:4004`. Host access is **127.0.0.1:4002 → container 4004 → Gateway 4002**. Never expose these ports publicly.

If GUI maintenance is needed, supply an owner-only `IBKR_VNC_PASSWORD_FILE` and explicitly add `infra/ibkr/compose.login.yaml`. Reach 127.0.0.1:5900 only through SSH forwarding; recreate without that overlay after login. Daily/weekly reauthentication remains manual. Reconnection does not bypass 2FA or replay orders.

### Private transcription

Review an actual CPU Speaches image for the VPS architecture and set:

```sh
export STT_IMAGE_DIGEST='sha256:<actually reviewed image digest>'
```

The STT overlay uses the app's private Docker network; port 8000 is not public. Install the exact `STT_MODEL` in its persistent model cache using the reviewed image's supported download method. If the image provides `uvx`, the documented Speaches CLI flow is:

```sh
docker compose -f infra/app/compose.yaml -f infra/app/compose.broker.yaml \
  -f infra/stt/compose.yaml exec stt \
  sh -lc 'SPEACHES_BASE_URL=http://127.0.0.1:8000 uvx speaches-cli model download Systran/faster-whisper-small'
```

Start the services in the next section before running `exec`. Use your configured model rather than silently substituting this example. Verify the private model registry and a consented short WAV against `/v1/audio/transcriptions`. Audio is bounded to eight seconds, 16 kHz mono signed PCM; the backend builds the WAV and never accepts spoken trade authorization. See the [official STT installation](https://speaches.ai/installation/) and [transcription guide](https://speaches.ai/usage/speech-to-text/).

## 4. Build and start the backend

From repository root:

```sh
export APP_DOMAIN='your-actual-dns-name'
export APP_ENV_FILE='/etc/headsup/app.env'
docker compose -f infra/app/compose.yaml -f infra/app/compose.broker.yaml \
  -f infra/stt/compose.yaml up -d --build
docker compose -f infra/app/compose.yaml logs --tail 50 app
```

`APP_DOMAIN`, `APP_ENV_FILE`, `STT_IMAGE_DIGEST` and the Gateway inputs are Compose interpolation values. The app's `env_file` does **not** automatically populate the operator shell or Compose interpolation.

The image builds the G2 bundle first with the public backend origin, copies it into `public/g2`, then builds the website/backend so Nitro indexes all static assets. Caddy serves HTTPS/WSS through the single Bun process:

- `/` — one-page feature and installation website; no login/dashboard.
- `/g2/` — SDK entry for Even App local testing; a normal browser cannot render the glasses bridge.
- `/BACKEND_SETUP.md` — this downloadable guide, with no deployment secrets.
- `/v1/*` — authenticated application API and first-frame-authenticated WebSocket at `/v1/events`.
- `/healthz` — basic process health, **not** broker/model readiness or live acceptance.
- `/internal/*` — denied at public ingress. The app additionally verifies the cron token.

Only Caddy's 80/443 are public. App port 3000 is host-loopback for cron; STT and Gateway remain private. Do not publish extra broker/STT/telemetry ports.

The app logs a **single-use, five-minute owner pairing code**. Enter it only in the SeeThrough setup webview inside the Even Realities App. Session credentials stay on that device, never in a URL. Use protected logs; do not publish pairing codes. After setup, account/research/voice/review/news operations belong on the glasses, not the website.

## 5. Install on Even G2

You need G2 glasses, the Even Realities phone app and developer/tester access. There is no claimed public SeeThrough store listing or fabricated download link.

### Local hardware testing

1. Enable Developer Mode / Even Hub in the Even Realities App.
2. Generate a QR for the deployed SDK entry with the installed workspace CLI:

   ```sh
   # Run from apps/g2 after dependency installation.
   bun run --bun evenhub qr --url 'https://your-actual-dns-name/g2/'
   ```

3. In the phone app's **Even Hub** tab choose **Scan QR**. Pair with the server code in the setup webview.
4. Use glasses temple/ring input: scroll/tap to choose pages, long-press/release for speech, then read every review page. NO is selected first; only deliberate YES plus tap can authorize the exact ticket.

QR testing is not a permanent installation and does **not** establish locked-phone/background behavior. A localhost URL on your laptop is not reachable as localhost on the phone. For a local dev server, use its actual LAN address and configure the backend's exact origin/CORS settings. See [official Local Testing](https://hub.evenrealities.com/docs/test/local-testing).

### Packaged Beta installation

Build from source against your actual backend origin:

```sh
# Repository root
VITE_API_BASE_URL='https://your-actual-dns-name' bun run --filter @heads-up/g2 build
# Then run from apps/g2
bun run --bun evenhub pack dist/app.json dist --sdk-ver 0.0.16 -o see-through.ehpk
```

Upload the `.ehpk` to your Even Hub project's **Builds** tab. Add your account to **Testing group**, accept its invitation so it is **Active**, then click the uploaded build's **Private** tag and promote it to **Beta**. In the phone app use **Me → Beta tester → Install**. A Beta build plus Active tester membership is required; Private builds alone do not put the app on the glasses menu.

Verify on a real Beta install: microphone denial, five-minute phone lock, resume, root double-tap system exit dialog and launching another glasses app afterward. Simulator screenshots do not prove BLE, permission or hardware lifecycle behavior. See [official packaging](https://hub.evenrealities.com/docs/ship/packaging) and [Beta Testing](https://hub.evenrealities.com/docs/test/beta-testing).

## 6. Configure optional SeeThrough News

News is independent from trading and disabled by default. Pairing a device, pairing a bot or doing research never subscribes the owner.

1. Configure the actual bot token, username, numeric owner ID, webhook secret, Brave key and permitted source hosts. The webhook accepts only that owner's private chat and validates Telegram's secret header.
2. Register `https://your-actual-dns-name/v1/telegram/webhook` through Telegram's `setWebhook`, including the same `secret_token`. Keep the token-bearing Bot API URL and secret in a mode-0600 curl config/request file, not shell history, process arguments or public logs. Verify Telegram's actual response; deployment does not register it automatically. See [Telegram setWebhook](https://core.telegram.org/bots/api#setwebhook).
3. On glasses open **News → Settings** and request bot pairing. Open the one-use Telegram link through the setup handoff and start the private chat. Pairing is not subscription.
4. Separately opt in on glasses or send `/subscribe` in the already paired owner chat. Manage verified watchlist/interests/exclusions, optional research-derived personalization, quiet hours, mute/reset/unsubscribe on glasses. Telegram also supports `/unsubscribe` and `/mute 60`; it has no trading commands or general chat reader/replies.
5. Set `NEWS_ENABLED=true` only after provider/source setup and explicit subscription. Recreate the app with the protected env file.
6. Create root-owned `/etc/headsup/news-curl.conf` (0600) with `header = "Authorization: Bearer ACTUAL_NEWS_CRON_TOKEN"`. Use the same secret as the app; never publish this file.
7. Install `infra/app/news.cron` as `/etc/cron.d/headsup-news`, root-owned mode 0644. It calls the DB-owning process on host loopback every minute; it is not a second application worker or GitHub scheduler.

No matching articles means no fabricated story. Search/model results are validated before the shared G2 inbox and Telegram outbox are committed. Capture a genuine Telegram `message_id` and the same persisted story on active glasses before claiming delivery. API acceptance is not proof of phone notification display or reading. Ambiguous sends remain UNKNOWN across restart and are never blindly resent.

## 7. Verify broker and voice acceptance deliberately

Use a dedicated paper/demo account. Every **create and cancel** needs a fresh immutable review and explicit glasses tap. Never test by automatically confirming HTTP requests, speaking “yes,” replaying idempotency keys with changed terms or generating new IDs after UNKNOWN outcomes.

- Read actual account/PnL/positions/open orders and exact venue-qualified stock/spot/option metadata, quote modes and source times. Missing data remains unavailable.
- Inspect genuine model-selected summaries, scoped rankings, historical charts and exact option terms. Rankings disclose universe/metric; charts never interpolate fake bars.
- Authorize a small permitted order, record actual broker ID/status/requested/filled/remaining/average-fill-or-null, then separately authorize cancellation of a resting order. Acknowledged, held or canceled is not filled.
- OKX premium/outlay conversion needs a genuine fresh USD index; USDT parity is not assumed. IBKR market data/trading permissions and actual PAPER/read-write settings must be verified independently.
- Exercise consented glasses speech through private STT and the configured Swiss AI model. Fixture PCM tests do not prove transcription, microphone quality or latency.
- Disconnect/restart once under supervision; verify genuine reconciliation without resubmission. Missing broker history is not evidence that a mutation never happened.

## 8. Backups, upgrades and troubleshooting

The `app_data` Docker volume owns trading/news SQLite state, WAL and dedup history. **Never run `down -v` on production data.** Take a consistent SQLite backup with its backup API or stop the app before copying state; copying only a live main file can omit WAL transactions. Protect backups like credentials.

Disable cron and stop ingress before upgrades. Shutdown closes audio/WebSockets, drains owned broker work, releases adapters and closes SQLite. Startup expires reviews and reconciles nonterminal operations. UNKNOWN writes and sends are investigated, never replayed automatically.

| Symptom                            | Next action                                                                                                                              |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Website loads but glasses do not   | Open `/g2/` through Even App, not a normal browser; verify exact HTTPS origin, whitelist, CORS and SDK version.                          |
| Account unavailable                | Check server-only credentials, venue mode, exact account binding, real permissions and Gateway login/2FA. No sample balance is expected. |
| Model setup error                  | Verify the one configured endpoint/model/key and its read-only tool probe; do not switch providers silently.                             |
| STT unavailable                    | Verify private routing, installed exact model and actual transcription endpoint before microphone acceptance.                            |
| News stays disabled                | Check real owner-chat pairing, separate subscription, scheduler flag/token, source allowlist and provider access.                        |
| Beta expired / not on glasses menu | Both build tag Beta and tester status Active are required.                                                                               |
| Mutation or message is UNKNOWN     | Reconcile actual provider facts. Do not create a replacement operation or resend.                                                        |

Keep sanitized evidence of checks and remaining access requirements. No claim of live broker fills, Telegram delivery, VPS deployment or physical G2 acceptance follows from source changes alone.
