docs
/
AI skills

App sign-in (AppAuth) and signing people in

How an app, a site, a script or an agent proves who it is to Appmint with an app credential, and how customers and staff then sign in on top of it — password, magic link, emailed code, social, two-factor, refresh and sign-out — with the exact headers, token lifetimes and failures that decide whether it works.

Every call to Appmint carries up to three things: which business (orgid), which app is calling (the app token), and, when a person is signed in, which person (their token). This skill sets each one up in the right place: the app first, then people on top of it.

The reference pages hold the full endpoint lists — link to them, don't re-read them here: Choosing an auth method, Customer authentication, User authentication, Two-factor and devices, OAuth and social login, API keys, Authentication (clients), Server proxy, Phone apps without a secret and Quickstart. This page is the how-to: which flow to pick, the exact calls, and what goes wrong.

The browser runtime as a whole (window.appmint) is in The Appmint JS engine on a page. This page covers only its sign-in methods. For the site's /login, /account and other fixed routes, see How a site's addresses route. A full website registration that creates a customer by automation is its own skill: Registration that creates the customer.

The model in plain words

  • An app credential is a user record in the System group with userType: "app". Its App ID is that user's username (the record's sk is accepted wherever an App ID is: app/key, app/challenge, app/attest and the appId header on guest/auth); its secret is that user's password. It is a service account, not a person, so it is listed under App Credentials, never Team Members. (appengine users.service.ts appRegister 3211–3267.)
  • The app token is an ordinary Appmint JWT for that app user. It says "this request comes from app X of business Y". It never says who the person is. (users.service.ts appToken 3167–3188.)
  • A person's token comes from a sign-in: a customer token for shoppers and members, a user token for staff. It rides in its own header, next to the app token.
  • orgid names the business. Tokens are verified against it: a token minted for one org is refused in another.
HeaderWhat goes in itWho sends it
orgidThe org's id, e.g. phazzerEvery tenant request
Authorization: Bearer <app token>The app's own tokenA server, proxy or phone app
x-client-authorization: Bearer <person token>The signed-in customer's (or staff's) token. The Bearer prefix is optional here.Only when a person is signed in
Content-Type: application/jsonRequests with a JSON body
x-client-host (or x-client-info with a host)The site the person is on, e.g. shop.example.comMagic links and emails that must link back to a site
x-api-key (or apiKey)An org API key, instead of an app tokenScoped server-to-server integrations

A customer token may also be sent alone as Authorization: Bearer <customer token> — customer routes accept that (verified: GET /client-data/profile with only the customer bearer returned the customer). Staff use Authorization: Bearer <staff token>. The middleware that reads all of this is current-user.middleware.ts; see How requests are checked.

orgid is required on almost everything. No orgid (header, ?orgid=, body field, or an orgid/orgId cookie) gives 400 missing_orgid. The exceptions are a short list of tenant-free routes — health, docs, and a signed-in request whose token already carries its org (pk = "<org>|<datatype>"). On the local engine, a bare GET /storefront/products with neither orgid nor a token answered 404 Not Found, not a helpful 400 — send the orgid. (current-user.middleware.ts 108–278.)

Which flow to use

Who is callingApp identityPeople sign in withWhere secrets live
A site hosted by Appmint (base-app)The host's app credential, already configured (APP_ID / APP_SECRET)The built-in /login and /register, or your own form posting to the site's /apiOn the host server. Nothing to set up.
Your own web app (Next.js, Remix, server-rendered)Its own app credential, exchanged on your server with POST /profile/app/keyYour login route on the server calls profile/customer/signin; the token goes in a cookie or server session you ownOn your server. Never in the browser bundle.
A headless / SPA front endAn app credential exchanged by a thin server proxy you runThe browser calls your proxy; the proxy adds the app token and forwards the person's tokenOn the proxy. The browser holds only the person's token.
A mobile app (iOS, Android, Flutter)The app's own credential, signed in with Apple App Attest / Google Play Integrity — no secret shipsprofile/customer/signin (or social) from the app, on top of the attested app tokenNowhere on the device. The secret is not shipped.
A script in a web page (the Appmint chat widget)The app's own credential, signed in by the website it runs on (app/attest with platform: "web") — no secret shipsA guest from profile/guest/auth on top of the app tokenNowhere in the page. The site's address goes on the app's Allowed domains.
AppMint Mobile (the staff app)None — it has no app credentialStaff sign in directly (profile/user/signin); every call carries the staff token and orgidNothing to keep; the staff token is the person's own.
A server-to-server integrationAn API key with scopes (not an app token)Usually none; acts as the key's system identityOn the integration server.
An AI agent / automationThe agent runs inside the engine with the staff identity; its tools inject orgid and the bearerNot applicable — it acts as the person who ran itIn the platform. Don't paste tokens into tool calls.

Pick by where the secret can be kept. A secret is safe only on a server you control. If code runs in a browser or ships in an app binary, it must not contain the secret — use the proxy pattern, App Attest / Play Integrity, or (for a script on a page) web sign-in by domain.

1. The app's own identity (AppAuth)

Register the app and get its secret

App registration is an administrator action (ConfigAdmin, RootAdmin or RootPowerUser), never anonymous signup. In Studio: Configuration › User, Group › App Credentials (sidebar user-group, open the App Credentials tab, or /app/user-group?view=app-credentials). Create Credential, give it an App ID and name. The secret is shown once, hidden behind an eye toggle, with a copy button — copy it then; the engine keeps only its hash and never shows it again. (websitemint packages/ui/src/components/user-management/modern-app-credentials.tsx 166–247; service app-credentials.service.ts registerApp 103–110.)

By API:

POST/profile/app/register

The reply is the new app's user record, carrying data.secret once. Keep sk (the record id) for later identity / debug-token / sign-in calls. (appengine users.controller.ts 821–826; users.service.ts appRegister 3211–3267.)

POST /profile/app/register always makes a new secret, and a repeat App ID is refused. A second register with the same appId answers 400 "App ID in use" (tested). To rotate a secret, use register?reset=true&id=<sk> (New key in Studio, rotateAppKey in the service); the old secret stops working at once. (app-credentials.service.ts 171–175.)

Exchange the secret for an app token (servers only)

POST/profile/app/key

The reply is { appConfig, token }. The token is the app token: a user JWT with data.userType: "app", groups: ["System"], roles: ["System"], aud: "user", iss: "appengine". It lasts one hour (JWT_EXPIRES_IN, default 1h; local development.env 142). There is no refresh token for an app token — exchange again when it nears the hour or a request answers 401. (users.controller.ts 828–832; users.service.ts appKey 3124–3160, getTokens 4511–4524; constants/jwt-constants.ts 13.)

The controller reads appId and secret (and optional domain); the key field the official clients also send is ignored — sending it is harmless (tested: a body with key + secret still succeeded). (users.controller.ts 828–832.)

Verified failures on app/key:

Body / stateAnswer
Wrong secret400 "bad secret"
App ID not an app of this org404 "app config not found <org> <appId>"
No orgid400 missing_orgid
orgid of another org404 "app config not found" (the lookup is tenant-scoped)
The app's check is Enforce401 { code: "app_attestation_required", reason: "secret_refused" }
The app credential is revoked401 "This app credential has been revoked"

Then every request carries:

GET/storefront/products

Tested: GET /storefront/products returned the catalog with the app token. The app token is a System account, so it can read public data but cannot read customer records (POST /repository/find/customer with only the app token → 403 RECORD_ACCESS) and GET /client-data/profile returns nothing — those need a person's token too.

System-group writes need a person. The app token can read catalogs and public data, but PUT/POST/DELETE /repository/create|update|delete as a System identity is refused with 401 "No customer found - x-client-authorization header is missing" unless the end user's token rides in x-client-authorization. The write is then evaluated against, and authored by, that person. (jwt.auth.guard.ts determineUser 193–211; customers.md.)

validate-app-key — an app token without the secret

POST /profile/validate-app-key returns an app token too, from { companyId, companyKey } (the org and App ID). It is role-gated (System, RootSystem, RootAdmin, RootPowerUser): tested, a staff ConfigAdmin token got 403 Forbidden, while an app token for the same app succeeded and returned a fresh 1-hour app token. base-app's validate_app_key runs this server-side; through a site's /api proxy an anonymous visitor reached it and got an app token (it is not on the proxy's server-only deny list). Use app/key for a server exchange; treat validate-app-key as the app re-minting its own token. (users.controller.ts 870–873; users.service.ts validateAppKey 3192–3209.)

Mobile apps: no secret on the device

A phone app ships only the org ID and App ID. It asks POST /profile/app/challenge for a one-use nonce (32 bytes, base64url, 2-minute life, one app only), proves itself at POST /profile/app/attest with Apple App Attest or Google Play Integrity, and gets a 1-hour app token carrying an attest claim. The full requests, the identity to register (iOS Team ID + bundle ID, Android package + signing SHA-256 + Play keys), the Off / Monitor / Enforce rollout, debug tokens for simulators, and every refusal reason are in Phone apps without a secret — follow it; don't duplicate it. (users.controller.ts 834–844; app-attestation/app-attestation.service.ts 90–91, TOKEN_LIFE 12–13.)

Tested on local against a skilltest-auth- app:

  • attest while the check is Off → 401 { reason: "attestation_off" }.
  • Setting the check to Monitor + allow debug tokens (PUT /profile/app/:id/identity { attestation: "monitor", allowDebugTokens: true }), making a debug token, then attest with platform: "debug" returned a 1-hour token whose claim was attest: { platform: "debug", method: "debug-token" }.
  • Re-using the same nonce → 401 { reason: "challenge_invalid" } (a nonce works once).
  • A challenge for an unknown App ID → 404 { code: "APP_NOT_FOUND" }.
  • Setting the check to Enforce then calling app/key → 401 { reason: "secret_refused" } (as above).

The check modes map exactly: Off — secret works, attest refused; Monitor — both work, failures still refused; Enforce — secret refused, attest only. (app-attestation/app-identity.ts attestationMode 29–31.)

Scripts on a web page: sign in by the website

A script on a page (the chat widget) ships only the org ID and App ID. It calls POST /profile/app/attest with { appId, platform: "web", domain: window.location.host } and no challenge. The engine answers a 1-hour app token (attest.method: "web-domain") when the domain is on the app's Allowed domains (data.app.web.domains) and the request's Origin header, when present, names the same host. A listed name without a port allows any port; one with a port allows only that port; a subdomain is a different website. This works whatever the check mode (Off, Monitor, Enforce). Refusals: web_not_configured (no domains listed), missing_proof (no domain sent), origin_mismatch, domain_not_allowed. Details and the Studio places that keep the list (App Credentials, Site Config › Chat, Chat Designer › Embed Code) are in Phone apps without a secret › Web. (app-attestation.service.ts verify; app-identity.ts domainAllowed.)

How a hosted site does it (base-app)

A site built on base-app never touches any of the above by hand. It reads APP_ID / APP_KEY / APP_SECRET / ORG_ID from its server env (lib/appmint-config.ts), and AppEngineClient.getAppToken() exchanges them at appmintEndpoints.appkey (profile/app/key) the first time it needs a token, caching it on the client instance and re-minting on a 401. (base-app lib/appmint-client.ts getAppToken 16–36, getHeaderWithToken 49–66, 401 retry 274–279.)

The browser never holds the secret. Browser code calls the site's own /api/* proxy (app/api/[...slug]/route.ts), which:

  • adds orgid and the app token server-side (getBaseHeader 38–46);
  • forwards the query string but not arbitrary request headers — it reads only authorization (the person's token) from the browser and re-sends it as x-client-authorization;
  • refuses a short deny-list of server-only API paths (lib/proxy-deny.ts: customer/social-login), returning 404.

The /api proxy drops custom headers. Anything you need the engine to see must go in the path, query string or body — not a custom header. Tested: a token sent to /api/client-data/profile as x-client-authorization was ignored (answered anonymous), while the same token as authorization (or a token cookie) signed in. This is why Registration that creates the customer puts the form code in the query string.

2. Signing people in, on top of the app token

Customers

Customers self-register. Every call below needs orgid plus the app token (or runs through the site's /api). The person's token comes back on success.

CallBodyReturns
POST /profile/customer/signup{ email, password, firstName?, lastName?, … }. Roles, permissions, groups and the fields the business sets (shared account, benefits, balance, tax exemption, verified flags) are not taken from a public sign-up: the new customer is in the group Customer only (users.service.ts customer sign-up fields){ customer, token, refreshToken }
POST /profile/customer/signin{ email (or username / phone), password }{ customer, token, refreshToken, orgId }, or a 2FA challenge
POST /profile/customer/refresh{ refresh_token }{ user, token, refreshToken }
GET /profile/magic-link?email=&type=code—sends a 6-digit code
POST /profile/magic-link/redirect{ email, code } or { email, token }{ user, token, refreshToken, … }
GET /profile/customer/password/forgot/:email/:redirectUrl?—{ email, success, strategy }, sends a reset link
POST /profile/customer/password/validate-token{ email, token }token check
POST /profile/customer/password/reset{ token, password }resets
POST /profile/customer/password/change (the customer's own token){ currentPassword, newPassword } (also read: password / oldPassword / current, and next). Always the signed-in customer's own account; the current password is required unless they are on a temporary one. Staff set one with customer/password/temporarychanges
POST /profile/customer/google/token{ code, redirectUri }native Google sign-in
POST /profile/customer/social-login (site-app only){ user, account }find-or-create behind a provider
POST /profile/customer/subscribe / unsubscribemarketing opt-in/out
DELETE /profile/customer/self (jwt)—the customer deletes their own account

The customer token: datatype: "customer", pk: "<org>|customer", aud: "user", 1-hour life; the refresh token 7 days (JWT_REFRESH_EXPIRES_IN, default 7d). (users.controller.ts 898–1056; users.service.ts customerAuth 3482–3634, customerSignup 3772–3862, refreshToken 1833–1871.)

Verified on local (sign-up and sign-in with [email protected], then deleted):

  • Sign-up stores a lower-cased email; [email protected] became [email protected]. Sign-in matches case-insensitively (tested SKILLTEST-... succeeded). New customers land in the Customer group. A welcome email (customer-welcome) is queued.
  • A duplicate sign-up answers 400: "An account with this email already exists. Please login instead.", or { code: "CUSTOMER_EMAIL_TAKEN" } when a staff token is on the request.
  • Sign-up with no email → 400 "Email required". Sign-in wrong password → 400 "bad password". Sign-in unknown email → 404 "customer … not found".

Customer refresh reads only refresh_token (snake_case) in the body. Tested: { refreshToken: … } and a bare authorization: Bearer <refresh> header both answered 400 "Cannot read properties of undefined (reading 'indexOf')" — a raw crash, not a clean error. Send { "refresh_token": "<token>" }. (Staff refresh at /profile/user/refresh accepts either refresh_token or refreshToken — users.controller.ts 372.) base-app's own refreshToken(refreshToken) helper posts { refreshToken }, so the hosted client's refresh is relying on the browser 401-retry path, not this body.

/profile/customer/password/reset wants { token, password }, where token is the reset token from the emailed link — not { email }. window.appmint.customer.resetPassword({ email }) and base-app's authApi.sendPasswordResetEmail both POST { email } to this endpoint, which crashes with the same indexOf 400 (tested). To send a reset email, use GET /profile/customer/password/forgot/:email (tested: { success: true }). Use reset only to apply a new password with the token the email carried. Treat the runtime's resetPassword({ email }) as unreliable; prefer the forgot GET to start a reset. (users.controller.ts 1035, 1063; base-app components/runtime/RuntimeBridge.tsx 91; runtime/namespaces.ts 733–736.)

A magic link needs a host; without one it 500s. GET /profile/magic-link?email=… with no x-client-host (and no redirectUrl) answered 500 on local, because it builds the link from the site's host. Send x-client-host: <site host> (the site's /api sets this from the request's Origin). The code variant (?type=code) needs no host and worked with just orgid. (users.controller.ts 1195–1216; magiclink.strategy.ts sendCustomerMagicLink 164–166.)

Magic code and magic link, tested:

  • GET /profile/magic-link?email=…&type=code stored a 6-digit data.magicCode with a 10-minute expiry; POST /profile/magic-link/redirect { email, code } returned a full session. A wrong code → 401 "Invalid code"; re-using a used code → 401 "Invalid code" (it is cleared on use). (magiclink.strategy.ts sendCustomerMagicCode 225–258, verifyMagicCode 338–408.)
  • The magic link token lives 15 minutes and is single-use — the record's data.magicToken is cleared on sign-in, so the same link a second time fails. Only the latest link works. (users.service.ts generateMagicLink 4466–4475; magiclink.strategy.ts validateAndSignIn 414–461.)

Staff may also hand a contact a one-time password (POST /profile/customer/password/temporary, { customerId, password, confirmed: true }); the next sign-in returns requiresPasswordChange: true with a token, and the person must set a new password. (users.controller.ts 1023–1028; customerAuth 3524–3533.)

Social sign-in

Providers: Google, Facebook, GitHub, Microsoft. Two shapes per provider: a redirect flow (web) and a token exchange (native / AJAX). The engine never trusts a profile from the request body on its own — an email the provider marks unverified is refused (403), and groups/roles in the body are ignored. (oauth-and-social.md; users.service.ts validateSocialLogin 2234–2305.)

  • Native Google (POST /profile/customer/google/token, { code, redirectUri }): the app runs Google OAuth, the engine exchanges the code server-side with its own client secret and reads the Google profile. (users.controller.ts 1339; exchangeGoogleCode 2160–2216.)
  • GitHub / Facebook token exchange (POST /profile/github/token, /profile/facebook/token, { code, state }): the state must be one the engine signed, and the org comes from the state, never the header. GitHub uses only the primary verified email. These controller routes sign the person in as staff (validateSocialLogin(..., false, ...)), so they are for operator apps, not storefronts. (github.strategy.ts 121–175; facebook.strategy.ts 133–206.)
  • POST /profile/customer/social-login is @SiteAppOnly: only the org's own site/app server may call it, after it has done the provider exchange itself and read the verified profile. An API key, a customer token or an ordinary staff token is refused. base-app's /api proxy blocks this path outright (proxy-deny.ts), so a browser can't reach it — tested, /api/profile/customer/social-login returned 404. (users.controller.ts 1056–1061; jwt.auth.guard.ts siteAppRefusal 293–315.)

On a hosted site, the social buttons are server routes: /auth/<provider> sets a signed, HttpOnly, one-attempt state cookie and redirects to the provider; /auth/<provider>/callback checks the state (login-CSRF guard), exchanges the code on the server, calls social-login, and sets the session cookies on the redirect. Only providers whose env is configured are shown. (base-app app/(auth)/auth/oauth-start-route.ts, oauth-callback-route.ts, callback-action.tsx 110–239.)

Staff

Staff are invited, not self-registered. POST /profile/user/signin (also /profile/signin, /user/signin), body { email, password }. Omit orgid and the email finds the org(s): one match signs in, several come back to choose from. The staff token is a user JWT; tested life 1 hour, refresh 7 days, and the signed-in payload carries the device id (did) so blocking that device ends the session. Refresh is POST /profile/user/refresh (refresh_token or refreshToken). (users.controller.ts 148–172, 371–378; signinToOrg 1183–1254.)

Use staff sign-in for admin calls, never in a site's front end. A staff token opens the whole back office. An AI agent uses it for admin work; a customer-facing page must only ever hold a customer token. Staff-only routes also refuse the app token and a customer token outright ("This needs someone signed in to the business"). (jwt.auth.guard.ts 55–63.)

Guests

POST /profile/guest/auth makes an anonymous guest customer so a cart, booking or chat can exist before anyone signs up. It needs this app's own token as the bearer, orgid, and the appId header naming the same app (its username or sk), plus email or phone in the body; without the app token it answers 401 { code: "app_token_required" }. The chat widget gets that token by web sign-in (above) and, on a 401, signs the app in again once before giving up. (users.controller.ts 125–127; guestAuth 757–795.)

Two-factor and new-device challenge

2FA sits on top of a password sign-in. It triggers when the org turns it on (securitySettings.enableTwoFactorForCustomers / ...ForUsers) or the person enabled it; separately, enableNewDeviceAuthentication forces an email code on an unrecognised device even with 2FA off. A trusted device is not challenged again. (customerAuth 3551–3619; two-factor.service.ts.)

When challenged, the sign-in returns instead of a token:

{ "requiresTwoFactor": true, "challengeToken": "…", "twoFactorMethod": "email",
  "message": "Verification code sent to your email" }

For email/sms the code is already sent; for authenticator the user reads it from their app. Then:

  • POST /profile/security/challenge/send { challengeToken, method? } — resend / switch method (public).
  • POST /profile/security/challenge/verify { challengeToken, code, trustDevice? } — exchanges the challenge for a real { user, token, refreshToken }. Both are public: the caller holds a challengeToken, not a session. (security.controller.ts 153–162; verifyChallenge 1227–1297.)

A wrong code → 400 { reason: "invalid_code" }; an expired or unknown challenge → 400 { reason: "challenge_expired" }. Backup codes are accepted in place of a code. trustDevice: true trusts the device for 30 days. The challenge token lives 10 minutes; the emailed/SMS code is held in the service's memory with a 10-minute life and a 5-try limit — then it is dropped and a fresh challenge is needed. (two-factor.service.ts 483–489, 667–680, 1276–1277.)

The org security switches (enableTwoFactorForUsers, enableTwoFactorForCustomers, enableNewDeviceAuthentication, alertOnNewDeviceLogin) are read from GET/PATCH /profile/security/settings (also GET /repository/setting/securitySettings). alertOnNewDeviceLogin is on unless explicitly false — a sign-up or sign-in from a new device emails the account. (two-factor-and-devices.md; customerAuth 3617–3619.)

Device management (jwt, under /profile/security/): GET devices, GET devices/current, POST devices/:id/trust, POST devices/:id/block, DELETE devices/:id, GET login-history. 2FA setup: GET 2fa/status, POST 2fa/setup/:method (email/sms/authenticator), POST 2fa/verify-setup, POST 2fa/enable / disable, POST 2fa/backup-codes. (security.controller.ts 19–130.)

On a hosted site

  • Built-in pages: /login, /register, /forgot-password, /reset-password, /login/error, and the /account/* portal are fixed Next routes, not pages you build (see routing). Tested: /login and /register return 200.
  • Where the session lives: on sign-in the server action writes three non-HttpOnly cookies — token, user, refreshToken (httpOnly: false so client activeSession can read them; Secure in production, SameSite=Lax, Path=/, 7-day max-age). The /api proxy reads the token cookie (or an authorization header) and forwards it as x-client-authorization. (base-app app/(auth)/actions.ts setAuthCookies 9–25; lib/active-session.ts 42–51; lib/appmint-auth.ts getClientInfo 460–468.)
  • /account redirects to /account/overview; signed out, any /account/* redirects to /login?redirect=<path>. Tested: /account → 307 /login; /account/orders anonymous → 307 /login?redirect=%2Faccount%2Forders; with a valid token cookie → 200. A dead token is special: the server adds ?expired=1, and /login clears the stale session instead of bouncing the visitor in a loop (tested: a garbage token cookie on /account/orders → 307 /login?expired=1). (base-app middleware.ts 21–26; lib/appmint-auth.ts 336, 371; app/(auth)/login/login-content.tsx 109–123.)
  • A custom login form uses window.appmint.customer.* (needs <RuntimeBridge /> mounted): signIn({ email, password }), signUp(input), signOut(), current(), isSignedIn(), changePassword(input). These delegate to the host's activeSession + auth bridge, so they store the session and update the UI — don't POST the auth endpoints by hand from a page. Honour the warning above about resetPassword. (base-app runtime/namespaces.ts 695–737; RuntimeBridge.tsx 72–93.)

Sign-out does not revoke server-side. POST /profile/signout is an empty handler; base-app's /auth/logout and activeSession.clearSession() just clear the cookies. A token already issued keeps working until it expires (or until the password is changed / the device is blocked / the account is locked, which the middleware checks live). To end sessions for real, change the password or block the device. (users.controller.ts 109–110; active-session.ts 53–61.)

How requests are checked

current-user.middleware.ts runs on every request and resolves identity before any guard:

  1. Reads orgid (header, query, body or cookie). Empty/missing → 400 missing_orgid, except the tenant-free routes and email-only sign-in. (108–278.)
  2. If an x-api-key/apiKey is present, authenticates the API key and checks its scope for this method+path; a scope miss → 403 { code: "api_key_scope" }. (271–285.)
  3. Reads Authorization. An app or staff/customer token is verified (signature, issuer appengine, audience, expiry, and pk against the org). A bad or expired primary token → 401 "Invalid or expired authorization". A revoked app credential → 401 { code: "app_revoked" }; a locked account, a changed password (session_revoked), or a blocked/removed device all end the session live. (307–455.)
  4. Reads x-client-authorization as the secondary person identity and loads it into request.currentCustomer. Its org and record are re-checked; a wrong-org customer token → 401 "Customer identity does not belong to this organization"; a tampered token → 401. An expired secondary token is not fatal — the request continues as anonymous (so public routes still answer), but it is marked expired so routes needing an identity still refuse. (525–600.)

JwtAuthGuard then applies the route's rule: @PublicRoute() lets anyone through; @SiteAppOnly() admits only the org's own site/app login; a staff-only route rejects the app identity and customers; @Roles(...) / @RequirePermissions(...) check the person's grants. Roles are a staff matter: a customer record counts only as Customer or Guest, whatever roles it names. Grants are read from the current account record, not the token's frozen copy, so a removed role stops working at once. (jwt.auth.guard.ts 33–100.)

Choosing and troubleshooting

Which flow (quick reference)

SituationApp identityPerson sign-inKey / secret
Appmint-hosted sitehost's app credential (env)/login, /register, window.appmint.customer.*on the host
Headless web appapp credential via your proxyyour login route → profile/customer/signinon the proxy
Mobile appApp Attest / Play Integrityprofile/customer/signin / socialnone on device
Chat widget / script on a pageweb sign-in by domainprofile/guest/authnone in the page
AppMint Mobile (staff)noneprofile/user/signinthe staff token only
Server-to-serverAPI key with scopes—on the integration
AI agent / automationinjected by the toolacts as the running staff userin the platform

Common failures

SymptomCauseFix
400 missing_orgidNo orgid anywhere on the requestSend orgid (header is normal); on a site the /api proxy adds it
404 Not Found on a public GETNo orgid and no token (the probe short-circuit)Add orgid or a token that carries the org
401 Invalid or expired authorizationThe app/staff token (primary Authorization) is bad or expiredRe-exchange the app token (app/key), or refresh the staff token
401 with an app token on a customer routeThe app token is not a shopperAttach the customer token as x-client-authorization
403 RECORD_ACCESS / "Customer identity is required"App token only, no personAdd the person's token
401 "No customer found - x-client-authorization header is missing"A System identity tried a repository write with no personSend the end user's token in x-client-authorization
401 "Customer identity does not belong to this organization"Customer token sent with the wrong orgidMatch orgid to the token's org
A custom header the engine never sees (on a hosted site)The /api proxy forwards only the query string and the person's authorizationPut the value in the path/query/body
401 { reason: "secret_refused" } on app/keyThe app's check is EnforceUse App Attest / Play Integrity, or give servers a separate app credential left Off
401 { reason: "domain_not_allowed" } / "web_not_configured" on a web attestThe website isn't on the app's Allowed domainsAdd the site's host (Site Config › Chat › Add this site, or Chat Designer › Embed Code)
401 { reason: "origin_mismatch" }The domain sent isn't the page's OriginSend window.location.host from the page itself
Magic-link request 500sNo host sentSend x-client-host, or use the ?type=code variant
400 "Cannot read properties of undefined (reading 'indexOf')" on refresh/resetWrong body shape (refreshToken instead of refresh_token; { email } to password/reset)Use { refresh_token }; start a reset with the forgot GET
A session that "won't sign out"Sign-out doesn't revokeExpect the token to live to expiry; change password / block device to kill it

Cloudflare blocks non-browser user agents on appengine.appmint.io (error code 1010). A script hitting the live engine with a default agent (seen with Python's urllib) gets 403 with an HTML body containing error code: 1010, before Appmint even sees the request. It is the WAF, not auth. Send a normal browser User-Agent, or test against the local engine. This does not apply to the local engine (192.168.1.239:3300). The engine itself also rate-limits (429) per IP window. (appengine main.ts 144–156.)

What it can't do yet

  • Customer refresh and password/reset crash on the wrong body shape (a raw 400, no clean message). The hosted runtime's resetPassword({ email }) hits this; use the forgot GET to start a reset.
  • The browser-side x-client-authorization convention does not travel through base-app's /api proxy — the proxy reads the person's token from authorization (or the token cookie) and re-adds x-client-authorization itself.
  • Session cookies on a hosted site are not HttpOnly (activeSession reads them in the browser), so treat the site's token as readable by page JavaScript; keep app secrets strictly server-side.
  • No server-side sign-out / global revoke endpoint. Revocation is only via password change, device block or account lock.

Don'ts

  • Don't put an app secret in a browser bundle, a mobile binary, or a NEXT_PUBLIC_/VITE_ variable. Server or proxy only; mobile uses App Attest / Play Integrity; a script on a page signs in by its website.
  • Don't use a staff token in a customer-facing page or app. Customers get a customer token; staff tokens are for the back office and AI admin work.
  • Don't turn the app identity into the buyer — a customer's own data needs the customer's token.
  • Don't print tokens or secrets in logs, URLs, screenshots or pages. GET /profile/who-is can echo token details; never expose its output.
  • Don't register a production app just to test — a skilltest- app on the local engine, deleted after, is enough.
  • Don't register an app from the browser (app/register is admin-only and gives the secret once).