ØSTEN AI

Architecture

ØSTEN AI is a monorepo of four deployable apps plus a shared Postgres database.

AppStackRuns at
backend/Fastify + TypeScript + ZodCloud Run — api.ostenai.com
frontend/Next.js 16 (App Router), React 19, Tailwind + shadcn/uiapp.ostenai.com
landing/Next.jsostenai.com
docs-site/Next.js (Fumadocs, static export)docs.ostenai.com

The database is PostgreSQL — Neon in production, Docker Postgres locally.

Request path

Browser ──► Next.js dashboard ──► apiClient (Axios)
                                     │  Authorization: Bearer <Firebase ID token>
                                     │  x-organization-id: <uuid>
                                     ▼
                              Fastify (Cloud Run)
                                     │  authenticate → requireOrg → assertOrgRole
                                     ▼
                    ┌────────────────┴────────────────┐
                    ▼                                 ▼
              PostgreSQL                     Platform connectors
           (every query scoped         (Google Ads, Meta, TikTok, GA4,
            to organization_id)          Shopify, Vertex AI, Stripe)

Every authenticated request carries two things: a Firebase ID token proving who, and an x-organization-id header declaring which tenant. The backend verifies both on every request — the org header is never trusted on its own.

Backend layout

The backend is organised by domain module, not by technical layer. There is no controllers/ or services/ directory; a module owns its routes and the logic behind them.

backend/src/
├── app.ts              buildApp(): plugins, CORS, then every module registered under /api
├── index.ts            process entry — listen, signal handling
├── config/env.ts       Zod-validated environment; the single source of config truth
├── plugins/            auth (authenticate/requireOrg/requireSuperAdmin),
│                       errorHandler, schedulerAuth
├── db/                 pool.ts (query/transaction helpers), migrate.ts
├── lib/                crypto, firebase, stripe, assetStorage, veoClient, turnstile
├── connectors/         one directory per external platform — the only code that
│                       speaks HTTP to Google Ads, Meta, TikTok, GA4 and Shopify
└── modules/            accounts, admin, assets, auth, automation, billing,
                        campaigns, insights, onboarding, orgs, products,
                        reporting, shopify, video

The split that matters: connectors talk to platforms, modules talk to the database and to connectors. A module never constructs a platform API request itself, and a connector never assumes anything about HTTP routing.

Frontend layout

frontend/
├── app/
│   ├── (auth)/         login, signup, forgot-password, complete-registration
│   ├── (dashboard)/    the product: dashboard/*, campaigns, onboarding,
│   │                   marketing-plan, product-segments
│   ├── admin/          super-admin console (organizations, access codes)
│   ├── oauth/*/success OAuth landing pages per platform
│   └── invite/, impersonate/, request-access/, terms/
├── components/         ui/ (shadcn), campaigns/, dashboard/, ai/, analytics/,
│                       onboarding/, admin/, agents/
└── lib/
    ├── api-client.ts   Axios instance — injects auth + org headers
    ├── firebase/       client SDK config
    └── constants/roles.ts

Data fetching goes through TanStack Query over apiClient. Never call fetch directly against the API — you lose the auth and tenancy headers.

Integrations

IntegrationWhat it doesDegrades to
Google AdsOAuth, account listing, campaign CRUD, daily metric sync, search terms, PMax asset groupsfeature unavailable
Meta AdsOAuth, campaign create/manage, catalogs, pages, pixels, and metric sync down to ad levelfeature unavailable
TikTok AdsOAuth, campaign listing, metric syncfeature unavailable
GA4Property connection, daily analytics syncfeature unavailable
ShopifyOAuth, real-time order webhooks, product sync, UTM attributionfeature unavailable
Vertex AI (Gemini, Gemini image, Veo)Recommendations, ad copy, assistant, images, videotemplate fallbacks
StripeSubscription checkout and billing portalbilling routes 503
ResendInvitations, weekly digestsend skipped
Firebase AuthIdentity— (required)

Integrations fail closed. Every credential above is optional in config/env.ts; code that needs one degrades rather than throws when it is unset. That is what makes a fresh clone runnable with no credentials at all.

Scheduled work

Cloud Scheduler drives three endpoints, all authenticated with a shared secret in X-Scheduler-Secret and all fail-closed — if the secret is not configured the endpoint returns 503 rather than running:

  • POST /api/scheduler/sync-daily — ingest yesterday's metrics for every org
  • POST /api/scheduler/weekly-digest — email each opted-in org its digest
  • POST /api/scheduler/refresh-demo — re-seed the demo orgs so their history ends today (docs/super-admin.md, "Keeping the demo current" — internal)

They do the work before responding and return a summary. Cloud Run only gives an instance CPU while a request is open, so work continued after an early 202 is throttled and never finishes. The jobs (osten-sync-daily, 05:00 daily, and osten-weekly-digest, Mondays 08:00, both Europe/Stockholm) use a 30-minute attempt deadline, the Cloud Scheduler maximum, and the service --timeout is 1800s to match.

refresh-demo carries a second gate the other two do not: DEMO_REFRESH_ENABLED must be true. The scheduler secret is shared across all three, and this is the only one that deletes and rewrites organizations rather than reading from an ad platform — one leaked secret should not be enough to trigger it.

On this page