Authentication¶
Tomoda exposes a single identity model — the User row — reached via several front doors. Once authenticated, every client carries the same access JWT and uses the same refresh-token flow. This page is the system-level view of how authentication is composed; for the implementation (services, struct fields, OTP internals, code paths) see backend/services/auth, and for the client wiring see Frontend API Client.
Authentication methods¶
Tomoda supports six independent authentication entry points. All of them converge on the same session pipeline — once a user is identified, the rest of the system treats them uniformly.
| Method | Front-door identity |
|---|---|
| Email + password | Bcrypt-hashed password |
| Google OAuth | Google ID token, verified server-side |
| Apple Sign-In | Apple identity token, JWKS verified server-side |
| WebAuthn / passkey | Stored public key + signed challenge |
| OTP (signup / reset) | Short-lived 6-digit code, purpose-tagged |
OTP is not a long-lived auth method on its own — it is a verification step that gates registration, password reset, email change, and phone updates. Once verified, the same registration / login paths mint the access tokens.
Token model¶
Every authenticated session is anchored by three pieces of state:
| Token / state | Lifetime | Purpose | Lives in |
|---|---|---|---|
| Access JWT | 24 h (Tomoda accounts: 15 min) | Bearer credential carried on every API call and on WS upgrade | Client memory + storage |
| Refresh token | 30 d (web) / 180 d (native) sliding, 1 y cap; Tomoda accounts 2 h sliding, 12 h cap | Opaque server-issued string used to mint new access JWTs | Postgres + Redis mirror |
| Session row | Until revoked | Per-device record (UA, IP, last-used) — surfaces "active sessions" UX | Postgres |
The access JWT is the only token the system trusts inline; the refresh token is exchanged at /auth/refresh for a new JWT; the session row is the audit/revocation surface users see on their security screen. Refresh tokens may be presented over HTTP (header) or query-string (WS upgrade, since browsers can't set headers on the upgrade).
High-level flow¶
┌──────────────────────────────┐
identity ────► │ AuthService — verify caller │
provider │ (password / OAuth / passkey)│
└─────────────┬────────────────┘
│ user resolved
▼
┌──────────────────────────────┐
│ Issue access JWT + refresh │
│ Create Session row │
└─────────────┬────────────────┘
│
▼
┌──────────────────────────────┐
│ Client stores tokens; every │
│ subsequent call carries JWT │
└──────────────────────────────┘
Refresh-token rotation, revocation, and session listing are all driven from the same Session + RefreshToken records — that uniformity is the system-level invariant.
Cross-cutting invariants¶
These hold across every auth method and every protected endpoint:
- One identity, many doors. Whichever method authenticated the caller, the downstream system sees a single
user_idandroleclaim. No handler branches on "how did this user log in?". - Access JWT is stateless; refresh token is stateful. The JWT is HMAC-signed and verified inline, then checked against the user's
token_versionand account status. Refresh tokens resolve against Postgres, which is the sole authority on whether a token is live. Redis holds a mirror of the token for other readers; a mirror hit never authenticates on its own, because it outlives the revocation that deleted the row. - Only a dead refresh token ends a session.
/auth/refreshreturns 401 only when the token is unknown, expired or revoked (or its user is gone). Any other failure, such as a database or Redis error while checking it, returns 503, and clients treat that and every other non-401/403 failure as transient: they keep the session and retry. Re-authentication failures (a wrong password or OTP for account deletion or data export) return 401 withREAUTH_FAILED, and a wrong step-up credential returnsSTEP_UP_FAILED; clients never read either as an expired session. - Sessions are sliding and long-lived. Every refresh-token use updates
last_used_atand pushes the token's expiry a full inactivity window forward (native 180 days, web 30 days), so an app that's opened at all within the window keeps its session until an absolute cap of one year from issue; a device untouched for the whole window has to sign in again sooner. - Revocation is per-session. Logging out a device deletes its refresh token and its session row in both Postgres and Redis. "Log out all devices" enumerates the user's tokens, deletes each Postgres row and its Redis mirror, then bumps
token_versionso live access JWTs die on their next request. - Losing account standing ends the session immediately. Disabling, suspending, or deactivating an account revokes its refresh tokens and bumps
token_version.JWTAuthalso confirms the account is still usable on every request (cached for 60 s), so a ban does not wait out the token's 24 h lifetime. Thetoken_versionand account-status checks fail open on a transient infrastructure error (a DB or Redis blip): the stateless JWT is still valid and unexpired, so a momentary outage must not sign every active user out. They fail closed only on a real signal, a version mismatch or a missing/inactive account. - OTP gates sensitive mutations. Registration, password reset, email change, and phone update all require a successful OTP verify before the mutation handler runs. Verification spends a per-address attempt budget (5 per 15 min) and issuing a code retires the previous one, so codes cannot be brute-forced or accumulated.
- Destructive account actions re-authenticate. Deleting an account needs a credential beyond the bearer token: the account password, or an OTP token for accounts that have none.
- Changing a password logs out everywhere, including the current device. Password change and password reset both delete every refresh token and session row, then bump
token_version. Becausetoken_versionis one epoch per user rather than per session, "all except this one" is not expressible, and a bump alone would leave refresh tokens live. Clients re-authenticate after either flow. - Provider webhooks are trusted only by signature. Apple's server-to-server endpoint is unauthenticated and can deactivate an account, so its ES256 signature, issuer, audience, and expiry are all verified before any claim is read. The JWKS
kidselects a key; it never confers trust, since the keys are public and thekidcomes from the caller. - IP-keyed defenses use one trusted-proxy policy. Rate limits, IP blocking, and audit attribution all derive the caller's address from
api.ClientIP, which believesX-Forwarded-Foronly as far as the configured trusted-proxy hop count or CIDR list allows. - WebSocket auth uses the same JWT. The hub's upgrade handler accepts the access JWT via
?token=query parameter because browsers cannot set headers on the WS upgrade. The validation path is otherwise identical, and no route outside/ws/accepts a query token.
Account types and roles¶
Every User row carries two orthogonal identity fields, both defined in backend/internal/models/user.go:
AccountType— what kind of account is this? Defaults tostandardand is set at signup or bymigrate.SeedSyntheticAccounts. Used to filter special accounts out of analytics, leaderboards, anti-abuse, and (future) MFA enforcement.Role— what is this account allowed to do inside the app? Defaults tobase.
| Account type | Used for |
|---|---|
standard |
Regular consumer signups |
tomoda |
Internal Tomoda accounts (admins, curators, ops). Cannot use the consumer app directly; link a standard account to access it. |
synthetic |
System-owned probe accounts (Cloudflare login monitor — see migrate.SeedSyntheticAccounts). Also the app-store review account and its companions (Synthetic accounts). Mounts the standard shell so monitors and reviewers can exercise real consumer routes; filtered out of analytics, leaderboards, anti-abuse. |
partner |
Partner accounts (merchants, advertisers, organizations). Cannot use the consumer app directly; link a standard account to access it. |
| Role | Used for |
|---|---|
base |
Default for new accounts — no elevated permissions |
admin |
Full administrative access (Tomoda or partner admins) |
curator |
May add curated content to Tomoda |
auditor |
Read-only access for monitoring / compliance review |
operator |
State management in app (ops actions) |
support |
Manage support cases |
moderator |
Act on member accounts (suspend, restore, sign out) |
developer |
Internal Tomoda devs; unlocks dev-mode UI and features |
Both columns are indexed varchar(20). The pair is the basis for RBAC: an admin of a partner account is scoped to that partner via PartnerMembership (see Partners), while a tomoda account's role maps to Backstage capabilities (see Account type policies). Tomoda roles are set only through Backstage Accounts (models.TomodaRoles); base on a tomoda account means revoked.
Authorization¶
Authorization is one framework in backend/internal/access. Every protected Backstage and partner route declares the capability it needs; one authorizer decides from the database on every request.
Account type policies¶
Everything that differs by account type lives in one static registry, policies in backend/internal/access/accounttypes.go. Each AccountPolicy declares:
| Field | Means |
|---|---|
Surface, Home |
The app shell the account type uses and its landing route |
Namespace |
The prefix of every capability of that surface |
Roles, RoleCapabilities |
The roles an invite may grant and what each role may do |
MembershipRoles |
Roles are held per workspace membership (partner), not as the account's own role |
SignIn |
The direct sign-in methods (password, google, apple, passkey); anything else answers like a wrong credential |
StepUp |
The credentials accepted to re-authenticate, in preference order |
Sessions |
Access token lifetime, refresh idle window and refresh chain cap; zero means the platform default |
Linkable, SwitchStepUp |
Whether a standard account can link this type and switch into it, and whether switching needs a fresh step-up |
| Type | Surface | Direct sign-in | Sessions | Linkable | Switch needs step-up |
|---|---|---|---|---|---|
standard |
member | every method | defaults | no | n/a |
tomoda |
backstage | passkey, or password plus an emailed code | 15 min access, 2 h idle, 12 h cap | yes | yes |
partner |
partner | every method | defaults | yes | yes |
synthetic, external-curators |
member | every method | defaults | no | n/a |
An unknown account type gets an empty policy: no sign-in and no capabilities. Adding a surface is a new registry entry plus its capabilities; the link, step-up, switch and invite endpoints stay the same.
Enforcement. Every sign-in path checks the policy on the server: password login and password reset (Login, ResetPassword), Google, Apple and passkey sign-in (finalizeLogin in backend/internal/services/auth/auth_service.go). A refused method answers exactly like a wrong credential, with the same password hash cost, and never spends the account's lockout budget. Access token lifetime comes from accessTTL and the refresh window and cap from refreshPolicyFor.
Access control¶
Four parts, each in one place:
- Capability registry (
capabilities.go). Each capability is declared once as aDef: its name (<surface>.<area>.<verb>, or<surface>.<area>.action.<verb>for changes), a description, and two flags.StepUpmeans a fresh sensitive step-up must accompany the request.Privatemeans the capability reads private member data and the request must carry a reason. The registry panics at start-up on a malformed name, a duplicate, a missing description, or a role that grants an unregistered capability or one from another surface. - Role tables (
backstageRoles,partnerRoles). One table per surface maps each role to its capabilities. Backstage roles are the account's own role; partner roles are the caller's membership in the workspace. The matrix below is generated from them. - Authorizer (
authorizer.go).Authorize(subject, capability, scope)returns allow or deny with a reason. Scope is global for Backstage and the workspace for partner. Backstage reads the caller'saccount_type,roleand standing from Postgres; partner reads the membership (and the workspace status, so a suspended workspace is refused). Nothing is cached, so a demotion, suspension or revocation applies to the very next call even though the JWT still carries the old role. A read error is returned as an error and answered with 503, never as an allow. - Route tables (
routes.go). A surface lists its routes asaccess.Get(path, capability, handler)entries (backstage.Routes,partner.Routes) and mounts them withaccess.Mount.Authorizer.Require(capability)is the only gate: it resolves the scope from the capability's surface (the{partner_id}route param for partner), asks the authorizer, then enforces the flags before the handler runs. A route without a capability cannot be written.
Responses: 401 for an unauthenticated caller or a gone account, 403 for any other denial, 503 when the database cannot answer. A denied request is counted in tomoda_auth_authz_denied_total{capability,reason} and logged at debug.
Step-up. A StepUp capability needs the header X-Step-Up-Token with a token from POST /auth/step-up (purpose sensitive). The middleware spends it after the role check, so a denied caller never burns one, and a missing or spent token answers 403 STEP_UP_REQUIRED. Handlers never check it themselves.
Private reads. A Private capability needs the header X-Access-Reason. The middleware rejects a request without one (400 REASON_REQUIRED) and hands the trimmed text to the handler through access.ReasonFrom(ctx) for the audit row.
Tests that keep it honest. A golden file (testdata/role_matrix.golden) holds the role by capability matrix, so any permission change shows up in review. The docs tables below and the client list frontend/services/backstage/Capabilities.ts are checked against the registry; go test ./internal/access -update regenerates all three. A router test walks every route under /backstage and /partner/{partner_id} and fails if one is reachable without passing a capability gate.
Adding a capability. Declare the constant and its Def, grant it to roles, add a route to the surface's table, run go test ./internal/access -update, and gate the screen with can('<capability>').
Adding a surface. Add a Surface and an account type policy with its role table, a route table, and the scope rule in Authorizer.Authorize.
Roles by capability. Generated; do not edit by hand.
Backstage
| Capability | Allows | Needs | admin | auditor | operator | support | developer | moderator | curator |
|---|---|---|---|---|---|---|---|---|---|
backstage.session.read |
Open Backstage and read your own capabilities | x | x | x | x | x | x | x | |
backstage.today.read |
See the Today dashboard | x | x | x | x | x | x | x | |
backstage.people.read |
Find members and read their profile | x | x | x | x | ||||
backstage.people.action.suspend |
Suspend a member and end their sessions | x | x | ||||||
backstage.people.action.restore |
Lift a member's suspension | x | x | ||||||
backstage.people.action.sign_out |
End every session of a member | x | x | x | |||||
backstage.audit.read |
Search the audit log | x | x | ||||||
backstage.reports.read |
Read the report triage queue and report groups | x | x | x | |||||
backstage.reports.action.resolve |
Dismiss a report group or act on it | x | x | ||||||
backstage.cases.read |
Read support cases, including internal notes | x | x | x | x | ||||
backstage.cases.action.reply |
Reply to, assign and change the status of support cases | x | x | x | |||||
backstage.crashes.read |
Read the top crash issues and a case's diagnostics | x | x | x | |||||
backstage.data.read |
Read registered datasets and recent data changes | x | x | x | |||||
backstage.data.read_private |
Read private fields of registered datasets | reason | x | ||||||
backstage.data.action |
Preview and apply typed, reversible data changes | x | |||||||
backstage.data.action.approve |
Approve or reject another admin's data change | x | |||||||
backstage.insights.read |
Read the daily platform insights | x | x | x | x | ||||
backstage.insights.read_member |
Read one member's engagement | x | x | ||||||
backstage.accounts.read |
List Tomoda accounts and invites | x | x | ||||||
backstage.accounts.action.manage |
Invite, change the role of, or revoke Tomoda accounts | step-up | x | ||||||
backstage.partners.read |
List partner workspaces, their members and invites | x | |||||||
backstage.partners.action.manage |
Invite an owner, change a member's role, suspend or restore a partner workspace | step-up | x | ||||||
backstage.ops.queues |
Read queue state | x | x | ||||||
backstage.ops.action.replay |
Replay or drop archived tasks, sweep orphans and re-evaluate challenges and stamps | x | x | ||||||
backstage.announcements.read |
Read announcements | x | x | x | |||||
backstage.announcements.action.publish |
Schedule, edit and withdraw announcements | x | |||||||
backstage.switches.read |
Read feature switches | x | x | x | |||||
backstage.switches.action.set |
Override a feature switch with a reason | x | |||||||
backstage.catalog.action.merge |
Merge duplicate places | x | x | ||||||
backstage.catalog.action.ranking |
Apply place ranking weights | x |
Partner
| Capability | Allows | Needs | owner | admin | member |
|---|---|---|---|---|---|
partner.workspace.read |
Read a partner workspace and its members | x | x | x | |
partner.workspace.action.manage |
Change a partner workspace and its members | x | x | ||
partner.billing.action.manage |
Handle billing and delete a partner workspace | x |
Only admin holds the account-management, plan override and ranking-weights capabilities. Clients read the caller's capabilities from GET /backstage/me and hide what the caller can't do through one can(capability) hook; the server enforces every one.
Latency vs. revocation tradeoff¶
Every gated route re-reads the database, so permission changes take effect on the next request. Tomoda access JWTs also last 15 minutes. Routes that only need a signed-in caller read the JWT claims and cannot see a demotion until the token expires.
Frontend authorization shell¶
The router mirrors the account-type split at the navigation layer:
- One active session, one shell. Each
AccountTypemounts a distinct top-level shell: standard (and synthetic) accounts see(tomoda), partner accounts thepartnershell under/partner, and a Backstage session sees(backstage)under/backstage. A given JWT renders exactly one of these shells, never two. - Capabilities, not roles, shape Backstage. Inside
(backstage), sections and actions show from the caller's capabilities (useBackstageMe(), backed byGET /backstage/me), read fresh from the server. Hiding a control is UX; every endpoint enforces its own capability. - The Backstage session sits beside the personal one. Entering Backstage swaps the active session without signing the personal account out (see On the device).
Root layout shape¶
app/_layout.tsx guards each shell with Stack.Protected on claims.account_type ((tomoda) and (capture) for standard and synthetic, partner for partner, (backstage) for tomoda). Tomoda accounts skip the profile-completion gate, since they carry no date of birth. The shells are mutually exclusive: when the active session changes (login, logout, entering or leaving Backstage), Stack.Protected unmounts the previous shell and mounts the next one fresh, so no state or stack history bleeds across identities.
Account types → router surfaces¶
| AccountType | Mounted shell | Default landing |
|---|---|---|
standard |
(tomoda) |
/discover |
tomoda |
(backstage) |
/backstage (Today) |
partner |
partner (/partner/*) |
/partner/dashboard |
synthetic |
(tomoda) |
/discover |
Linked accounts¶
A person can hold team accounts beside their standard account: a tomoda Tomoda account, a partner account, and later others. The accounts are separate users server-side, with their own ids, credentials, JWTs and refresh tokens. A link is one account_links row (personal_user_id, linked_user_id, account_type): a standard account links at most one account of each type (primary key on personal_user_id, account_type), a linked account links to one standard account (linked_user_id unique), and both sides cascade with the user. Only account types whose policy is Linkable can be linked.
Linking is optional. Someone without a regular Tomoda account can hold only a team account and sign straight into its surface with the methods its policy allows.
Why separate JWTs, not a "view" flag on one JWT?
- The active JWT is the source of truth for what the caller can do; a client-side "view" would diverge UI from server enforcement.
- The standard account's footprint stays an ordinary member's (analytics, anti-abuse, account-type filters), and team actions are attributed to the team account in the audit log.
- Switching re-authenticates the team credential, which gives a clean audit trail.
Linking from the Tomoda side¶
A Tomoda account that was created standalone, or unlinked later, links a personal account from inside Backstage by signing into it. The Tomoda account must be active and linkable, and must hold no link already.
| Step | Endpoint (JWT of the Tomoda account, StepUpLimit) |
Does |
|---|---|---|
| Step-up | POST /auth/step-up/begin {purpose: "link"} then /finish |
A fresh link token proven with the Tomoda account's own credential |
| Link | POST /auth/links/personal {step_up_token, email, password} or {step_up_token, provider, id_token, nonce?} |
Signs into the personal account the way it normally signs in (its email or username and password, or a Google or Apple ID token), then creates the account_links row; answers 201 with the personal account's session, as a sign-in would |
| Unlink | DELETE /auth/links/personal {step_up_token} |
Spends a fresh link token and removes the Tomoda account's own link; 404 when it has none |
- The same sign-in check. A password goes through
AuthService.verifyPassword, the check behindPOST /auth/login: the account's lockout budget (5 failures per 15 minutes), its sign-in policy and the failed-attempt record inlogin_histories. A Google or Apple token goes through the same ID-token verification as the social sign-ins (signature, issuer, audience, expiry, nonce) and must already be attached to an account: linking never creates one, and a valid token for an unknown identity answers like a wrong credential. Success issues the same session a sign-in does (the client keeps it as the personal session to switch back to). A standard account's sign-in needs no emailed code, so none is asked for; a type whose policy setsPasswordNeedsCode(Tomoda) is refused as a target in any case. A request carries exactly one proof, a password or a provider token. - Who can be linked. An active, non-suspended, non-deactivated
standardaccount that holds no link of this type. A Tomoda, partner or synthetic account, a suspended or deactivated account, and an account already linked to another Tomoda account all answer 400LINK_TARGET_INVALIDor 409ALREADY_LINKED. A Tomoda account that already holds a link answers 409ALREADY_LINKEDbefore any credential is checked. Accounts that only sign in with Google or Apple have no password and can't be linked this way. - The step-up is checked first and spent last. A missing, forged, expired or wrong-purpose token answers 403
STEP_UP_REQUIREDbefore the personal credentials are looked at. The token is spent only once they verify, so a typo doesn't cost a re-authentication; guessing is capped by the personal account's lockout and the per-accountStepUpLimit. - Failures are recorded. A wrong password or a token that does not verify answers 400
LINK_CREDENTIALS_INVALID(not a 401, so the Tomoda session isn't treated as expired). Refused attempts write anaudit_logslinkrow under the Tomoda actor ("Failed to link a personal account"); a failed password also counts against the personal account's lockout. - Success is audited and announced. The row is inserted in one statement, with the primary key and
linked_user_idunique index closing a concurrent link, then alinkrow (resource: the personal account) is written under the Tomoda actor and the personal account's address gets a short notice in its saved language. An unlink writes anunlinkrow. - Afterwards the Tomoda account sees "Switch to personal account" in Backstage, and the personal account sees it in the Hub linked-account rows, switching in with the step-up the policy already requires. Backstage revocation (Accounts) still removes the link as before.
Invites¶
Team accounts are created by accepting an invite into an account type with a role (auth.InviteService, table account_invites). The caller that creates it checks its own permission first: Backstage Accounts needs backstage.accounts.action.manage and a fresh step-up. The role must be one the account type's policy offers, and only the token's hash is stored.
| Step | Endpoint (optional JWT, InviteLimit: 10 per hour per IP, fails closed) |
Does |
|---|---|---|
| Preview | POST /auth/invites/preview {token} |
Account type, surface, role, status and a masked address |
| Code | POST /auth/invites/send-code {token} |
Emails a code to the invited address |
| Accept | POST /auth/invites/accept {token, code, password, name} |
Proves the address and creates the account |
Signed in on a standard account, acceptance links the new account to it. Signed out, the new account stands alone and the response carries a session for it, so the invitee lands in the new surface. A signed-in team account can't accept an invite. Tomoda accounts need an address at tomoda.life (AccountPolicy.EmailDomain), checked when the invite is created, again when it is accepted, and when the account is created. A partner invite names its workspace (account_invites.partner_id) and accepting it creates the partner account and its membership in one transaction.
Sign-in code¶
An account type whose policy sets PasswordNeedsCode (Tomoda) never signs in with a password alone. POST /auth/login checks the password under the account's lockout budget and answers 202 {code_required, challenge, email_hint} instead of tokens, after emailing a one-time code (login intent) to the account's address. POST /auth/login/code {challenge, code} spends the single-use challenge (Redis, 10 minutes, keyed by the hash of the token) and starts the session. A wrong code, an expired challenge and an unknown challenge all answer the same 401; a wrong code spends the same login failure budget as a wrong password and the per-address code attempt budget (5 per 15 minutes) maps to the lockout. Because the reset-by-email flow would hand the password to anyone reading the mailbox, these accounts cannot reset their password that way. A passkey remains the preferred method and signs in directly.
Step-up and switching¶
Every switch into a team account whose policy sets SwitchStepUp, and every sensitive change inside a team account, is re-authenticated on the server with that account's own credential. The proof is a step-up token, never a client flag.
| Step | Endpoint (JWT, StepUpLimit: 20 per 15 min per account, fails closed) |
Does |
|---|---|---|
| Links | GET /auth/links |
For a standard account: each usable linked account with its surface, home, whether switching needs a step-up and which methods it can step up with |
| Begin | POST /auth/step-up/begin {purpose, account_id?} |
Opens a 5-minute challenge for the target account; returns passkey request options when it has a passkey |
| Finish | POST /auth/step-up/finish {challenge_id, password \| credential} |
Verifies the password or passkey assertion; returns a single-use 5-minute step-up token |
| Switch | POST /auth/links/{id}/switch {step_up_token?, previous_refresh_token?} |
Spends a switch token when the policy asks for one and issues a fresh session for the linked account |
- Purpose binds caller and target.
switchis begun by the standard account and names one of its linked accounts;sensitiveis begun by a team account itself and authorizes one change (for Backstage: an invite, role change or revocation);linkis begun the same way and authorizes linking or unlinking its personal account. A token carries its purpose, the target account (sub) and the caller (act), is signed with a key derived from the JWT secret (so no other token kind verifies as one), and is marked spent in Redis on first use; if that marker can't be written, the token is refused. A token for one linked account can't open another. - Failures spend the login lockout. A wrong password or passkey records a failed login on the target account, so the per-account lockout (5 per 15 minutes) caps guessing, and every attempt writes an
audit_logsstep_uprow. If the failure count can't be read, the step-up is refused as locked out. - Sessions follow the target's policy. A Backstage session gets 15-minute access tokens, a 2-hour idle window and a 12-hour cap. Switching again needs a new step-up and starts a new chain; a previous refresh token of that account presented on switch is revoked. Each switch writes an
audit_logsswitchrow. - Standard and team sessions are independent. Switching never touches the standard session, and logging out of the team session (
/auth/logoutwith its refresh token) ends only that chain and bumps that account's token version. - The first admin is created by an operator.
task backstage:bootstrap ENV=dev|prod(cmd/backstage-bootstrap) reads the latest version oftomoda-backstage-master-password-<env>with the operator's own gcloud credentials, reaches the environment's database through a port-forward, and creates a standalone Tomoda admin at the developers mailbox in one transaction. It refuses once an admin exists.ROTATE=1(-rotate) refreshes only that account's password hash from the current secret version, ends its live sessions, and never re-activates, re-roles or re-links it, so a revocation or demotion made in Backstage stays. The secret is generated bysetup-gcp-secrets.shand is not mounted in any pod; the command never prints or logs it. Signing in still needs the code emailed to that mailbox. After the first sign-in, real Tomoda accounts are invited from Accounts.
On the device¶
- Switching. The Hub's Account section ends with one row per linked account whose surface the app knows (
components/hub/LinkedAccountRows, entries inutils/surfaces.ts), fromGET /auth/links./hub/switch/{id}runs the step-up when the link needs one (the platform passkey prompt when the account has a passkey and the device supports it, else its password), callsenterLinkedAccountwith the new session and lands on the surface's home. A partner or creator surface reuses the same rows and screen once it has an entry and strings. - Signing in directly. A Tomoda account signs in from the normal sign-in screen with its passkey; the root layout mounts Backstage for a
tomodasession either way, and Today offers sign out instead of switching back. - Invites.
/invite?token=(a public page) accepts an invite signed in or signed out: signed in, it switches into the new linked account with the password just set; signed out, it signs in with the session the server returns. - Separate storage. The personal tokens stay in
tokenStore. The linked account's refresh token lives in its own device-only keychain item (session storage on web,utils/linkedSession.ts) and its access token only in memory; neither reaches the share extension's shared keychain. One linked session is active at a time. - Leaving and expiry. "Switch to personal account" on Today returns to the personal session; leaving signs the linked session out on the server and clears its token from the device, so no staff refresh token outlives the visit. When it expires or is revoked, the app drops back to personal and shows "Backstage session ended". A cold start or web reload resumes the personal session; switching again asks for a fresh step-up. A sensitive step-up token is bound to the capability it was begun for and is accepted only by that capability's routes.
- Logging out. Inside a linked account, logout ends only that session. On the personal account it also ends any linked session kept on the device.
Where the frontend identity predicates live¶
| Predicate | Source |
|---|---|
isAuthenticated |
AuthContext (has JWT + user) |
profileIncomplete |
app/_layout.tsx (a non-Tomoda user missing username or date_of_birth) |
accountType |
AuthContext.claims.account_type (JWT-decoded). Compare against AccountTypes; user.account_type is an echo and may drift. |
linkedActive, isBackstageSession, isMemberSession |
AuthContext: a linked session entered from personal is active; the active token is a Tomoda account; signed in on a member-facing account |
| Tomoda accounts capabilities | useBackstageMe() (can(capability)) |
| Linked accounts | useAccountLinks() |
Never read JWT claims directly outside AuthContext.
Where to read next¶
- Where the
authslice sits among the backend domains: Domains. - Service-level implementation (handlers, stores, OTP internals, password-reset flow, Apple JWKS handling, refresh-token TTL logic): Backend → Auth service.
- Client-side wiring (token cache, scheduled refresh, 401 → session-expired event bus): Frontend → API Client.
- Underlying middleware chain and per-IP throttling that fronts the auth endpoints: Backend → Security.