ØSTEN AI

Backend Guide

Fastify + TypeScript, in backend/. Node 24 (see .nvmrc).

npm run dev:backend      # :8080
npm run test:backend
npm run typecheck:backend

Structure

src/
├── app.ts          buildApp() — the whole HTTP surface, assembled in one place
├── index.ts        listen + graceful shutdown
├── config/env.ts   Zod-validated env, plus derived flags (aiFeaturesEnabled, …)
├── plugins/        auth, errorHandler, schedulerAuth
├── db/             pool.ts, migrate.ts
├── lib/            crypto, firebase, stripe, assetStorage, veoClient, videoFormats, turnstile
├── connectors/     google-ads/, meta-ads/, tiktok-ads/, ga4/, shopify/
└── modules/        one directory per domain

A module is a Fastify plugin: export async function xRoutes(app: FastifyInstance). app.ts imports each one dynamically and registers it under /api:

const { campaignRoutes } = await import('./modules/campaigns/routes');
await app.register(campaignRoutes, { prefix: '/api' });

Two modules use their own prefix: assetRoutes under /api/assets and videoRoutes under /api/video-jobs.

Auth and tenancy

Three decorators, registered by plugins/auth.ts:

DecoratorGuarantees
app.authenticateValid Firebase ID token, and the user exists in users. Sets request.user.
app.requireOrgThe above, plus the caller is a member of the org in x-organization-id. Sets request.organizationId and request.orgRole.
app.requireSuperAdminThe above, plus system_role = 'SUPER_ADMIN'.
app.post('/product-segments', { preHandler: app.requireOrg }, async (request) => {
  assertOrgRole(request, 'MEMBER');
  // request.organizationId is now safe to use as a filter
});

A wrong or unauthorized org id is a hard 403 — there is deliberately no fallback to the user's first organization. assertOrgRole is a separate, explicit step because membership is not permission: VIEWER ranks below MEMBER and must not be able to write. See docs/MULTI_TENANT_SECURITY.md (internal) for the full role table.

Endpoints that are not user-driven authenticate differently: Cloud Scheduler routes verify X-Scheduler-Secret, the Shopify webhook verifies an HMAC, and the Stripe webhook verifies a signature.

Spending money at Vertex

Every route that reaches Gemini or Veo turns one authenticated request into a billable call, so those routes are guarded by app.aiGuards(feature) (plugins/aiQuota.ts) instead of app.requireOrg:

// requireOrg + role check + burst limit + daily budget, in that order
app.post('/ai/generate-image', { preHandler: app.aiGuards('image') }, async (request) => {
  // no assertOrgRole here — the guard already did it
});
FeatureBurst (per org)Daily budget (per org, UTC)
text — ad copy, assistant, plans, scans, digests30/min500
image — Gemini image models, one unit per rendered variant10/min50
video — Veo5/min10

The two limits stop different things. The burst limit is an in-memory counter per Cloud Run instance — enough to smooth a runaway client, not enough to be an accounting record. The daily budget is the real cap: one row per (organization, UTC day, feature) in ai_usage_daily, charged with a single INSERT ... ON CONFLICT DO UPDATE ... WHERE used < limit, so the check and the write cannot be interleaved by two concurrent requests at the limit.

A unit is charged before generation and is not refunded if it fails: a refund path is the one an attacker would drive, since making a call fail is cheaper than making it succeed. GET /api/ai/usage reports the remaining budget so the UI can say so before a user meets a 429.

Raising a limit is a code change in plugins/aiQuota.ts rather than an environment variable — deliberately, so the number that bounds the bill is reviewed rather than set per-deployment.

AI creatives: real products, real logos

Ad images are built so the AI can only change the scene, never the brand:

  • Product. POST /api/ai/generate-image refuses (422 NO_PRODUCT_PHOTO) unless at least one real store photo loads; there is no text-only mode. The prompt also forbids people, added text and logos. After each render a vision call compares it with the store photo (checkFidelity); drift is flagged to the user, sorted last, and stored on creative_assets.fidelity alongside the photos it was built from (source_urls).
  • Logo. Nothing generates a logo. modules/brand finds the store's real logo on its website (or takes an upload), a person confirms it into brand_kits, and code places it: GET /api/brand-kit/logo-pack pads it into Google's 1:1 and 4:1 sizes.
  • Words and prices on a promo image are drawn in the browser (frontend/.../wizard/lib/promoOverlay.ts) from typed text and the store's real price, so they cannot come out misspelled or mis-priced.

Connectors

Each connector directory owns one platform and exposes a typed client plus task-shaped functions:

connectors/google-ads/
├── GoogleAdsClient.ts    authenticated transport
├── oauth.ts              connect/callback token exchange
├── gaql.ts               query builders
├── sync.ts               daily metric ingestion (idempotent upserts)
├── campaigns.ts          create/read campaigns
├── mutations.ts          budget/status changes
├── structure.ts          ad groups, ads, keywords, asset groups
├── searchTerms.ts        wasted-spend analysis
└── accounts.ts           accessible-customer listing

Sync is idempotent — metrics upsert on (entity, date), so re-running an overlapping window corrects rather than duplicates.

Database

db/pool.ts exposes query(sql, params) and transaction(fn). There is no ORM; queries are parameterised SQL.

const result = await query(
  'SELECT id, name FROM campaigns WHERE organization_id = $1 AND status != $2',
  [request.organizationId, 'REMOVED']
);

Never interpolate values into SQL, and never omit the organization_id filter on an org-scoped table.

Migrations live in backend/migrations/ as numbered .sql files and are additive — see docs/database-schema.md (internal).

Errors

Throw AppError; the central handler in plugins/errorHandler.ts does the rest.

throw AppError.notFound('Campaign not found');
throw AppError.badRequest('Budget must be positive', 'INVALID_BUDGET');

Responses are { error, code }. AppError messages are treated as client-safe and are logged at warn. Anything else is logged in full and returned to the client as a generic 500 in production, so database error text never leaks. Zod/Fastify validation failures become 400 VALIDATION_ERROR, and a Postgres unique violation becomes 409 DUPLICATE_RECORD.

Configuration

Every environment variable is declared and validated in config/env.ts. Adding one means touching three places, or it fails at runtime instead of at build:

  1. backend/src/config/env.ts
  2. backend/.env.example
  3. the --set-env-vars / --set-secrets lists in .github/workflows/deploy-backend.yml

Tests

Vitest, in backend/test/. Route-level tests build the real app and use app.inject, mocking only firebase-admin/auth and src/db/pool:

const res = await app.inject({
  method: 'POST',
  url: '/api/planner',
  headers: { authorization: 'Bearer ok', 'x-organization-id': 'org-1' },
  payload: {},
});

test/setup.ts refuses to run the suite unless DATABASE_URL points at a local database whose name ends in _test or _ci.

On this page