Skip to Content
ArchitectureAuthentication

Authentication

How a caller gets a token, what the token carries, how every request checks it, how a session is refreshed and revoked, and which endpoints admit which callers. The backend keeps no user table: a session is an RS256 JWT, the identity behind it is a Repliers client or agent, the role comes from the local ACL table, and the only server-side session state is two Keyv stores, one for one-time codes and one for revoked token ids. Terms are in the Glossary.

Auth endpoints · Request lifecycle · Data ownership · Module catalogue · W9 worked trace

D03a — login and session lifecycle

One client signs in by OTP, uses the token, refreshes it and logs out. Every call shown is awaited; the only detached work in these flows is the registration event of a signup (not shown). Repliers is the upstream API; otp and blocklist are Keyv namespaces.

The other two ways in have their own, shorter sequences: OAuth and the FUB embed login.

Sessions — JWT

Issuing

Every token is signed by AuthService.generateToken (src/services/auth.ts), whatever the flow.

ClaimValueSet bySource
subMeaning depends on the flow (sub): the clientId for OTP, email-token and OAuth client sign-ins; the agentId for an OAuth agent sign-in; absent on the FUB embed tokenthe flow, as a stringsrc/services/auth.ts (useOtp, useRepliersToken, embedLogin), src/services/oauth.ts (callback, agentLogin)
emailThe client’s email; the agent’s email; on the embed token the FUB user’s email from the signed contextthe flowsame
roleA number (UserRole: Root 1, User 2, Admin 3, Agent 4), resolved as acl?.role || payload.role || User from the acl row of email. With persistence on, every token gets one. With APP_DISABLE_PERSISTENCE=true the lookup is skipped and only the embed and OAuth-agent flows set a role (Agent), so an OTP token has no role claimgenerateTokensrc/services/auth.ts (generateToken), src/repository/acl.ts (getUserAcl), src/constants.ts (UserRole)
external.fub_idOAuth agent sign-in only: the id of the first FUB user returned for the agent’s email; absent when FUB returns none or BOSS_ENABLED=falseOAuthService.agentLoginsrc/services/oauth.ts (agentLogin)
jticrypto.randomUUID(), new on every issuegenerateTokensrc/services/auth.ts (generateToken)
issJWT_ISSUER (default http://repliers-proxy)generateTokensrc/config.ts (auth.jwt.issuer)
iat, expexp from the lifetime: JWT_EXPIRE (default 30d); for a resolved role with an entry in auth.roleOverrides, that entry (Agent: AGENT_JWT_EXPIRE, default 1d), applied only when the ACL lookup runs; on refresh, the old token’s exp − iatgenerateToken, refreshsrc/services/auth.ts (generateToken, getRoleOverride, refresh), src/config.ts (auth.roleOverrides)

Keys. JWT_PRIVATE_KEY and JWT_PUBLIC_KEY hold either the PEM text itself (recognised by a leading -----BEGIN PRIVATE KEY----- / -----BEGIN PUBLIC KEY-----) or a path resolved from the backend root (npm run jwt:generate writes keys/private.pem and keys/public.pem). Both are read once per process by middleware.jwt.config.keys (src/providers/middleware/jwt/config.keys.ts); the process does not start without them (Startup prerequisites). One key pair signs and verifies every token type.

Role resolution needs the database. With persistence on, every issue (OTP, email token, OAuth, embed, refresh) awaits the acl query, and a database error fails the request with a 500. A role is never read from the request body: it comes from the acl row, the flow’s own choice or the default.

Verifying

Two middlewares, both koa-jwt with one configuration (middleware.jwt.config: the public key, algorithms: ["RS256"], the configured issuer, and isRevoked). The token is read from the Authorization: Bearer <token> header only; no cookie is configured. The decoded claims land in ctx.state["user"].

Requestmiddleware.jwt (strict)middleware.jwt.passthroughSource
No Authorization header401 Authentication Errorguest: passes, no ctx.state.userkoa-jwt lib/index.js; src/providers/middleware/jwt/passthrough.ts (middleware.jwt.passthrough)
Header not of the form Bearer <token> (other scheme, no token)401 Bad Authorization header format. …guest: the token is treated as missing (jwt must be provided)koa-jwt lib/resolvers/auth-header.js (resolveAuthorizationHeader)
Bad signature, other algorithm, other issuer, expired401 Authentication Error: <reason> (for example jwt expired)401 ApiError with the reason (401 - jwt expired - <path>)src/providers/middleware/jwt/config.ts (middleware.jwt.config), src/app.ts (HttpError branch)
jti missing or not a string401 Authentication Error: Token revoked401, reason Token revokedsrc/providers/middleware/jwt/config.ts (isRevoked)
jti in the blocklist401 Authentication Error: Token revoked401, reason Token revokedsrc/repository/blocklist.ts (isRevoked)
Validctx.state.user = claimssamesrc/providers/middleware/jwt/jwt.ts (middleware.jwt)

The strict errors are koa HttpErrors and the passthrough ones ApiErrors, so their bodies differ (error variants). Neither middleware checks the role or looks the identity up upstream.

Revocation

isRevoked (src/providers/middleware/jwt/config.ts) runs on every verified token, strict or passthrough. It returns revoked for a token without a string jti, else asks AuthService.isRevoked, which is BlocklistRepository.isRevoked → keyv.has(jti) on the blocklist namespace. Logout and refresh write jti → exp with a TTL of the token’s remaining lifetime, so an entry disappears when the token would have expired anyway. Store keys and lifetimes: Keyv stores own their data.

The otp and blocklist stores are in process memory unless REDIS_KEYV_ENABLE=true. Without Redis, a code issued by one web process cannot be exchanged on another, a logout or refresh revokes the old token only on the process that handled it, and a restart forgets every code and every revocation. Run more than one web process only with Redis-backed Keyv.

Login flows (/api/auth)

Every flow ends in generateToken. The endpoint table with statuses is on Auth endpoints; each flow’s mechanics follow.

OTP login

The sequence is D03a above; the worked values are in W9.

StepBehaviourSource
LookupuserLoginSchema requires email or phone. RepliersClients.filter({ email, phone, operator: "OR" }); the first client returned is used. None: 404 User not foundsrc/validate/auth.ts (userLoginSchema), src/services/auth.ts (login)
MailingWhen the client has preferences.email false or preferences.unsubscribe true, the client is updated to email: true, unsubscribe: false before the code is sent. A failed update: 500 Error ensuring user can receive emailsrc/services/auth.ts (login, ensureMailingAllowed)
Cooldownotp_sent_<clientId> present: 403 with Retry-After = ceil((AUTH_OTP_RESEND_TTL_MS − elapsed) / 1000) seconds, repeated in the body’s infosrc/services/auth.ts (otpSendRateOpened), src/app.ts
CodeSix digits from Codegen.generate, stored as the key with { clientId } as the value, for AUTH_OTP_TTL_MS (default 10 min). The cooldown marker is written right after, for AUTH_OTP_RESEND_TTL_MS (default 1 min)src/services/auth/codegen.ts (Codegen), src/services/auth.ts (sendOtp)
MessageRepliersMessages.send → POST /messages with the client’s agentId, sender: "agent" and content shaped by AUTH_OTP_MESSAGE_TYPE: code → the message with the code; link → the message plus AUTH_OTP_URI?code=<code>; link_and_code (default, also for an unknown value) → both. AUTH_OTP_MESSAGE_SUBJECT adds subject when set. The request names no channel; delivery is Repliers’src/services/auth.ts (formatOtpMessageContent), src/lib/config.utils.ts (parseOtpMessageType)
Response{ result: true }; with DEBUG_AUTH_OTP_EXPOSE_CODE=true also codesrc/routes/auth.ts (router.post("/login"))
ExchangeuserOtpSchema: a 6-character string. Unknown or used code: 403. Otherwise RepliersClients.get(clientId), a token with email and sub = clientId, and the profile fname, lname, phone, email, status, preferences, tags; the code is deleted after the token is signed. Response { token, profile }src/services/auth.ts (useOtp, userProfilKeys)

Rate-limit /api/auth/* in front of the backend (Limits).

DEBUG_AUTH_OTP_EXPOSE_CODE=true returns the code in the login and signup response body. Startup refuses the flag when APP_ENVIRONMENT contains prod (src/config.ts). Leave it unset on deployments with real clients.

Signup

POST /api/auth/signup validates fname, lname and email (all required), phone and the Referer header, creates a Repliers client under the default agent (REPLIERS_AGENT_ID) with email and SMS preferences on and status: true, starts a registration event without awaiting it, and then runs the OTP login for the new client (same cooldown, message and response). An existing client makes Repliers answer 409, which is relayed. Source: src/services/auth.ts (signup, reportClientRegistration); test test/routes/auth.test.ts (signup 409).

Email token

POST /api/auth/repliers-token exchanges the token of a Repliers message (a UUID) for a JWT.

CaseOutcomeSource
Body token not a UUID400src/validate/auth.ts (authRepliersTokenSchema)
AUTH_EMAILTOKEN_ENABLED not true400 Endpoint is not activatedsrc/services/auth.ts (useRepliersToken), src/config.ts (auth.emailtoken)
GET /messages?token=<uuid> finds no message403 Email token is invalidsrc/services/auth.ts (useRepliersToken), src/services/repliers/messages.ts (get)
Message sent longer ago than AUTH_EMAILTOKEN_EXPIRE (default 30d, from delivery.sentDateTime)403 Email token has expired; with AUTH_EMAILTOKEN_AUTO_OTP=true a fresh OTP is first sent to the message’s client through sendOtp and the status is 412src/services/auth.ts (useRepliersToken, sendOtp)
Otherwisea token for the message’s clientId; response { result: { token, profile } }src/services/auth.ts (useRepliersToken), src/routes/auth.ts (router.post("/repliers-token"))

OAuth sign-in

GET /api/auth/{provider}/url and POST /api/auth/{provider}/cb. router.param("provider") admits google and facebook (oauthUrlSchema, 400 otherwise), but only oauth.google is registered (src/providers/oauth/google.ts: OIDC discovery on Google’s issuer with OAUTH_GOOGLE_CLIENT_ID and OAUTH_GOOGLE_CLIENT_SECRET), so facebook fails when the service resolves its configuration.

The agent match compares emails case-insensitively among RepliersAgents.filter({ email, status: true }). A new client’s registration event is not awaited. Source: src/services/oauth.ts (url, callback, agentLogin), src/services/oauth/google.ts (OAuthGoogleAdapter).

FUB embed login

POST /api/auth/embed signs in an agent from the Follow Up Boss embedded-app context.

The response key is jwt, not token. The token passes the /api/agent role guard but has no sub:

/api/agent routesEmbed token without ?s=With a valid ?s=Source
No path parameter: POST and GET /client, GET and POST /boss/people400 from validation: agentId is required (on boss/people the missing external.fub_id is reported first)not applicable: no guard reads ssrc/routes/agent.ts (router.post("/client"), router.get('/client'), router.get('/boss/people'), router.post('/boss/people')), src/validate/agent.ts (agentIdSchema, agentGetBossPeopleSchema)
clientId parameterthe guard runs before validation; checkClient filters clients by the path id and an agent id of NaN, and no client matches: 403 (a Repliers error status is relayed instead)sub becomes the client’s agentId and the route runssrc/routes/agent.ts (router.param("clientId")), src/services/agent.ts (checkClient, checkSignature)
estimateId parameter404 for an unknown estimate, 403 without a clientId, then checkOwnership compares the owner’s agentId with an absent id: 403as for clientIdsrc/routes/agent.ts (router.param("estimateId")), src/services/estimate.ts (get, checkOwnership)

A context that passes the signature but is not base64 JSON fails with a 500. The route is mounted whatever BOSS_ENABLED says. BOSS_SYSTEM_KEY keys the signature check; set a unique secret on every deployment. Source: src/services/auth.ts (embedLogin), src/lib/boss/auth.ts (isFromFollowUpBoss), src/routes/index.ts.

Refresh and logout

EndpointBehaviourSource
POST /api/auth/refresh (strict)Copies every claim except iat, exp, iss, jti (so sub, email, role, external carry over), re-runs the role resolution, signs with the old lifetime exp − iat, then blocklists the old jti until its exp. A token without iat or exp: 500. Response { token }src/services/auth.ts (refresh)
POST /api/auth/logout (strict)Blocklists the token’s jti until its exp. Response { result: true }src/services/auth.ts (logout), src/repository/blocklist.ts (create)

Each refresh restarts the full lifetime.

Agents and roles

Roles are checked by middleware.role([...]) (src/providers/middleware/role.ts): 403 Insufficient privileges unless ctx.state.user.role is in the list. The comparison is on the number in the claim; a token with no role passes no role check.

RouterGuardRoles admittedSource
/api/agentrouter.use(middleware.jwt, middleware.role(...))Agent, Adminsrc/routes/agent.ts (router.use)
/api/adminrouter.use(middleware.jwt, middleware.role(...))Admin, Rootsrc/routes/admin.ts (router.use)
/api/vtour writes (POST, PUT, DELETE)per route; on PUT and DELETE after the slug guardAdmin, Rootsrc/routes/vtour.ts (roleMiddleware)
every other routernoneany role, or none—

Roles come from three places only: an ACL row (no code in the repository writes one), the OAuth agent sign-in (Agent) and the embed login (Agent); otherwise the default User. The ACL row wins over both flows.

Signed client links (?s=). On /api/agent routes with a clientId or estimateId path parameter, the param guard accepts a query s, a signature of the client id keyed with AUTH_AGENTS_SIGNATURE_SALT (AgentService.checkSignature, calcSignature). A valid signature loads the client and replaces ctx.state.user.sub with the client’s own agentId: the request acts as the client’s agent in place of the ownership check. An invalid one is 403 Invalid signature; without s the ownership check runs (the client’s agentId must equal sub, 403). The same signature is appended to the client links written into FUB (secureFubAvmLink). AUTH_AGENTS_SIGNATURE_SALT ships with a built-in placeholder; set a unique secret on every deployment. Source: src/routes/agent.ts (router.param("clientId"), router.param("estimateId")), src/services/agent.ts (checkSignature, checkClient), src/lib/utils.ts (calcSignature, secureFubAvmLink).

Endpoint access

One row per endpoint. Middleware: strict middleware.jwt, passthrough middleware.jwt.passthrough, none no JWT middleware; a router.param guard is named when it runs on the route. Roles: the middleware.role list, any (a valid token with any role or none) or none (no role check). Ownership: the check that ties the target to the caller, with its status, or — when the route has none. Guest: what a request without a token gets. On passthrough routes a valid token makes the caller a user and an invalid one is a 401, as above. The handler, validator and service of each endpoint are in the module catalogue.

/api/auth

EndpointMiddlewareRolesOwnershipGuestSource
GET /api/auth/{provider}/urlnone; provider guard (400)none—same response for everyonesrc/routes/auth.ts (router.get("/:provider/url"))
POST /api/auth/{provider}/cbnone; provider guard (400)nonethe provider’s verified email selects the client or agentsigns in, or creates a clientsrc/routes/auth.ts (router.post("/:provider/cb"))
POST /api/auth/loginnonenone—sends a codesrc/routes/auth.ts (router.post("/login"))
POST /api/auth/otpnonenonethe client stored with the codesigns in with a valid codesrc/routes/auth.ts (router.post("/otp"))
POST /api/auth/refreshstrictanythe token’s own claims401src/routes/auth.ts (router.post("/refresh"))
POST /api/auth/logoutstrictanythe token’s own jti401src/routes/auth.ts (router.post("/logout"))
POST /api/auth/signupnonenone—creates a client and sends a codesrc/routes/auth.ts (router.post("/signup"))
POST /api/auth/repliers-tokennonenonethe message token names the clientsigns in with a valid tokensrc/routes/auth.ts (router.post("/repliers-token"))
POST /api/auth/embednone; signature checked in the service (401)none (issues Agent)—signs in with a valid signaturesrc/routes/auth.ts (router.post("/embed")), src/services/auth.ts (embedLogin)

/api/listings

EndpointMiddlewareRolesOwnershipGuestSource
POST /api/listings/searchpassthroughnone—guest scrubbing (@scrubbed("listings"))src/routes/listings.ts (router.post("/search"))
GET /api/listings/searchpassthroughnone—guest scrubbingsrc/routes/listings.ts (router.get("/search"))
GET /api/listings/countpassthroughnone—identity not read: same resultsrc/routes/listings.ts (router.get("/count"))
POST /api/listings/countpassthroughnone—identity not readsrc/routes/listings.ts (router.post("/count"))
GET /api/listings/{mlsNumber}/similarpassthroughnone—guest scrubbing (@scrubbed("similar"))src/routes/listings.ts (router.get("/:mlsNumber/similar"))
GET /api/listings/locationspassthroughnone—identity not readsrc/routes/listings.ts (router.get("/locations"))
POST /api/listings/nlppassthroughnone—the follow-up search is guest-scrubbed; the NLP result is not decoratedsrc/routes/listings.ts (router.post('/nlp'))
GET /api/listings/lastUpdatedOn (Not in OSS)passthroughnone—identity not readsrc/routes/listings.ts (router.get('/lastUpdatedOn'))
GET /api/listings/featured/{slug}passthroughnone—guest scrubbingsrc/routes/listings.ts (router.get('/featured/:slug'))
GET /api/listings/historypassthroughnone—guest scrubbing per record (@scrubbed("history"))src/routes/listings.ts (router.get("/history"))
GET /api/listings/{mlsNumber}passthroughnone (the view event skips role Agent)—guest scrubbing; no view eventsrc/routes/listings.ts (router.get('/:mlsNumber'))

/api/autosuggest, /api/locations, /api/buildings, /api/stats

EndpointMiddlewareRolesOwnershipGuestSource
GET /api/autosuggestpassthroughnone—listing results guest-scrubbedsrc/routes/autosuggest.ts (router.get("/"))
GET /api/autosuggest/locationsnonenone—no identity readsrc/routes/autosuggest.ts (router.get("/locations"))
GET /api/autosuggest/addressnonenone—no identity readsrc/routes/autosuggest.ts (router.get('/address'))
GET /api/locationspassthroughnone—identity not readsrc/routes/locations.ts (router.get("/"))
GET /api/locations/autocompletepassthroughnone—identity not readsrc/routes/locations.ts (router.get("/autocomplete"))
POST /api/buildingsnonenone—no identity readsrc/routes/buildings.ts (router.post("/"))
GET /api/buildingsnonenone—no identity readsrc/routes/buildings.ts (router.get("/"))
GET /api/buildings/{addressKey}nonenone—no identity readsrc/routes/buildings.ts (router.get("/:addressKey"))
GET /api/stats/widgetspassthroughnone—identity not readsrc/routes/stats.ts (router.get("/widgets"))
GET /api/stats/neighborhoodsranking (Not in OSS)passthroughnone—a fixed stub, no upstream callsrc/routes/stats.ts (router.get("/neighborhoodsranking")), src/services/stats.ts (neighborhoodsranking)
GET /api/stats/communitiesnonenone—no identity readsrc/routes/stats.ts (router.get("/communities"))

/api/favorites, /api/searches, /api/contact

EndpointMiddlewareRolesOwnershipGuestSource
POST /api/favoritesstrictanycreated for sub401src/routes/favorites.ts (router.post("/"))
GET /api/favoritesstrictanythe list of sub401src/routes/favorites.ts (router.get("/"))
DELETE /api/favorites/{favoriteId}strictanyservice: the id must be in the caller’s list (400)401src/routes/favorites.ts (router.delete("/:favoriteId")), src/services/favorites.ts (delete)
POST /api/searchesstrictanycreated for sub401src/routes/searches.ts (router.post("/"))
PATCH /api/searches/{searchId}strictany—401src/routes/searches.ts (router.patch("/:searchId"))
GET /api/searchesstrictanythe searches of sub401src/routes/searches.ts (router.get("/"))
DELETE /api/searches/{searchId}strictanyservice: the id must be in the caller’s searches (400)401src/routes/searches.ts (router.delete("/:searchId")), src/services/searches.ts (delete)
GET /api/searches/{searchId}passthroughnone—identity not readsrc/routes/searches.ts (router.get("/:searchId"))
POST /api/contact/contactuspassthroughnone—sent as the REPLIERS_UNAUTHENTICATED_CLIENT_ID client to the default agent; event reported for guests toosrc/routes/contact.ts (router.post("/contactus")), src/services/contact.ts (defaultMessageFields)
POST /api/contact/schedulepassthroughnone—as contactussrc/routes/contact.ts (router.post("/schedule"))
POST /api/contact/schedule/estimatepassthroughnone—message and CRM note under the guest clientsrc/routes/contact.ts (router.post("/schedule/estimate")), src/services/contact.ts (scheduleEstimate)
POST /api/contact/requestinfopassthroughnone—as contactussrc/routes/contact.ts (router.post("/requestinfo"))
POST /api/contact/subscribe/newsletterpassthroughnone—event reported for guests toosrc/routes/contact.ts (router.post("/subscribe/newsletter"))

/api/user

EndpointMiddlewareRolesOwnershipGuestSource
PATCH /api/userstrictanythe client sub401src/routes/user.ts (router.patch("/"))
GET /api/user/mestrictanythe client sub401src/routes/user.ts (router.get("/me"))
GET /api/user/agentpassthroughnonethe agent of the client subthe default agent (REPLIERS_AGENT_ID)src/routes/user.ts (router.get("/agent")), src/services/user.ts (agent)
POST /api/user/assets/{type}strictanyrows keyed by the token’s email401src/routes/user/assets.ts (router.post('/:type'))
GET /api/user/assets/{type}strictanythe token’s email401src/routes/user/assets.ts (router.get('/:type'))
POST /api/user/assets/{type}/removestrictanythe token’s email401src/routes/user/assets.ts (router.post('/:type/remove'))
GET /api/user/social/{provider}/urlstrictany—401src/routes/user/social.ts (router.get("/:provider/url"))
GET /api/user/social/{provider}/cbstrictanytokens stored under the token’s email401src/routes/user/social.ts (router.get("/:provider/cb"))
GET /api/user/social/{provider}/refreshstrictanythe token’s email401src/routes/user/social.ts (router.get("/:provider/refresh"))
GET /api/user/social/{provider}strictanythe token’s email401src/routes/user/social.ts (router.get("/{:provider}"))
DELETE /api/user/social/{provider}strictanythe token’s email401src/routes/user/social.ts (router.delete("/:provider"))
POST /api/user/boss/tagstrictanythe FUB person linked to the client sub (externalId)401src/routes/user/boss.ts (router.post("/tag"))

/api/estimate

EndpointMiddlewareRolesOwnershipGuestSource
POST /api/estimatepassthroughnonethe new estimate belongs to subcreated with no clientId (owned by nobody); data withheld upstream and applied locally; event and note reported for guests toosrc/routes/estimate.ts (router.post("/")), src/services/estimate.ts (add)
PATCH /api/estimate/{estimateId}strict, then assertOwnershipanythe estimate must exist (404); sub must equal its clientId (403)401src/routes/estimate.ts (assertOwnership), src/services/estimate.ts (checkOwnership, get)
GET /api/estimatepassthroughnone—same estimate; no view eventsrc/routes/estimate.ts (router.get("/"))
GET /api/estimate/mystrictanythe estimates of sub401src/routes/estimate.ts (router.get("/my"))
DELETE /api/estimate/{estimateId}strict, then assertOwnershipanythe estimate must exist (404); sub must equal its clientId (403)401src/routes/estimate.ts (assertOwnership), src/services/estimate.ts (checkOwnership, get)
GET /api/estimate/property_detailspassthroughnonea signed-in caller’s own estimates are read for the mergeno previous-estimate mergesrc/routes/estimate.ts (router.get("/property_details")), src/services/estimate.ts (propertyDetails)

/api/vtour, /api/agent, /api/admin, /api/webhooks

On /api/vtour the slug guard runs before the route’s JWT and role middleware; on /api/agent the router.use guard runs before the clientId and estimateId guards.

EndpointMiddlewareRolesOwnershipGuestSource
POST /api/vtourstrictAdmin, Rootowner_id = sub401src/routes/vtour.ts (router.post("/"))
DELETE /api/vtour/{slug}slug guard (400, 404), then strictAdmin, Rootvalidator: the tour’s owner_id must equal sub (400)400 or 404 from the guard, else 401src/routes/vtour.ts (router.param("slug"), router.del("/:slug")), src/validate/vtour.ts (vtourRemoveSchema)
PUT /api/vtour/{slug}slug guard (400, 404), then strictAdmin, Rootvalidator: owner_id must equal sub (400)400 or 404 from the guard, else 401src/routes/vtour.ts (router.put("/:slug")), src/validate/vtour.ts (vtourUpdateSchema)
GET /api/vtour/{slug}slug guard (400, 404), then strictany—400 or 404 from the guard, else 401src/routes/vtour.ts (router.get("/:slug"))
POST /api/agent/clientstrictAgent, Admincreated with agentId = sub; 400 for a token without sub401src/routes/agent.ts (router.post("/client"))
GET /api/agent/clientstrictAgent, Adminclients filtered by agentId = sub; 400 for a token without sub401src/routes/agent.ts (router.get('/client'))
GET /api/agent/client/{clientId}strict; clientId guardAgent, Admin?s= signature, else the client’s agentId must equal sub (403, also for a token without sub)401src/routes/agent.ts (router.param("clientId"))
PATCH /api/agent/client/{clientId}strict; clientId guardAgent, Adminas above401src/routes/agent.ts (router.patch('/client/:clientId'))
POST /api/agent/estimate/{clientId}strict; clientId guardAgent, Adminas above401src/routes/agent.ts (router.post("/estimate/:clientId"))
GET /api/agent/estimate/{clientId}strict; clientId guardAgent, Adminas above401src/routes/agent.ts (router.get("/estimate/:clientId"))
POST /api/agent/estimate/{estimateId}/sendstrict; estimateId guardAgent, Adminthe estimate must exist (404) and have a clientId (403); ?s= signature, else the owner’s agentId must equal sub (403, also for a token without sub)401src/routes/agent.ts (router.param("estimateId")), src/services/estimate.ts (get, checkOwnership)
PATCH /api/agent/estimate/{estimateId}strict; estimateId guardAgent, Adminas above401src/routes/agent.ts (router.patch("/estimate/:estimateId"))
DELETE /api/agent/estimate/{estimateId}strict; estimateId guardAgent, Adminas above401src/routes/agent.ts (router.delete("/estimate/:estimateId"))
POST /api/agent/messages/{clientId}strict; clientId guardAgent, Adminas for client/{clientId}401src/routes/agent.ts (router.post("/messages/:clientId"))
GET /api/agent/messages/{clientId}strict; clientId guardAgent, Adminas for client/{clientId}401src/routes/agent.ts (router.get("/messages/:clientId"))
GET /api/agent/boss/peoplestrictAgent, AdminFUB people assigned to the claim external.fub_id (400 without it)401src/routes/agent.ts (router.get('/boss/people'))
POST /api/agent/boss/peoplestrictAgent, Adminas above401src/routes/agent.ts (router.post('/boss/people'))
GET /api/admin/agentsstrictAdmin, Root—401src/routes/admin.ts (router.get('/agents'))
POST /api/admin/agentsstrictAdmin, Root—401src/routes/admin.ts (router.post('/agents'))
PATCH /api/admin/agents/{agentId}strictAdmin, Root—401src/routes/admin.ts (router.patch('/agents/:agentId'))
POST /api/webhooks/boss/peoplenone; FUB signature: fub-signature must equal the hex HMAC-SHA256 of the base64-encoded raw body, keyed with BOSS_SYSTEM_KEY (401)none—no JWT read; 401 without a valid signaturesrc/routes/webhooks/boss.ts (router.post('/people')), src/providers/middleware/boss.webhook.auth.ts

Hardening layers

What surrounds authentication in the middleware chain; the order and the per-environment switches are on Request lifecycle.

  • helmet headers and the koa-sslify HTTPS redirect, both only when NODE_ENV is production, which is also its value when unset (src/providers/middleware/helmet.ts, sslify.ts, src/config.ts env).
  • CORS (src/providers/middleware/cors.ts): in production the request origin is reflected when it matches an entry of APP_CORS_DOMAIN (comma-separated), otherwise the first entry of the allow-list is sent, a built-in URL that precedes the APP_CORS_DOMAIN entries; outside production *. Tokens travel in the Authorization header, not in cookies.
  • xss sanitization of the parsed body, the headers and the query (src/lib/middleware/xss.ts); the FUB webhook signature is checked against the raw body, which the body parser keeps aside before sanitization.
  • The OTP resend cooldown and the token blocklist above. Rate-limit /api/auth/* in front of the backend (Limits).
  • Outbound Repliers throttling protects the upstream quota, not the login endpoints (Repliers proxy).

Side effects and failures

FlowCommitted before a later failureFailure outcomeSource
OTP loginThe mailing-preferences update; the code and the cooldown marker are stored before POST /messagesA failed message send leaves the cooldown in place: a retry inside it gets 403 with Retry-Aftersrc/services/auth.ts (login, sendOtp)
SignupThe Repliers client; the detached registration eventA failed send after the create leaves the client; a second signup gets Repliers’ 409src/services/auth.ts (signup, reportClientRegistration)
OTP exchangeNothing until the token is signed; the code is deleted lastA failed ACL query or client read keeps the code usable until its TTLsrc/services/auth.ts (useOtp)
Email token with auto_otpA new code, its cooldown marker and the messageThe request still fails with 412; inside the cooldown it fails with the cooldown’s 403 insteadsrc/services/auth.ts (useRepliersToken, sendOtp)
RefreshThe new token is signed before the old jti is blocklistedA blocklist write failure returns 500; the new token is not deliveredsrc/services/auth.ts (refresh), src/repository/blocklist.ts (create)
OAuth first sign-inThe new Repliers clientA later failure leaves the client; the next sign-in finds itsrc/services/oauth.ts (callback)

Variation

  • Persistence off (APP_DISABLE_PERSISTENCE=true): no ACL lookup; no role on OTP, email-token and OAuth-client tokens; no role-based lifetime (agent tokens get JWT_EXPIRE). Routes with middleware.role answer 403 to tokens without a role.
  • Redis off: both stores per process (see the callout above).
  • BOSS_ENABLED=false: an OAuth agent token has no external.fub_id, so the FUB people routes answer 400; the embed and webhook signatures are still checked.
  • Email tokens off (the default): POST /api/auth/repliers-token answers 400.
  • Export variants: no authentication code sits in an @oss-remove or @export-only region; the two Not in OSS rows of the register are listing and statistics routes.

Evidence

  • Source: the files named in each table; koa-jwt 4.0.4 (lib/index.js, lib/resolvers/auth-header.js) for the header handling and the revocation error; openid-client 6.8.7 for the OAuth checks.
  • Tests: test/routes/auth.test.ts (signup 409, unknown-user 404, cooldown 403 with 0 < Retry-After ≤ 60, wrong code 403), test/services/auth.test.ts (message shapes), test/routes/oauth.test.ts. Run on 2026-10-20 with nock-mocked upstreams and no database: the tests that issue no token passed; the two that issue one failed with 500 on the ACL query, the dependency described under Issuing.
  • Not executed: no auth endpoint was called against a live upstream, because they send messages or create clients. Repliers’ delivery of sender: "agent" messages and the frontend’s use of the embed clientSignature are not established by this checkout.

Gotchas

  1. A malformed Authorization header is a guest on passthrough routes but a 401 on strict ones: koa-jwt drops a non-Bearer header silently when passthrough is set. Source: src/providers/middleware/jwt/passthrough.ts (middleware.jwt.passthrough), koa-jwt lib/resolvers/auth-header.js (resolveAuthorizationHeader).
  2. After a signed ?s= link, sub is a number. The guard assigns the client’s numeric agentId to ctx.state.user.sub; every issued token carries sub as a string. Source: src/routes/agent.ts (router.param("clientId"), router.param("estimateId")), src/services/agent.ts (checkSignature).

Verified against portal-backend 997ae3e, 2026-10-20.

Last updated on