# Self-hosting Visibling

Visibling runs as a single Cloudflare Worker with D1, R2, Queues, and Basin Pipelines. You can deploy it on your own Cloudflare account and keep all operational and event data there.

Set `SELF_HOSTED=true` to disable SaaS-only behavior:

- Plan event caps and source map byte caps are not enforced; ingest admits every valid item.
- Monthly usage metering is skipped.
- Stripe billing is inert.
- The daily retention cron does not delete error occurrences or source maps, because a self-hosted install promises no retention.

## Prerequisites

- A Cloudflare account with Workers, D1, R2, Queues, and Basin Pipelines available.
- Node.js 20+ and pnpm 11.
- A domain or Workers route for the deployment.
- A Basin Catalog (Iceberg in R2) warehouse and a Basin SQL read token.

## 1. Get the source and install

The `lecstor/visibling` repository is private, so cloning requires an authenticated GitHub account with access to it. Ask the maintainers for access (or for a source archive of the release you want) before you start, then:

```sh
git clone https://github.com/lecstor/visibling.git
cd visibling
pnpm install
```

## 2. Create the Cloudflare resources

```sh
wrangler d1 create visibling
wrangler r2 bucket create visibling-artifacts
wrangler r2 bucket create visibling-basin
wrangler queues create visibling-ingest
wrangler queues create visibling-ingest-dlq
```

Create a Basin Pipeline stream in the Cloudflare dashboard (Basin → Pipelines) for the `visibling_events` table. The canonical row shape is `BasinEventRow` in `packages/@visibling/shared/src/normalize.ts`; columns are immutable once the stream is active, and custom event properties live inside `props_json`.

## 3. Configure bindings

Edit `apps/web/wrangler.jsonc`. The top-level block is local development; create a deployment block under `env.production` (or rename it) with:

| Binding | Kind | Purpose |
| --- | --- | --- |
| `DB` | D1 database | Accounts, organizations, projects, ingest keys, issues, occurrences, usage. |
| `ARTIFACTS` | R2 bucket | Source maps and oversized payloads. |
| `INGEST_QUEUE` | Queue producer + consumer | Asynchronous symbolication, fingerprinting, end-user upserts, and alerts. |
| `EVENTS_STREAM` | Pipeline | Product event rows delivered to the Basin stream. |
| `EMAIL` | Send Email binding | Verification and password-reset mail. Required for sign-up outside local dev. |
| `ratelimits` | Rate limit bindings | Every `RL_*` binding the code reads: sign-in, sign-up, verify, auth catch-all, ingest, API mutations, source maps, Cloudflare webhooks, Basin queries, Stripe webhooks, and Cloudflare trace queries. |

Vars for the deployment block:

| Var | Value |
| --- | --- |
| `DEPLOY_ENV` | `production` (anything other than `local` disables the dev fallbacks). |
| `APP_ORIGIN` | Optional, but set it to your deployment's public base URL (e.g. `https://visibling.example.com`). Issue alert emails use it to build "View issue in Visibling" links; without it those links fall back to `https://visibling.com`. |
| `SELF_HOSTED` | `true`. |
| `BASIN_ACCOUNT_ID` | Your Cloudflare account id. |
| `BASIN_BUCKET` | The R2 bucket backing the Basin Catalog warehouse. |
| `EMAIL_FROM` | The verified sender address for verification and reset mail. |

Keep `"compatibility_flags": ["nodejs_compat"]` and a current `compatibility_date`. The Worker needs Node compatibility for `AsyncLocalStorage`, which the request context uses.

Rate-limit `namespace_id` values are account-global. Every id must be unique across every app in your account; pick a free block and use a different id for each binding. Two bindings that share an id share one counter.

```sh
pnpm --filter @visibling/web types
```

Regenerate `worker-configuration.d.ts` after changing `wrangler.jsonc`, and commit it.

## 4. Set secrets

```sh
openssl rand -base64 32 | wrangler secret put AUTH_SECRET
openssl rand -base64 32 | wrangler secret put TOKEN_ENCRYPTION_KEY
wrangler secret put BASIN_SQL_TOKEN
```

- `AUTH_SECRET` signs sessions, verification links, and OAuth tokens. Required outside local dev.
- `TOKEN_ENCRYPTION_KEY` must decode to exactly 32 bytes. It encrypts per-project Cloudflare API tokens at rest.
- `BASIN_SQL_TOKEN` needs Basin SQL read permission; the dashboards query through it.

Optional secrets: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, and the four `STRIPE_PRICE_*` ids. Leave them unset to keep billing disabled.

## 5. Apply migrations

```sh
pnpm --filter @visibling/web db:migrate:production
```

This runs `wrangler d1 migrations apply DB --env production --remote`. If you deploy under the top-level configuration instead, run:

```sh
pnpm --filter @visibling/web exec wrangler d1 migrations apply DB --remote
```

Migrations are generated and committed with `pnpm db:generate`. Do not hand-edit an applied migration.

## 6. Build and deploy

```sh
pnpm build
pnpm --filter @visibling/web deploy:production
```

The deploy script rebuilds with `CLOUDFLARE_ENV=production` before `wrangler deploy`. That variable matters: `@cloudflare/vite-plugin` bakes `wrangler.jsonc` into `dist/server/wrangler.json` at build time, so deploying a build made for another environment ships the wrong bindings.

Set the route or custom domain in the deployment block, for example:

```jsonc
{
  "routes": [{ "pattern": "visibling.example.com", "custom_domain": true }]
}
```

If you want search-engine metadata and canonical URLs to name your own host, update `SITE_ORIGIN` in `apps/web/src/lib/site.ts` before building. The discovery endpoints (`/sitemap.xml`, `/robots.txt`) already use the request origin.

## 7. Point your apps at the deployment

Client apps install `@visibling/sdk` and point it at your deployment. The default proxy ingest URL is `https://visibling.com/api/v1/ingest`; for a self-hosted install, set it explicitly:

```ts
createVisiblingProxy({
  serverKey: env.VISIBLING_SERVER_KEY,
  ingestUrl: "https://visibling.example.com/api/v1/ingest",
  getIdentity,
});
```

Direct-mode browser clients use the same URL with a `vis_pub_` key:

```ts
createVisiblingClient({
  endpoint: "https://visibling.example.com/api/v1/ingest",
  publicKey: "vis_pub_your_key_here",
});
```

Tail Workers need `ingestUrl` too when no Service Binding is configured.

## 8. Smoke test

1. Open `https://visibling.example.com/sign-up`, create an account, and complete email verification.
2. Create a project and a server key under **Project settings → Keys**.
3. Send a batch:

```sh
curl -i -X POST https://visibling.example.com/api/v1/ingest \
  -H 'content-type: application/json' \
  -H 'x-visibling-key: vis_srv_your_key' \
  -d '{"items":[{"type":"track","name":"self_host_smoke"}]}'
```

A healthy install answers `202` with `{"ok":true,"accepted":1,"droppedInvalid":0,"droppedQuota":0}`, and `self_host_smoke` appears in the project overview.

## Operational notes

- The cron trigger `0 3 * * *` runs the retention sweep. With `SELF_HOSTED=true`, the sweep performs no deletions; it exists for the SaaS plan tiers.
- Queue consumers retry three times and route exhausted messages to the dead-letter queue. Keep the DLQ bound so failures are inspectable.
- Product events are written to Basin; operational state is written to D1. Back up the Basin warehouse and D1 database according to your own policy.
- `SELF_HOSTED` does not weaken auth: email verification is still required, and ingest keys are still stored hashed and shown once.
