Hopp til innholdet

DocumentationSystem ownerMarkdown

System owner: plans, usage, suspension, impersonation

Snakkbar's own staff (platform admins, rows in platform_admins) run every customer from the System owner view of the hosted panel (/panel). It is only shown to, and its API only answers, a platform admin signed in with Supabase Auth.

Who can do what

Caller/platform/*Operator APIVisitor API
Platform admin, Supabase token (hosted panel)yesany tenant (X-Snakkbar-Tenant)—
Platform admin impersonating an operatornoas that operator, audited—
Minted operator token (customer's UI)noown tenant—
Secret API key (sk_snakkbar_…)no— (server API)—

authPlatform (server/auth.ts) refuses minted tokens, visitor tokens and API keys outright, verifies the Supabase token, checks platform_admins on every request (no cache, so removing an admin takes effect at once) and only accepts browser calls from Snakkbar's own origin.

Plans and limits

Per tenant, set in System owner › Customers (columns on tenants):

ColumnMeaningNULL
planLabel shown to the customer ("Standard", "Pro", …)— (default standard)
monthly_turn_limitAssistant replies per calendar month (Europe/Oslo)unlimited
max_operatorsActive operators (platform admins' own rows do not count)unlimited
max_documentsUploaded files, imported pages and crawled PDFs (approved answers do not count). A PDF run adds no new PDFs once it is reachedunlimited
featuresjsonb map of flags; a missing key means on—

Existing tenants get NULL limits, so nothing changes for them until a limit is set. New tenants created in the panel start at 2 000 replies, 5 people and 100 documents (editable).

Enforcement

  • Assistant replies: snakkbar_claim_turn counts a turn before it runs (visitor messages and @assistant messages from the team). Over the monthly limit, or over the per-day abuse cap (max(500, monthly / 4), or 2 000 a day without a monthly limit — what used to be hard-coded), the visitor gets the usual graceful answer (code assistant_limit, the widget says "contact the team"; the callback/ask-for-a-person options stay). A team @assistant message is stored but the assistant stays quiet. A claimed turn that produced nothing (the assistant failed) is refunded. Admins see a banner when the month is used up and the numbers in Settings › «Usage this month».
  • Operators: provisioning (PUT /server/operators/:externalId, the first POST /server/operator-tokens for a new person, reactivation) and the panel's «Add person» answer 409 limit_reached when the plan is full.
  • Documents: POST /operator/knowledge/documents (file, upload intent, URL) answers 409 limit_reached when full.

Feature flags (server/plan.ts FEATURES): liveVisitors, proactiveChat, translations, callbacks, serverApi, webhooks, notifications. Enforced today: liveVisitors (public config and /visitor/activity) and serverApi (API keys are refused). The others are there for the features that will read them: hasFeature(tenant.features, "name"). Unknown keys are kept, so a new feature can store its own flag without a migration. The operator API exposes the resolved map as TenantSettings.features.

Usage metering

tenant_usage has one row per tenant per day (Europe/Oslo), incremented atomically by snakkbar_meter(tenant, counters, visitorId) (fire-and-forget after the response; metering never breaks a chat):

CounterWhere
conversationsPOST /visitor/conversations
visitor_messagesPOST /visitor/conversations/:id/messages (not replays)
operator_messagesPOST /operator/conversations/:id/messages (not replays)
assistant_turnssnakkbar_claim_turn (minus refunds)
assistant_tokens_in/out, assistant_cost_usdsummed from eve's step.completed usage (provider-reported, not estimated; cost only when the provider reports one)
other_cost_usdtranslations, the mascot's description and drawing: the AI Gateway's reported cost (providerMetadata.gateway.cost)
embedding_tokens, documents_indexedknowledge indexing (embedMany usage)
active_visitorsdistinct visitors per day: a new browsing session, a conversation or a message

Not metered: the embedding of the search query inside the assistant's knowledge tool.

GET /operator/usage (admins) returns the month with limits and states (ok, warning from 80 %, reached). The per-day visitor sets (tenant_usage_visitors) are pruned after 40 days by the cleanup cron; the counters are kept.

Revenue and cost

System owner › Customers is a table of every customer with its price and, for the last 7, 30 and 365 days (Europe/Oslo, today included), the result (revenue − cost) with revenue and cost as two thin bars on the column's scale; hover or focus shows the figures. Clicking a customer opens its figures: revenue, cost, result and margin, cost per AI answer, revenue against cost per day (30 days), week (90) or month (12 months), AI answers, the cost breakdown, usage, limits and the price history. The overview has the 30-day result for all customers.

  • Revenue is the subscription, not invoices: tenant_prices holds one row per price change (valid_from, monthly_price_nok, NOK excl. MVA), and each day earns the price in effect that day divided by the days in its month (snakkbar_revenue_days). No row = no revenue; 0 = free. A change is set in the customer dialog («Pris per måned» + «Gjelder fra», default today) and never rewrites earlier days. Choosing a plan from lib/plans.ts by name (Kokos, Mango, Pasjon, Tiki) fills in its price, limits and flags. Suspension does not stop revenue; set the price to 0 from a date for that.
  • Cost is model cost: assistant_cost_usd + other_cost_usd + embeddings estimated from embedding_tokens at text-embedding-3-small's list price ($0.02 per million tokens), converted to NOK at Norges Bank's latest USD/NOK (cached six hours; SNAKKBAR_USD_NOK or 9.4 when it cannot be reached). Past costs are converted at today's rate. Hosting, Supabase, e-mail and push are not included.

snakkbar_platform_economics(today) returns both per tenant and period; the server converts and sums (server/economics.ts, tested in server/test/economics.test.mjs).

Suspension

tenants.suspended_at (+ suspended_reason, shown to system owners only). While set:

  • GET /tenants/:id/config answers available: false with nothing else of note; the widget renders nothing and does not create a visitor or track. It reappears on the next page load after reopening.
  • Visitor API (POST /visitors and everything with a visitor token) answers 403 tenant_suspended.
  • Operator API answers 403 tenant_suspended, except GET /operator/me (so the admin can explain), and except platform admins and impersonation sessions. The admin shows a "This account is suspended" screen to the tenant's people and a red banner to system owners.
  • Server API (API keys) answers 403 tenant_suspended.

Tenant settings are cached for 60 s per server instance, so a suspension reaches every instance within a minute.

Tenants and people

System owner › Customers: create (id slug, name, sites, origins, assistant name, plan, limits, features, first admin), edit, suspend/reopen, delete (type the id; files in the documents, attachments and avatars buckets are removed first, then the row cascades) and open (the tenant switcher).

System owner › People: every operator across tenants, add a person to a tenant, change role, deactivate/reactivate (deactivation leaves open conversations, as the server API does), send a sign-in link, «Sign in as», and the list of system owners (add; remove, never the last one — removing one also deactivates their operator rows, which mostly exist because they opened tenants).

Invites and password links. A new e-mail address gets a Supabase invite (auth.admin.inviteUserByEmail); «Send sign-in link» re-sends the invite to someone who never signed in, otherwise a password reset e-mail. Both land on /panel/set-password, which signs the person in from the link and lets them choose a password. Links are only e-mailed, never shown in the panel: a system owner who could read them could sign in as the person outside the audited impersonation.

Only Snakkbar's own logins get access. Logins Snakkbar creates (invites, sign-in links for provisioned operators) carry app_metadata.snakkbar_created; older logins that already have an operator row or are system owners count too and get the mark when seen. Any other login with an address (a public sign-up with someone else's e-mail and a password of the signer's choosing) is never linked to operators, and is deleted and recreated before Snakkbar sends an invite or sign-in link to that address, so whoever made it keeps neither password nor sessions (server/auth-users.ts).

Impersonation («Sign in as»)

  1. POST /platform/operators/:id/impersonate (platform admin's Supabase token; optional reason) records a platform_impersonations row (≤ 1 hour) and mints an operator token with an imp claim { sid: <row id>, uid: <platform admin's user id> }, signed with SNAKKBAR_TOKEN_SECRET. Impersonating a platform admin (or yourself) is refused.
  2. The admin UI keeps its own client for the system owner and runs on the minted token (kept in sessionStorage for the tab) until «End» or expiry. A black banner says "You are signed in as X (Tenant) — End" the whole time; the tenant switcher, sign-out and the System owner view are hidden.
  3. «End» calls POST /platform/impersonations/:id/end with the system owner's own token and returns to the System owner view.

Unforgeable. Only the platform routes pass an imp claim to mintToken; customers' API keys cannot. Every request with an impersonation token re-checks the row (not ended, not expired, same operator, tenant and actor) and that the actor is still a platform admin, so ending a session or removing an admin stops the token at once, whatever its exp says. The claim's lifetime is checked too (≤ 1 hour).

Attribution and audit. Requests are made as the operator (they see what the operator sees and messages appear under the operator's name), but every change (any non-GET except heartbeats, typing, read markers and live-view renewals) is written to the audit log with the platform admin as actor before it runs; if the log cannot be written, the request is refused. Messages sent while impersonating carry meta.impersonatedBy = { userId, email, sessionId } (never sent to the visitor or exposed by the API; it is in the database and the audit log has the request). System notices that joining writes ("Ola joined the conversation.") are attributed to the operator.

Presence. Heartbeats from an impersonation session are ignored and available cannot be changed, so the real person never appears online. Typing indicators are shown as the operator.

AI models

System owner › AI models picks the model per role: Kundechat (the website assistant, eve, agent/agent.ts) and Pixel (the staff assistant, eve, pixel/agent/agent.ts). The choice is a platform default (platform_settings, key models), and a tenant can have its own (tenants.chat_model / pixel_model, in the tenant's dialog). The order is tenant → platform → built-in default (agent/lib/models.ts). Models are AI Gateway ids; the list with prices comes from the Gateway's public catalog (language models that can call tools, cached for six hours), and a save is refused for an id the catalog does not have. Both pick their model when a conversation starts, so ongoing conversations keep theirs. Platform defaults are cached for a minute per instance.

Try a model before switching. npm run eval runs the website assistant's evals (evals/) on a local dev server against a real tenant (EVAL_TENANT, default amatec: its settings, knowledge and site), with handoffs and callbacks stubbed so nothing reaches its inbox. EVAL_MODEL=<gateway id> npm run eval runs the same cases on another model. The eval sign-in (agent/channels/eve.ts) only exists on a local dev server (EVE_DEV). Needs a fresh VERCEL_OIDC_TOKEN (vercel env pull).

Audit log

platform_audit (append-only: updates, deletes and TRUNCATE are blocked by triggers; no foreign keys, so entries outlive tenants and users): tenant.create|update|suspend|unsuspend|delete, operator.add|update|deactivate|reactivate|login_link, platform_admin.add|remove, impersonation.start|end|request, platform.models. Each has actor (user id, e-mail), tenant, target, impersonation id and details (changed fields with before/after, reason, method and path). System owner › Log lists it newest first with filters by kind and actor; GET /platform/audit?action=tenant.&tenantId=&actor=&before=.

API

All under /api/v1/platform, platform admin only; SDK: createOperatorClient(…).platform.

GET /platform/overviewtotals this month, top tenants, replies per day
GET /platform/tenants · POST · PATCH /:id · DELETE /:id { confirm }tenants (price: { monthlyNok, from? } sets a new price; models: { chat?, pixel? } the tenant's own models, null follows the platform)
GET /platform/models · PUT { chat?, pixel? }built-in and platform default model per role, with the Gateway catalog (catalog null when it could not be reached)
GET /platform/economicsrevenue, cost and result per tenant for 7, 30 and 365 days, with totals
GET /platform/tenants/:id/economics?days=30|90|365one tenant per day, with the price history
POST /platform/tenants/:id/suspend { reason? } · /unsuspendsuspension
GET /platform/users?q=&tenantId= · POST { tenantId, email, name, role }people
PATCH /platform/operators/:id { role?, name?, deactivated? }change a person
POST /platform/operators/:id/login-linkinvite again or password reset e-mail
POST /platform/operators/:id/impersonate { reason? } → ImpersonationSessionstart
POST /platform/impersonations/:id/endend
GET /platform/admins · POST { email, name } · DELETE /:userIdsystem owners
GET /platform/auditaudit log

Setup

  • Migrations supabase/migrations/20261017150000_platform.sql, 20261021090000_tenant_economics.sql and 20261021160000_auth_user_lookup.sql (applied on push to main).
  • Supabase Auth › URL configuration: add https://<snakkbar host>/panel/set-password (and preview hosts) to the redirect allow list, and configure SMTP so invites and reset e-mails are delivered. The "Invite user" and "Reset password" templates may stay as they are.
  • Supabase Auth › Sign In / Providers: turn off "Allow new users to sign up". Every login is made by Snakkbar (admin API); public sign-ups are only a way to squat someone else's address.
  • The first platform admin is still added by hand: insert into platform_admins (user_id, display_name) values (…).
  • No new environment variables.