Skip to Content
gentlemans-stack
ReferenceServices

iam-service

Generated Hono/oRPC service that includes health, Scalar docs, OpenAPI, RPC, and REST transports, an in-process session middleware (Better Auth getSession, cookie or bearer), and the workspace procedures (workspaces, members, roles, invitations).

API

RouteDescription
/Health check (the healthRoute default).
/docsInteractive API reference (Scalar).
/openapi.jsonGenerated OpenAPI 3.1 spec, including the Better Auth endpoints under /auth/....
/api/*REST-style oRPC endpoints.
/rpc/*oRPC endpoints for typed TypeScript clients.
/api/auth/*Better Auth endpoints.

Workspace procedures

Served at /api/... (REST) and /rpc/... (oRPC). Every call needs a session: cookie or Authorization: Bearer. The session is read from the database on each call, so a ban or revocation applies immediately (the cookie cache is bypassed). workspaceId is part of every workspace-scoped input; the intent guard looks up the caller's role in it.

ProcedureRESTIntent
workspaces.createPOST /workspacessign-in only
workspaces.listMineGET /workspacessign-in only
workspaces.getGET /workspaces/{workspaceId}member:list
workspaces.updatePATCH /workspaces/{workspaceId}workspace:update
workspaces.deleteDELETE /workspaces/{workspaceId}workspace:delete
workspaces.transferOwnerPOST /workspaces/{workspaceId}/transfer-ownerworkspace:transferOwner
audit.listGET /workspaces/{workspaceId}/auditaudit:read (owner, admin); filters action, actorId, cursor paging; leaves out ip, spanId and traceId; reads are not audited
members.listGET /workspaces/{workspaceId}/membersmember:list; each member carries name and email, looked up through Better Auth's internal adapter
members.setRolePATCH /workspaces/{workspaceId}/members/{userId}member:setRole
members.removeDELETE /workspaces/{workspaceId}/members/{userId}member:remove
invitations.createPOST /workspaces/{workspaceId}/invitationsmember:invite
invitations.listGET /workspaces/{workspaceId}/invitationsmember:invite
invitations.revokeDELETE /workspaces/{workspaceId}/invitations/{invitationId}member:invite
invitations.acceptPOST /invitations/acceptsign-in only
invitations.listMineGET /invitations/minesign-in only
invitations.acceptMinePOST /invitations/{invitationId}/acceptsign-in only

Rules enforced on the server: the creator is the only owner; setRole never grants owner (use transferOwner); an admin cannot change or remove an owner; the last owner cannot be demoted or removed (409 last_owner, checked in the same database update); a non-member gets 403 not_a_member, the same for a workspace that does not exist.

Invitations (src/lib/handlers/invitations.ts): create makes a token of 32 random bytes (node:crypto, base64url), stores only its SHA-256 hash with expiresAt 7 days ahead, and returns the token once; nothing logs it. accept takes the token in the body (never the path, which reaches the request log), hashes it and passes the session user's id and email to acceptInvitation, which joins the workspace and marks the invite used in one transaction. Refusals: unknown token 404, another email 403 email_mismatch, 409 invite_expired, invite_used (used or revoked) or already_member. The rateLimit metas on workspaces.create, invitations.create, invitations.accept and invitations.acceptMine are enforced per client IP by createClientIpRateLimitMiddleware (@gentlemans-stack/server-setup/client-ip-rate-limit), the first middleware of every procedure, so a refused call still counts; the answer is 429 RATE_LIMIT_EXCEEDED with Retry-After. Deleting a workspace also deletes its invites.

Audit events

Every procedure with an audit meta is recorded by createAuditMiddleware (audit-domain), which runs before the intent guard so a refused attempt gets a denied row and a thrown error a failed one. Role changes, removals and accepted invites are written inside the change's own transaction (the audit hook of workspace-domain), so the row and the change commit or roll back together. Account events (sign-in, password change, two-factor, passkey, session revoke, account delete) come from a Better Auth hooks.after in src/lib/account-audit.ts; they have no workspace and are not in the workspace feed. Not audited: transferOwner, workspace delete and password reset. Rows keep traceId and spanId for operators; audit.list does not return them.

Better Auth

Better Auth 1.7.x is mounted at /api/auth/* through the mounts option of serviceServerApp (see libs/server-setup).

  • Plugins: admin, bearer and openAPI. The openAPI plugin's own reference page is disabled; its endpoints appear on /docs under /auth/....
  • Sign-up and sign-in with email and password are enabled.
  • Sessions are Better Auth's database sessions, carried by the session cookie. The bearer plugin returns a set-auth-token header, so non-browser clients can send Authorization: Bearer.
  • Sessions and revocation: with the cookie cache on, a browser request stays valid for up to IAM_SERVICE_SESSION_COOKIE_CACHE_SECONDS after the session is revoked; a bearer request is checked against the database every time and is rejected at once.
  • Same-site: the browser sends the session cookie only to hosts on the same site as the IAM service (same registrable domain, or one reverse proxy; localhost ports count as one site).
  • Rate limits (Better Auth's own, stored in the database, per client IP): sign-in, sign-up, change-password and admin/set-user-password 5 per minute, admin/ban-user, admin/remove-user and admin/create-user 10 per minute, password reset 3 per minute. oRPC procedures use libs/rate-limit.
  • Roles: admin plugin, default role user, admin role admin (application-wide; per-tenant roles come later). Sign-up never grants a role. Seed the first admin as an operator (for example auth.api.createUser({ body: { role: "admin", ... } }) from a one-off script, or set role on the user document); there is no env-based promotion, because an unverified sign-up with a known address could claim it. An admin cannot ban or remove themselves (Better Auth refuses, YOU_CANNOT_BAN_YOURSELF / YOU_CANNOT_REMOVE_YOURSELF) or change their own role through admin/set-role or admin/update-user (a hooks.before guard in src/lib/auth.ts, 400 CANNOT_CHANGE_OWN_ROLE).
  • Production guards: startup fails when NODE_ENV=production and IAM_SERVICE_BASE_URL is not https or the secret is the example value; trusted origins must be exact (no *). The request log skips /api/auth/reset-password/**, whose URL carries the reset token.
  • The shared gentlemans_stack database user can read Better Auth's collections. In production give iam-service its own user or database.
  • Password-reset and verification mails are only logged (event and user id). The token and URL are never logged.
  • Better Auth writes its collections (user, session, account and verification) into the shared gentlemans-stack database, next to the service's own. Only this service writes them.
  • The adapter receives both client and db (mongodbAdapter(db, { client })), so Better Auth's multi-document writes run in transactions. This requires a replica set in every environment: local infra runs one (see LOCAL_INFRA), and production must be a replica set or Atlas.

Run locally

Run pnpm infra:up, then the serve target with the variables from Configuration set in the root .env.

Complete the service

  1. Generate a contract under contracts/<name>-contracts, add it with the generator's --contracts option, and implement its procedures in src/lib/create-app.ts and, if needed, generate a domain in domains/<name>-domain.
  2. Add the contract's router in src/lib/create-app.ts next to createWorkspaceRouter (see src/lib/handlers/): the session middleware authenticates, createRequireIntent checks the procedure's declared intent.
  3. Register only this service's shared OpenAPI schemas in src/lib/openapi-schemas.ts.

Configuration

Add these values to the repository root .env.

VariableDefaultPurpose
MONGO_URIrequiredThe MongoDB URI shared by every service (the gentlemans-stack database). The local value is the top of .env.example.
IAM_SERVICE_AUTH_SECRETrequired, at least 32 charactersSigning secret for session cookies. Env only; never logged.
IAM_SERVICE_BASE_URLhttp://localhost:33001Public origin of the auth endpoints.
IAM_SERVICE_TRUSTED_ORIGINShttp://localhost:4200Comma-separated browser origins allowed to call the auth endpoints.
IAM_SERVICE_APP_NAMEgentlemans-stack-iam-servicePrefix of every auth cookie, for example gentlemans-stack-iam-service.session_token.
IAM_SERVICE_AUTH_DATABASE_NAMEunset (the shared database)Database that holds Better Auth's collections (user, session, account, verification, two-factor, passkey). Set it in production and give the other services a Mongo user with no access to it, so they cannot read password hashes.
IAM_SERVICE_SESSION_COOKIE_CACHE_SECONDS300How long a browser request trusts the signed session cookie before the database is read again.
IAM_SERVICE_SESSION_EXPIRES_DAYS7Session lifetime.
IAM_SERVICE_SIGN_UP_RATE_LIMIT5Sign-ups per client IP per minute. Only the e2e run raises it (apps/todo-ui/playwright.config.ts).
IAM_SERVICE_COOKIE_DOMAINunsetParent domain (for example example.com) that makes sibling subdomains share the session. Unset for a single host.
IAM_SERVICE_CLIENT_IP_HEADERunset (x-forwarded-for)Header the client IP is read from for rate limits. Name only a header your proxy overwrites; behind none, clients can spoof it and dodge the limits.
IAM_SERVICE_TRUSTED_PROXIESunsetComma-separated proxy IPs or CIDRs allowed to append to a multi-hop IAM_SERVICE_CLIENT_IP_HEADER.
IAM_SERVICE_PASSKEY_RP_IDunset (the host of IAM_SERVICE_BASE_URL)Relying-party ID for passkeys: the registrable domain the web app runs on (example.com). It cannot change later without invalidating passkeys.
IAM_SERVICE_GITHUB_CLIENT_ID, IAM_SERVICE_GITHUB_CLIENT_SECRETunsetA GitHub OAuth app, so users can link it in their account. Both or neither; unset keeps GitHub off.
IAM_SERVICE_DISCORD_CLIENT_ID, IAM_SERVICE_DISCORD_CLIENT_SECRETunsetA Discord OAuth app, same rule.
IAM_SERVICE_API_ADDRESSrequiredExternally advertised service address.
IAM_SERVICE_API_HOST0.0.0.0Listener host.
IAM_SERVICE_API_PORT33001Listener port.

LOG_LEVEL and NODE_ENV are shared logging/runtime configuration.

Tests

Tests run against an in-memory MongoDB.

Commands

pnpm nx run iam-service:typecheck          # type-check the service and its dependencies
pnpm nx run iam-service:test               # run the service tests
pnpm nx run iam-service:serve              # run locally
pnpm nx run iam-service:build              # create the deployable bundle
pnpm nx run iam-service:prune              # create the deployment manifest and workspace modules
pnpm nx run iam-service:sync-deploy-deps   # check the bundle dependencies against the deploy manifest
pnpm nx run iam-service:docker:build       # build the container image
pnpm nx run iam-service:docker:run         # run the container image

On this page