Skip to Content
Architecture & Surfaces

Architecture

Understand the boundaries between the web app, API, contracts, providers, and data.

The foundation separates the browser, API, contracts, persistence, and provider adapters so a builder or coding agent can change product behavior without inventing a second architecture.

flowchart LR
  U[Browser] -->|static assets| W[Native AWS or GCP host, or Cloudflare\nReact SPA]
  U -->|HTTPS + Better Auth cookie| A[Railway, AWS, or GCP\nBun + Hono API]
  W -. typed Hono RPC .-> A
  A -->|bun:sql| P[(Postgres 18)]
  A -->|Better Auth pg adapter| P
  A -->|normalized provider contract| B[Selected billing provider]
  A -->|transactional delivery| E[Resend]
  A -->|presigned upload + metadata| R[R2, Amazon S3, or GCS]
  A -->|optional envelope tunnel| S[Sentry]

The supported cloud defaults are cost-first and promote explicitly to HA. Each environment selects one backend cloud and one static frontend target. The application is a Vite SPA, not a server-rendered Next.js application, and there is deliberately no generic worker or queue in v1.

Workspace boundaries

PathOwns
apps/webReact shell, React Router, TanStack Query, Zustand client state, CSS Modules, Zag.js
apps/startTanStack Start full-stack edition on one Cloudflare Worker and D1
apps/mobileExpo client: expo-router, Unistyles, TanStack Query over the same typed RPC boundary
apps/serverHono routes, services, SQL repositories, Better Auth, migrations, provider orchestration
apps/docsSeparate Fumadocs and Next.js documentation application
apps/siteStatic Astro marketing site and the Cloudflare Worker that serves it
packages/contractsZod wire schemas and inferred request/response types
packages/billingProvider-neutral billing types and Polar, Stripe, Dodo, and RevenueCat adapters
packages/uiDesign tokens, global styles, and React primitives shared by the web and Start apps
packages/emailTyped React Email sources and deterministic rendered HTML
packages/create-appBuyer copy, package/brand rewrite, secret/env generation, optional Git initialization
packages/tsconfigShared compiler policy
infraOpenTofu bootstrap, cloud modules, executable roots, locks, and tests
scripts and .githubRelease, deployment, CI, and verification orchestration

internal/ is the source seller's private root — the commercial site, fulfillment operations, and planning documents. It is outside the root workspace and is never copied into a generated buyer product.

Server domain shape

Every product domain uses explicit layers:

contracts schema
      ↓
routes.ts        HTTP mapping, session, validation, response status
      ↓
service.ts       policy, provider-neutral orchestration, transactions
      ↓
repository.ts    parameterized SQL and persistence mapping
      ↓
Postgres

Routes do not contain SQL. Repositories do not know Hono. Services do not accept raw provider payloads after adapter normalization. Wire schemas live once in packages/contracts; database rows are mapped rather than exposed accidentally.

See Worked saved-links feature for a complete vertical slice, and preserve the ownership, failure, migration, contract, and test rules above.

Identity and authorization

Better Auth owns /auth/*, password hashing, verification, password reset, magic links, Google OAuth, cookies, and sessions. sessionAuth resolves the cookie through auth.api.getSession(), sets user_id and session_id in Hono context, and forwards refreshed Set-Cookie headers when Better Auth slides expiry.

Product authorization is separate from authentication:

  1. the route requires a verified session (sessionAuth) and, for organization-owned data, resolves the acting workspace from users.active_organization_id through organizationContext;
  2. role checks call can(role, permission) / requirePermission(role, permission) from apps/server/src/domains/organizations/permissions.ts;
  3. reads and writes include the organization_id (or user_id for personal account data) predicate directly in SQL;
  4. a missing or cross-owner private record returns the same 404 shape when existence must remain private.

There is no application access JWT, refresh token, local-storage token, or parallel user key.

See Authentication.

Billing and entitlement flow

The browser may request checkout, but it never grants access:

sequenceDiagram
  participant Browser
  participant API
  participant Provider
  participant DB as Postgres

  Browser->>API: create checkout (session cookie + plan)
  API->>Provider: product/price ID + external user ID
  Provider-->>Browser: hosted checkout
  Provider->>API: signed webhook
  API->>API: verify and normalize in adapter
  API->>DB: claim event + mutate subscription in one transaction
  API->>DB: derive paid entitlement
  Browser->>API: fetch billing status
  API-->>Browser: server-derived access

Subscription/customer rows are provider-neutral. The event claim and state mutation are one transaction; duplicate events are ignored and older provider timestamps cannot restore stale access. Trial, active, past-due, canceled-with-time-remaining, and expired states have explicit policy in domains/billing/entitlements.ts.

Account deletion is blocked while the local provider subscription can renew, an already-paid period remains, or the account owns a shared team organization with other active members. Deleting application data does not cancel a remote provider subscription.

Email and local development

React Email source templates are rendered into the server's required HTML inventory. The server preloads all ten templates before serving traffic. Resend handles production delivery; when Resend is unset in development/test, the complete email and action URL are logged.

The fallback makes authentication deterministic without vendor keys. Production environment validation requires Resend so reset, verification, and magic-link URLs cannot leak through the local log path.

Upload flow

The foundation ships two upload purposes: PROFILE_PIC (user-scoped public avatar, up to 5 MiB) and USER_FILE (organization-scoped private file library for /files, up to 10 MiB, downloaded via 5-minute attachment-pinned presigned GET URLs):

  1. validate purpose, MIME allowlist, declared size, target ownership, and entitlement;
  2. persist a pending claim and issue a 15-minute provider presigned PUT to the private staging bucket;
  3. confirm against actual provider metadata, object magic bytes/structure, and the pinned ETag or generation;
  4. atomically consume the claim and publish to the destination prefix, or mark it failed and best-effort delete the staged object.

The path prevents URL-only ownership, replayed confirmation, spoofed file types, and trusting the browser's claimed size. Storage remains optional locally. See Storage.

Configuration boundary

apps/server/src/config/env.ts is the sole server environment reader. Zod validates deployment strings, converts them into the typed Config, and enforces atomic optional integrations. Domain code consumes config(); it must not read process.env ad hoc.

Only explicitly public web values use VITE_*. Never place provider tokens, auth secrets, webhook secrets, database URLs, or private DSNs in the web build.

Runtime and deployment lifecycle

Deployments separate schema migration (./server migrate) from serving traffic (./server serve); local dev:server runs both in sequence. serve follows this startup order:

  1. validate environment;
  2. connect to Postgres;
  3. register application events;
  4. locate and preload all ten required email templates;
  5. bind the Bun server.

The compiled binary still requires external migration SQL and rendered templates. The Docker image copies both. Missing required resources fail startup rather than producing a delayed auth or billing failure.

/health is liveness. /ready queries the initialized database and gates Railway, ALB, and Cloud Run traffic. See Deployment.

State ownership

  • TanStack Query owns browser server-state caching and invalidation.
  • Zustand owns deliberate client-only state, not a copy of the API cache.
  • React Router owns route composition and protected navigation.
  • Postgres is the application system of record.
  • dbmate is the sole schema/migration history (executed via apps/server/src/infra/db/migrate.ts).
  • Better Auth is the sole session authority.
  • Provider adapters own raw external payloads and SDK types.
  • Zod contracts own public request and response shapes.

Deliberate limits

The v1 contract excludes multiple frontend frameworks, enterprise identity and provisioning, seat billing, admin impersonation, a generic job queue, and running multiple web billing providers in one deployment. Mobile is no longer excluded: a single Expo client on this API is accepted scope through docs/decisions/0005-mobile-edition-expo-client-on-the-existing-backend.md, and native mobile in-app purchases via RevenueCat (plus optional Superwall paywalls) are accepted through docs/decisions/0007-mobile-in-app-purchases-revenuecat-superwall.md. Local-first sync, offline writes, and a second mobile framework remain out of scope. The buyer selects one of the shipped Polar, Stripe, or Dodo adapters for web billing and may optionally enable MOBILE_IAP_PROVIDER=revenuecat for native stores. The SPA ships English, Spanish, and German, and deployment setup supports the documented Railway, AWS, and GCP targets. Broader scope requires a validated buyer job and a complete support contract.

Vite+ 1.6 and TypeScript 7 are pinned early-adopter dependencies. Vite+ owns package-local tooling and finite workspace verification; Turborepo owns the persistent root development process tree. Their operational rules and package-native escape hatches are in Setup.

On this page