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.
| Claim | Value | Set by | Source |
|---|---|---|---|
sub | Meaning 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 token | the flow, as a string | src/services/auth.ts (useOtp, useRepliersToken, embedLogin), src/services/oauth.ts (callback, agentLogin) |
email | The client’s email; the agent’s email; on the embed token the FUB user’s email from the signed context | the flow | same |
role | A 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 claim | generateToken | src/services/auth.ts (generateToken), src/repository/acl.ts (getUserAcl), src/constants.ts (UserRole) |
external.fub_id | OAuth 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=false | OAuthService.agentLogin | src/services/oauth.ts (agentLogin) |
jti | crypto.randomUUID(), new on every issue | generateToken | src/services/auth.ts (generateToken) |
iss | JWT_ISSUER (default http://repliers-proxy) | generateToken | src/config.ts (auth.jwt.issuer) |
iat, exp | exp 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 − iat | generateToken, refresh | src/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"].
| Request | middleware.jwt (strict) | middleware.jwt.passthrough | Source |
|---|---|---|---|
No Authorization header | 401 Authentication Error | guest: passes, no ctx.state.user | koa-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, expired | 401 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 string | 401 Authentication Error: Token revoked | 401, reason Token revoked | src/providers/middleware/jwt/config.ts (isRevoked) |
jti in the blocklist | 401 Authentication Error: Token revoked | 401, reason Token revoked | src/repository/blocklist.ts (isRevoked) |
| Valid | ctx.state.user = claims | same | src/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.
| Step | Behaviour | Source |
|---|---|---|
| Lookup | userLoginSchema requires email or phone. RepliersClients.filter({ email, phone, operator: "OR" }); the first client returned is used. None: 404 User not found | src/validate/auth.ts (userLoginSchema), src/services/auth.ts (login) |
| Mailing | When 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 email | src/services/auth.ts (login, ensureMailingAllowed) |
| Cooldown | otp_sent_<clientId> present: 403 with Retry-After = ceil((AUTH_OTP_RESEND_TTL_MS − elapsed) / 1000) seconds, repeated in the body’s info | src/services/auth.ts (otpSendRateOpened), src/app.ts |
| Code | Six 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) |
| Message | RepliersMessages.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 code | src/routes/auth.ts (router.post("/login")) |
| Exchange | userOtpSchema: 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.
| Case | Outcome | Source |
|---|---|---|
Body token not a UUID | 400 | src/validate/auth.ts (authRepliersTokenSchema) |
AUTH_EMAILTOKEN_ENABLED not true | 400 Endpoint is not activated | src/services/auth.ts (useRepliersToken), src/config.ts (auth.emailtoken) |
GET /messages?token=<uuid> finds no message | 403 Email token is invalid | src/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 412 | src/services/auth.ts (useRepliersToken, sendOtp) |
| Otherwise | a 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 routes | Embed token without ?s= | With a valid ?s= | Source |
|---|---|---|---|
No path parameter: POST and GET /client, GET and POST /boss/people | 400 from validation: agentId is required (on boss/people the missing external.fub_id is reported first) | not applicable: no guard reads s | src/routes/agent.ts (router.post("/client"), router.get('/client'), router.get('/boss/people'), router.post('/boss/people')), src/validate/agent.ts (agentIdSchema, agentGetBossPeopleSchema) |
clientId parameter | the 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 runs | src/routes/agent.ts (router.param("clientId")), src/services/agent.ts (checkClient, checkSignature) |
estimateId parameter | 404 for an unknown estimate, 403 without a clientId, then checkOwnership compares the owner’s agentId with an absent id: 403 | as for clientId | src/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
| Endpoint | Behaviour | Source |
|---|---|---|
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.
| Router | Guard | Roles admitted | Source |
|---|---|---|---|
/api/agent | router.use(middleware.jwt, middleware.role(...)) | Agent, Admin | src/routes/agent.ts (router.use) |
/api/admin | router.use(middleware.jwt, middleware.role(...)) | Admin, Root | src/routes/admin.ts (router.use) |
/api/vtour writes (POST, PUT, DELETE) | per route; on PUT and DELETE after the slug guard | Admin, Root | src/routes/vtour.ts (roleMiddleware) |
| every other router | none | any 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
| Endpoint | Middleware | Roles | Ownership | Guest | Source |
|---|---|---|---|---|---|
GET /api/auth/{provider}/url | none; provider guard (400) | none | — | same response for everyone | src/routes/auth.ts (router.get("/:provider/url")) |
POST /api/auth/{provider}/cb | none; provider guard (400) | none | the provider’s verified email selects the client or agent | signs in, or creates a client | src/routes/auth.ts (router.post("/:provider/cb")) |
POST /api/auth/login | none | none | — | sends a code | src/routes/auth.ts (router.post("/login")) |
POST /api/auth/otp | none | none | the client stored with the code | signs in with a valid code | src/routes/auth.ts (router.post("/otp")) |
POST /api/auth/refresh | strict | any | the token’s own claims | 401 | src/routes/auth.ts (router.post("/refresh")) |
POST /api/auth/logout | strict | any | the token’s own jti | 401 | src/routes/auth.ts (router.post("/logout")) |
POST /api/auth/signup | none | none | — | creates a client and sends a code | src/routes/auth.ts (router.post("/signup")) |
POST /api/auth/repliers-token | none | none | the message token names the client | signs in with a valid token | src/routes/auth.ts (router.post("/repliers-token")) |
POST /api/auth/embed | none; signature checked in the service (401) | none (issues Agent) | — | signs in with a valid signature | src/routes/auth.ts (router.post("/embed")), src/services/auth.ts (embedLogin) |
/api/listings
| Endpoint | Middleware | Roles | Ownership | Guest | Source |
|---|---|---|---|---|---|
POST /api/listings/search | passthrough | none | — | guest scrubbing (@scrubbed("listings")) | src/routes/listings.ts (router.post("/search")) |
GET /api/listings/search | passthrough | none | — | guest scrubbing | src/routes/listings.ts (router.get("/search")) |
GET /api/listings/count | passthrough | none | — | identity not read: same result | src/routes/listings.ts (router.get("/count")) |
POST /api/listings/count | passthrough | none | — | identity not read | src/routes/listings.ts (router.post("/count")) |
GET /api/listings/{mlsNumber}/similar | passthrough | none | — | guest scrubbing (@scrubbed("similar")) | src/routes/listings.ts (router.get("/:mlsNumber/similar")) |
GET /api/listings/locations | passthrough | none | — | identity not read | src/routes/listings.ts (router.get("/locations")) |
POST /api/listings/nlp | passthrough | none | — | the follow-up search is guest-scrubbed; the NLP result is not decorated | src/routes/listings.ts (router.post('/nlp')) |
GET /api/listings/lastUpdatedOn (Not in OSS) | passthrough | none | — | identity not read | src/routes/listings.ts (router.get('/lastUpdatedOn')) |
GET /api/listings/featured/{slug} | passthrough | none | — | guest scrubbing | src/routes/listings.ts (router.get('/featured/:slug')) |
GET /api/listings/history | passthrough | none | — | guest scrubbing per record (@scrubbed("history")) | src/routes/listings.ts (router.get("/history")) |
GET /api/listings/{mlsNumber} | passthrough | none (the view event skips role Agent) | — | guest scrubbing; no view event | src/routes/listings.ts (router.get('/:mlsNumber')) |
/api/autosuggest, /api/locations, /api/buildings, /api/stats
| Endpoint | Middleware | Roles | Ownership | Guest | Source |
|---|---|---|---|---|---|
GET /api/autosuggest | passthrough | none | — | listing results guest-scrubbed | src/routes/autosuggest.ts (router.get("/")) |
GET /api/autosuggest/locations | none | none | — | no identity read | src/routes/autosuggest.ts (router.get("/locations")) |
GET /api/autosuggest/address | none | none | — | no identity read | src/routes/autosuggest.ts (router.get('/address')) |
GET /api/locations | passthrough | none | — | identity not read | src/routes/locations.ts (router.get("/")) |
GET /api/locations/autocomplete | passthrough | none | — | identity not read | src/routes/locations.ts (router.get("/autocomplete")) |
POST /api/buildings | none | none | — | no identity read | src/routes/buildings.ts (router.post("/")) |
GET /api/buildings | none | none | — | no identity read | src/routes/buildings.ts (router.get("/")) |
GET /api/buildings/{addressKey} | none | none | — | no identity read | src/routes/buildings.ts (router.get("/:addressKey")) |
GET /api/stats/widgets | passthrough | none | — | identity not read | src/routes/stats.ts (router.get("/widgets")) |
GET /api/stats/neighborhoodsranking (Not in OSS) | passthrough | none | — | a fixed stub, no upstream call | src/routes/stats.ts (router.get("/neighborhoodsranking")), src/services/stats.ts (neighborhoodsranking) |
GET /api/stats/communities | none | none | — | no identity read | src/routes/stats.ts (router.get("/communities")) |
/api/favorites, /api/searches, /api/contact
| Endpoint | Middleware | Roles | Ownership | Guest | Source |
|---|---|---|---|---|---|
POST /api/favorites | strict | any | created for sub | 401 | src/routes/favorites.ts (router.post("/")) |
GET /api/favorites | strict | any | the list of sub | 401 | src/routes/favorites.ts (router.get("/")) |
DELETE /api/favorites/{favoriteId} | strict | any | service: the id must be in the caller’s list (400) | 401 | src/routes/favorites.ts (router.delete("/:favoriteId")), src/services/favorites.ts (delete) |
POST /api/searches | strict | any | created for sub | 401 | src/routes/searches.ts (router.post("/")) |
PATCH /api/searches/{searchId} | strict | any | — | 401 | src/routes/searches.ts (router.patch("/:searchId")) |
GET /api/searches | strict | any | the searches of sub | 401 | src/routes/searches.ts (router.get("/")) |
DELETE /api/searches/{searchId} | strict | any | service: the id must be in the caller’s searches (400) | 401 | src/routes/searches.ts (router.delete("/:searchId")), src/services/searches.ts (delete) |
GET /api/searches/{searchId} | passthrough | none | — | identity not read | src/routes/searches.ts (router.get("/:searchId")) |
POST /api/contact/contactus | passthrough | none | — | sent as the REPLIERS_UNAUTHENTICATED_CLIENT_ID client to the default agent; event reported for guests too | src/routes/contact.ts (router.post("/contactus")), src/services/contact.ts (defaultMessageFields) |
POST /api/contact/schedule | passthrough | none | — | as contactus | src/routes/contact.ts (router.post("/schedule")) |
POST /api/contact/schedule/estimate | passthrough | none | — | message and CRM note under the guest client | src/routes/contact.ts (router.post("/schedule/estimate")), src/services/contact.ts (scheduleEstimate) |
POST /api/contact/requestinfo | passthrough | none | — | as contactus | src/routes/contact.ts (router.post("/requestinfo")) |
POST /api/contact/subscribe/newsletter | passthrough | none | — | event reported for guests too | src/routes/contact.ts (router.post("/subscribe/newsletter")) |
/api/user
| Endpoint | Middleware | Roles | Ownership | Guest | Source |
|---|---|---|---|---|---|
PATCH /api/user | strict | any | the client sub | 401 | src/routes/user.ts (router.patch("/")) |
GET /api/user/me | strict | any | the client sub | 401 | src/routes/user.ts (router.get("/me")) |
GET /api/user/agent | passthrough | none | the agent of the client sub | the default agent (REPLIERS_AGENT_ID) | src/routes/user.ts (router.get("/agent")), src/services/user.ts (agent) |
POST /api/user/assets/{type} | strict | any | rows keyed by the token’s email | 401 | src/routes/user/assets.ts (router.post('/:type')) |
GET /api/user/assets/{type} | strict | any | the token’s email | 401 | src/routes/user/assets.ts (router.get('/:type')) |
POST /api/user/assets/{type}/remove | strict | any | the token’s email | 401 | src/routes/user/assets.ts (router.post('/:type/remove')) |
GET /api/user/social/{provider}/url | strict | any | — | 401 | src/routes/user/social.ts (router.get("/:provider/url")) |
GET /api/user/social/{provider}/cb | strict | any | tokens stored under the token’s email | 401 | src/routes/user/social.ts (router.get("/:provider/cb")) |
GET /api/user/social/{provider}/refresh | strict | any | the token’s email | 401 | src/routes/user/social.ts (router.get("/:provider/refresh")) |
GET /api/user/social/{provider} | strict | any | the token’s email | 401 | src/routes/user/social.ts (router.get("/{:provider}")) |
DELETE /api/user/social/{provider} | strict | any | the token’s email | 401 | src/routes/user/social.ts (router.delete("/:provider")) |
POST /api/user/boss/tag | strict | any | the FUB person linked to the client sub (externalId) | 401 | src/routes/user/boss.ts (router.post("/tag")) |
/api/estimate
| Endpoint | Middleware | Roles | Ownership | Guest | Source |
|---|---|---|---|---|---|
POST /api/estimate | passthrough | none | the new estimate belongs to sub | created with no clientId (owned by nobody); data withheld upstream and applied locally; event and note reported for guests too | src/routes/estimate.ts (router.post("/")), src/services/estimate.ts (add) |
PATCH /api/estimate/{estimateId} | strict, then assertOwnership | any | the estimate must exist (404); sub must equal its clientId (403) | 401 | src/routes/estimate.ts (assertOwnership), src/services/estimate.ts (checkOwnership, get) |
GET /api/estimate | passthrough | none | — | same estimate; no view event | src/routes/estimate.ts (router.get("/")) |
GET /api/estimate/my | strict | any | the estimates of sub | 401 | src/routes/estimate.ts (router.get("/my")) |
DELETE /api/estimate/{estimateId} | strict, then assertOwnership | any | the estimate must exist (404); sub must equal its clientId (403) | 401 | src/routes/estimate.ts (assertOwnership), src/services/estimate.ts (checkOwnership, get) |
GET /api/estimate/property_details | passthrough | none | a signed-in caller’s own estimates are read for the merge | no previous-estimate merge | src/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.
| Endpoint | Middleware | Roles | Ownership | Guest | Source |
|---|---|---|---|---|---|
POST /api/vtour | strict | Admin, Root | owner_id = sub | 401 | src/routes/vtour.ts (router.post("/")) |
DELETE /api/vtour/{slug} | slug guard (400, 404), then strict | Admin, Root | validator: the tour’s owner_id must equal sub (400) | 400 or 404 from the guard, else 401 | src/routes/vtour.ts (router.param("slug"), router.del("/:slug")), src/validate/vtour.ts (vtourRemoveSchema) |
PUT /api/vtour/{slug} | slug guard (400, 404), then strict | Admin, Root | validator: owner_id must equal sub (400) | 400 or 404 from the guard, else 401 | src/routes/vtour.ts (router.put("/:slug")), src/validate/vtour.ts (vtourUpdateSchema) |
GET /api/vtour/{slug} | slug guard (400, 404), then strict | any | — | 400 or 404 from the guard, else 401 | src/routes/vtour.ts (router.get("/:slug")) |
POST /api/agent/client | strict | Agent, Admin | created with agentId = sub; 400 for a token without sub | 401 | src/routes/agent.ts (router.post("/client")) |
GET /api/agent/client | strict | Agent, Admin | clients filtered by agentId = sub; 400 for a token without sub | 401 | src/routes/agent.ts (router.get('/client')) |
GET /api/agent/client/{clientId} | strict; clientId guard | Agent, Admin | ?s= signature, else the client’s agentId must equal sub (403, also for a token without sub) | 401 | src/routes/agent.ts (router.param("clientId")) |
PATCH /api/agent/client/{clientId} | strict; clientId guard | Agent, Admin | as above | 401 | src/routes/agent.ts (router.patch('/client/:clientId')) |
POST /api/agent/estimate/{clientId} | strict; clientId guard | Agent, Admin | as above | 401 | src/routes/agent.ts (router.post("/estimate/:clientId")) |
GET /api/agent/estimate/{clientId} | strict; clientId guard | Agent, Admin | as above | 401 | src/routes/agent.ts (router.get("/estimate/:clientId")) |
POST /api/agent/estimate/{estimateId}/send | strict; estimateId guard | Agent, Admin | the 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) | 401 | src/routes/agent.ts (router.param("estimateId")), src/services/estimate.ts (get, checkOwnership) |
PATCH /api/agent/estimate/{estimateId} | strict; estimateId guard | Agent, Admin | as above | 401 | src/routes/agent.ts (router.patch("/estimate/:estimateId")) |
DELETE /api/agent/estimate/{estimateId} | strict; estimateId guard | Agent, Admin | as above | 401 | src/routes/agent.ts (router.delete("/estimate/:estimateId")) |
POST /api/agent/messages/{clientId} | strict; clientId guard | Agent, Admin | as for client/{clientId} | 401 | src/routes/agent.ts (router.post("/messages/:clientId")) |
GET /api/agent/messages/{clientId} | strict; clientId guard | Agent, Admin | as for client/{clientId} | 401 | src/routes/agent.ts (router.get("/messages/:clientId")) |
GET /api/agent/boss/people | strict | Agent, Admin | FUB people assigned to the claim external.fub_id (400 without it) | 401 | src/routes/agent.ts (router.get('/boss/people')) |
POST /api/agent/boss/people | strict | Agent, Admin | as above | 401 | src/routes/agent.ts (router.post('/boss/people')) |
GET /api/admin/agents | strict | Admin, Root | — | 401 | src/routes/admin.ts (router.get('/agents')) |
POST /api/admin/agents | strict | Admin, Root | — | 401 | src/routes/admin.ts (router.post('/agents')) |
PATCH /api/admin/agents/{agentId} | strict | Admin, Root | — | 401 | src/routes/admin.ts (router.patch('/agents/:agentId')) |
POST /api/webhooks/boss/people | none; 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 signature | src/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_ENVisproduction, which is also its value when unset (src/providers/middleware/helmet.ts,sslify.ts,src/config.tsenv). - CORS (
src/providers/middleware/cors.ts): in production the request origin is reflected when it matches an entry ofAPP_CORS_DOMAIN(comma-separated), otherwise the first entry of the allow-list is sent, a built-in URL that precedes theAPP_CORS_DOMAINentries; outside production*. Tokens travel in theAuthorizationheader, 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
| Flow | Committed before a later failure | Failure outcome | Source |
|---|---|---|---|
| OTP login | The mailing-preferences update; the code and the cooldown marker are stored before POST /messages | A failed message send leaves the cooldown in place: a retry inside it gets 403 with Retry-After | src/services/auth.ts (login, sendOtp) |
| Signup | The Repliers client; the detached registration event | A failed send after the create leaves the client; a second signup gets Repliers’ 409 | src/services/auth.ts (signup, reportClientRegistration) |
| OTP exchange | Nothing until the token is signed; the code is deleted last | A failed ACL query or client read keeps the code usable until its TTL | src/services/auth.ts (useOtp) |
Email token with auto_otp | A new code, its cooldown marker and the message | The request still fails with 412; inside the cooldown it fails with the cooldown’s 403 instead | src/services/auth.ts (useRepliersToken, sendOtp) |
| Refresh | The new token is signed before the old jti is blocklisted | A blocklist write failure returns 500; the new token is not delivered | src/services/auth.ts (refresh), src/repository/blocklist.ts (create) |
| OAuth first sign-in | The new Repliers client | A later failure leaves the client; the next sign-in finds it | src/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 getJWT_EXPIRE). Routes withmiddleware.roleanswer 403 to tokens without a role. - Redis off: both stores per process (see the callout above).
BOSS_ENABLED=false: an OAuth agent token has noexternal.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-tokenanswers 400. - Export variants: no authentication code sits in an
@oss-removeor@export-onlyregion; the two Not in OSS rows of the register are listing and statistics routes.
Evidence
- Source: the files named in each table;
koa-jwt4.0.4 (lib/index.js,lib/resolvers/auth-header.js) for the header handling and the revocation error;openid-client6.8.7 for the OAuth checks. - Tests:
test/routes/auth.test.ts(signup 409, unknown-user 404, cooldown 403 with0 < 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 embedclientSignatureare not established by this checkout.
Gotchas
- A malformed
Authorizationheader is a guest on passthrough routes but a 401 on strict ones:koa-jwtdrops a non-Bearerheader silently whenpassthroughis set. Source:src/providers/middleware/jwt/passthrough.ts(middleware.jwt.passthrough),koa-jwtlib/resolvers/auth-header.js(resolveAuthorizationHeader). - After a signed
?s=link,subis a number. The guard assigns the client’s numericagentIdtoctx.state.user.sub; every issued token carriessubas 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.