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
| Route | Description |
|---|---|
/ | Health check (the healthRoute default). |
/docs | Interactive API reference (Scalar). |
/openapi.json | Generated 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.
| Procedure | REST | Intent |
|---|---|---|
workspaces.create | POST /workspaces | sign-in only |
workspaces.listMine | GET /workspaces | sign-in only |
workspaces.get | GET /workspaces/{workspaceId} | member:list |
workspaces.update | PATCH /workspaces/{workspaceId} | workspace:update |
workspaces.delete | DELETE /workspaces/{workspaceId} | workspace:delete |
workspaces.transferOwner | POST /workspaces/{workspaceId}/transfer-owner | workspace:transferOwner |
audit.list | GET /workspaces/{workspaceId}/audit | audit:read (owner, admin); filters action, actorId, cursor paging; leaves out ip, spanId and traceId; reads are not audited |
members.list | GET /workspaces/{workspaceId}/members | member:list; each member carries name and email, looked up through Better Auth's internal adapter |
members.setRole | PATCH /workspaces/{workspaceId}/members/{userId} | member:setRole |
members.remove | DELETE /workspaces/{workspaceId}/members/{userId} | member:remove |
invitations.create | POST /workspaces/{workspaceId}/invitations | member:invite |
invitations.list | GET /workspaces/{workspaceId}/invitations | member:invite |
invitations.revoke | DELETE /workspaces/{workspaceId}/invitations/{invitationId} | member:invite |
invitations.accept | POST /invitations/accept | sign-in only |
invitations.listMine | GET /invitations/mine | sign-in only |
invitations.acceptMine | POST /invitations/{invitationId}/accept | sign-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,bearerandopenAPI. TheopenAPIplugin's own reference page is disabled; its endpoints appear on/docsunder/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
bearerplugin returns aset-auth-tokenheader, so non-browser clients can sendAuthorization: Bearer. - Sessions and revocation: with the cookie cache on, a browser request stays valid for up to
IAM_SERVICE_SESSION_COOKIE_CACHE_SECONDSafter 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;
localhostports count as one site). - Rate limits (Better Auth's own, stored in the database, per client IP): sign-in, sign-up,
change-passwordandadmin/set-user-password5 per minute,admin/ban-user,admin/remove-userandadmin/create-user10 per minute, password reset 3 per minute. oRPC procedures uselibs/rate-limit. - Roles:
adminplugin, default roleuser, admin roleadmin(application-wide; per-tenant roles come later). Sign-up never grants a role. Seed the first admin as an operator (for exampleauth.api.createUser({ body: { role: "admin", ... } })from a one-off script, or setroleon 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 throughadmin/set-roleoradmin/update-user(ahooks.beforeguard insrc/lib/auth.ts, 400CANNOT_CHANGE_OWN_ROLE). - Production guards: startup fails when
NODE_ENV=productionandIAM_SERVICE_BASE_URLis 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_stackdatabase 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,accountandverification) into the sharedgentlemans-stackdatabase, next to the service's own. Only this service writes them. - The adapter receives both
clientanddb(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
- Generate a contract under
contracts/<name>-contracts, add it with the generator's--contractsoption, and implement its procedures insrc/lib/create-app.tsand, if needed, generate a domain indomains/<name>-domain. - Add the contract's router in
src/lib/create-app.tsnext tocreateWorkspaceRouter(seesrc/lib/handlers/): the session middleware authenticates,createRequireIntentchecks the procedure's declared intent. - Register only this service's shared OpenAPI schemas in
src/lib/openapi-schemas.ts.
Configuration
Add these values to the repository root .env.
| Variable | Default | Purpose |
|---|---|---|
MONGO_URI | required | The MongoDB URI shared by every service (the gentlemans-stack database). The local value is the top of .env.example. |
IAM_SERVICE_AUTH_SECRET | required, at least 32 characters | Signing secret for session cookies. Env only; never logged. |
IAM_SERVICE_BASE_URL | http://localhost:33001 | Public origin of the auth endpoints. |
IAM_SERVICE_TRUSTED_ORIGINS | http://localhost:4200 | Comma-separated browser origins allowed to call the auth endpoints. |
IAM_SERVICE_APP_NAME | gentlemans-stack-iam-service | Prefix of every auth cookie, for example gentlemans-stack-iam-service.session_token. |
IAM_SERVICE_AUTH_DATABASE_NAME | unset (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_SECONDS | 300 | How long a browser request trusts the signed session cookie before the database is read again. |
IAM_SERVICE_SESSION_EXPIRES_DAYS | 7 | Session lifetime. |
IAM_SERVICE_SIGN_UP_RATE_LIMIT | 5 | Sign-ups per client IP per minute. Only the e2e run raises it (apps/todo-ui/playwright.config.ts). |
IAM_SERVICE_COOKIE_DOMAIN | unset | Parent domain (for example example.com) that makes sibling subdomains share the session. Unset for a single host. |
IAM_SERVICE_CLIENT_IP_HEADER | unset (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_PROXIES | unset | Comma-separated proxy IPs or CIDRs allowed to append to a multi-hop IAM_SERVICE_CLIENT_IP_HEADER. |
IAM_SERVICE_PASSKEY_RP_ID | unset (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_SECRET | unset | A 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_SECRET | unset | A Discord OAuth app, same rule. |
IAM_SERVICE_API_ADDRESS | required | Externally advertised service address. |
IAM_SERVICE_API_HOST | 0.0.0.0 | Listener host. |
IAM_SERVICE_API_PORT | 33001 | Listener 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