@xeplr/auth 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,574 @@
1
+ # @xeplr/auth
2
+
3
+ **The sign-in service for xeplr apps.** Register, activate, log in, forgot / reset password, invites, and sessions made of a short-lived access token plus a refresh token — kept in Redis, with an optional sliding refresh that hands back a new token in the `X-New-Token` response header. It also owns the RBAC catalog — `roles`, `apis`, `uiPages`, `uiElements` and `menus`, each mapped to roles and each (except elements) with an `isPublic` flag — and records multi-tenant membership in `userTenantsMapping`, which `mtMembershipMiddleware` enforces. Data lives in PostgreSQL; sessions and the access cache live in Redis.
4
+
5
+ ```
6
+ POST /auth/api/login { email, password }
7
+ → { accessToken, refreshToken, user, access: { roles, pages, apis, menus, menuItems, elements } }
8
+ ```
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm i @xeplr/auth
14
+ ```
15
+
16
+ Peer: `express ^4 || ^5`. Needs PostgreSQL (migration `0001` runs `CREATE EXTENSION pgcrypto`) and Redis.
17
+
18
+ > **`REDIS_PREFIX` is required.** Set one of your own, e.g. `REDIS_PREFIX=myapp:`. It may not be unset, and may not be the shared default `xeplr:` — [why](#redis_prefix-is-required). Apps upgrading from an earlier version must add it, or the service will not start.
19
+
20
+ ## Two ways to run it
21
+
22
+ ### As its own service: `xeplr-auth-server`
23
+
24
+ ```json
25
+ "start-auth": "dotenv -e development.env -- xeplr-auth-server"
26
+ ```
27
+
28
+ `bin/server.js` calls `boot()`. It reads `process.env` only and loads no `.env` file — the launcher provides the environment. `boot()`:
29
+
30
+ 1. checks `REDIS_PREFIX` ([refuses](#redis_prefix-is-required) if missing or `xeplr:`);
31
+ 2. checks Redis is reachable ([refuses](#startup) if not);
32
+ 3. runs auth's own migrations, then the directories in `XEPLR_AUTH_MIGRATIONS`;
33
+ 4. configures email from env and checks it can send (never fatal);
34
+ 5. starts Express on `AUTH_PORT` (default `19001`) with `/auth/api` and `/auth/api/admin` mounted;
35
+ 6. prints a [banner](#startup) of the effective configuration.
36
+
37
+ When run under a parent process (`process.send` exists), it sends `{ status: 'ready' }` once listening.
38
+
39
+ To register [hooks](#hooks), write your own boot file — hooks only fire in the process that does the work:
40
+
41
+ ```js
42
+ var auth = require('@xeplr/auth')
43
+ auth.hooks.on('user', 'create', async function(userId) { /* … */ })
44
+ auth.boot()
45
+ ```
46
+
47
+ ### In your own process
48
+
49
+ ```js
50
+ var auth = require('@xeplr/auth')
51
+
52
+ await auth.init({
53
+ database: 'myapp_auth', // or AUTH_DB_NAME, default 'auth'
54
+ connection: process.env.XEPLR_DB_CONNECTION, // encrypted string, or { host, port, user, password }
55
+ jwt: { secret: process.env.AUTH_JWT_SECRET, accessTokenExpiresIn: '15m' },
56
+ email: { provider: 'smtp', smtp: { /* … */ } } // optional
57
+ })
58
+
59
+ app.use('/auth/api', auth.router({ resetBaseUrl: 'https://app.example.com' }))
60
+ app.use('/auth/api/admin', auth.adminRouter())
61
+ ```
62
+
63
+ `init()` checks `REDIS_PREFIX` but does **not** check Redis, run migrations, or print the banner — run [`xeplr-auth-migrate`](#migrations) yourself. It binds the auth models as the **process-wide** default connection; a process with its own database should use `attach()` instead, which opens a secondary connection. Pass `jwt.accessTokenExpiresIn` to match `AUTH_ACCESS_TOKEN_TTL_MINUTES` — without `jwt` the token lifetime is `15m` while the session entry in Redis follows the env value.
64
+
65
+ To act on auth tables from another service (invite a user, assign roles) while auth itself runs standalone:
66
+
67
+ ```js
68
+ var auth = require('@xeplr/auth').attach() // AUTH_DB_NAME + the connection env
69
+ await auth.ready()
70
+ await auth.model('UserRolesMapping').query().insert({ /* … */ })
71
+ await auth.service.invite({ email, name, invitedBy, inviterName, appName })
72
+ ```
73
+
74
+ ## Exports
75
+
76
+ | export | |
77
+ |---|---|
78
+ | `boot()` | the standalone service, env-driven, as above; resolves to the `http.Server` |
79
+ | `start(config)` | `init(config)` + Express on `config.port` with both routers; no Redis check, no migrations, no banner |
80
+ | `init(config)` | connect and bind the models, configure JWT and email; checks `REDIS_PREFIX` |
81
+ | `attach()` | secondary connection to the auth database from another process: `{ ready, conn, model(name), service }` |
82
+ | `router(options)` | the `/auth/api` router; `options.resetBaseUrl` sets where reset links point |
83
+ | `adminRouter()` | the `/auth/api/admin` router |
84
+ | `authMiddleware` | Bearer token check against the Redis session; sets `req.user`; slides within tolerance |
85
+ | `accessMiddleware(options)` | per-API RBAC from the `apis` catalog — see [Access checks](#access-checks) |
86
+ | `requireRole(...names)` | 403 unless `req.user.roles` holds one of the names; use after `authMiddleware` |
87
+ | `mtMembershipMiddleware(options)` | 403 when a tenant header names a value the caller has no membership for |
88
+ | `authService` | `register`, `activate`, `invite`, `previewInvite`, `acceptInvite`, `login`, `forgotPassword`, `resetPassword`, profile, phone OTP, `changePassword`, `configureActivation`, `configureEmail` |
89
+ | `accessService` | `getUserAccess`, `userApiState`, `userHasApiAccess`, `apiStateFor`, `ACCESS_STATES`, `getApiRule`, `getPublicItems`, `clearUserAccess`, `clearAccessRules`, `clearAllAccess` |
90
+ | `sessionService` | `createSession`, `getSession`, `validateAccessToken`, `slideAccessToken`, `rotateSession`, `destroySession`, `destroyAllUserSessions` |
91
+ | `ticketService` | `issueTicket`, `consumeTicket` — single-use 30-second tickets for SSE / WebSocket |
92
+ | `authHelper` | `configure`, `hashPassword`, `comparePassword`, `generateAccessToken`, `verifyToken`, `decodeVerified`, `generateId`, … |
93
+ | `hooks` | `on(identifier, event, fn)`, `fire`, `setHooksEnabled` |
94
+ | `seedSuperAdmin(knex, { email, password, name? })` | insert-if-absent super admin user + role mapping, for apps seeding from JS |
95
+ | `configureWorkflowResume(fn)` | hand in `@xeplr-workflow/api`'s `resumeByKey`; activation with a `workflowKey` then resumes that workflow (best-effort) |
96
+ | `requiredEnv` | the env names this package needs, for an app's `env.required.js`; `requiredEnv.activationLinkVar` names the activation-link variable in use |
97
+ | `models` | Objection models: `User`, `Role`, `Api`, `UiPage`, `UiElement`, `Menu`, the five `*RolesMapping`, `UserTenantsMapping` |
98
+
99
+ ## Environment
100
+
101
+ ### Required
102
+
103
+ Everything in `requiredEnv`, plus a connection and an activation link.
104
+
105
+ | variable | default in code | meaning |
106
+ |---|---|---|
107
+ | `REDIS_PREFIX` | — (refused) | namespace for every auth key in Redis; not `xeplr:` — [why](#redis_prefix-is-required) |
108
+ | `ENCRYPTION_KEY` | — | decrypts the connection string |
109
+ | `XEPLR_DB_CONNECTION` or `AUTH_DB_CONNECTION_INFO_ENCRYPTED` | — | encrypted `{ host, port, user, password }`. The shared `XEPLR_DB_CONNECTION` is used unless `AUTH_DB_CONNECTION_INFO_ENCRYPTED` overrides it for this service. Not in `requiredEnv`, since either one is correct |
110
+ | `AUTH_DB_NAME` | `auth` | the auth database — the server comes from the connection, the database from here |
111
+ | `AUTH_JWT_SECRET` | `change_me_in_production` | signs access tokens; the banner shows `✗ INSECURE DEFAULT` when unset |
112
+ | `AUTH_PORT` | `19001` | port for `boot()` / `start()` |
113
+ | `AUTH_SUPER_ADMIN_EMAIL` | — | the first account, used by migration `0008` — [details](#the-first-account) |
114
+ | `AUTH_SUPER_ADMIN_PASSWORD` | — | its password; no quotes, spaces, `$` or `#` (substituted into SQL) |
115
+ | `XEPLR_AUTH_MIGRATIONS` | none | comma-separated app migration directories, run after auth's own — [details](#migrations) |
116
+ | `AUTH_TENANT_HEADER` | — | the header that names the company a role is created in (e.g. `x-company-id`), or `none` for a single-tenant app. No default: a multi-tenant app that forgot it would make every role visible to every company — [details](#roles-belong-to-a-company) |
117
+ | `AUTH_ACTIVATION_URL` | — | full address of your activation page, e.g. `http://localhost:19100/auth/activate`; `?token=…` is appended. The older `AUTH_ACTIVATION_BASE_URL` (below) also satisfies it — `requiredEnv.activationLinkVar` names whichever the install uses. The service starts without it, but registration fails |
118
+
119
+ ### Optional
120
+
121
+ | variable | default | meaning |
122
+ |---|---|---|
123
+ | `AUTH_INVITE_URL` | derived | full address of your accept-invite page; `?token=…` is appended |
124
+ | `AUTH_ACTIVATION_BASE_URL` | — | older form: an origin; `/auth/activate` and `/auth/accept-invite` are appended when the two URLs above are unset |
125
+ | `AUTH_ACCESS_TOKEN_TTL_MINUTES` | `15` | access token lifetime |
126
+ | `AUTH_REFRESH_TOKEN_TTL_DAYS` | `7` | refresh token (session) lifetime |
127
+ | `AUTH_ACCESS_TOKEN_TOLERANCE_SECONDS` | `0` | grace after expiry during which a token is still served and slid; `0` turns sliding refresh off |
128
+ | `AUTH_MAX_SESSIONS_PER_USER` | `5` | concurrent sessions; the oldest are evicted |
129
+ | `AUTH_RESET_TOKEN_EXPIRY_MINUTES` | `30` | password reset link lifetime |
130
+ | `AUTH_ENABLE_HOOKS` | on | `false` turns every hook off |
131
+ | `REDIS_HOST` / `REDIS_PORT` | `127.0.0.1` / `6379` | the session store |
132
+ | `REDIS_PASSWORD` / `REDIS_DB` | none / `0` | read by `@xeplr/utils`' cache |
133
+ | `UPLOAD_DIR` | `./uploads` | where avatar uploads are written |
134
+ | `EMAIL_PROVIDER` | not configured | `smtp`, `brevo`, `aws` or `azure` |
135
+ | `SMTP_HOST`, `SMTP_PORT` (587), `SMTP_USER`, `SMTP_PASS`, `SMTP_FROM`, `SMTP_SECURE`, … | | SMTP settings, read by `@xeplr/utils` |
136
+ | `BREVO_API_KEY`, `BREVO_FROM_EMAIL`, `BREVO_FROM_NAME` | | Brevo |
137
+ | `AWS_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SES_FROM` | | Amazon SES |
138
+ | `AZURE_COMMUNICATION_CONNECTION_STRING`, `AZURE_EMAIL_FROM` | | Azure Communication Services |
139
+
140
+ ## REDIS_PREFIX is required
141
+
142
+ Every key auth writes to Redis — sessions, the access-token whitelist, SSE tickets and the access cache — is written under `REDIS_PREFIX`. `@xeplr/utils` falls back to `xeplr:` when it is unset, so **two apps on one Redis** (any developer machine running more than one) read and write the same keys.
143
+
144
+ Most of those keys contain a token or a user id and never collide. The access cache does not: `access:public` (the menus and pages everyone may see) and `access:api:<name>` (whether an API is open, and to which roles) are named by content. One app fills them from its database and the other serves them as its own:
145
+
146
+ - the drawer shows another product's menus and drops its own;
147
+ - an API the other app never registered is cached as open to everyone, so a guarded route answers any signed-in caller for up to ten minutes — no error, no log line.
148
+
149
+ So `init()` and `boot()` (and therefore `start()` and `xeplr-auth-server`) **refuse to start**, naming the variable, when `REDIS_PREFIX` is unset, blank, or exactly `xeplr:`. `xeplr:` is refused even when written out, because it is exactly what an env file copied from another project carries.
150
+
151
+ ```
152
+ REDIS_PREFIX is not set. Give this app its own, e.g. REDIS_PREFIX=myapp: — apps sharing a Redis without one serve each other's sessions, menus and API permissions.
153
+ ```
154
+
155
+ Fix: `REDIS_PREFIX=myapp:` — one value per app, the same in every process of that app.
156
+
157
+ ## Startup
158
+
159
+ **Redis must be reachable.** `boot()` writes, reads and deletes a probe key before anything else, and exits with instructions if it cannot. Without Redis, login still *succeeds* (minting a token needs no Redis) but the session write fails silently, and every following request answers `Invalid or expired token` — which points at clocks and secrets rather than the missing service.
160
+
161
+ **The banner** shows the effective configuration, defaults resolved, secrets masked:
162
+
163
+ ```
164
+ ┌─────────────────────────────────────────────────────────────┐
165
+ │ xeplr-auth · running │
166
+ ├─────────────────────────────────────────────────────────────┤
167
+ │ port 19001 │
168
+ │ database myapp_auth │
169
+ │ XEPLR_AUTH_MIGRATIONS./migrations-auth │
170
+ │ activation url http://localhost:19100/auth/activate │
171
+ │ invite url (derived) │
172
+ │ access token ttl 15m │
173
+ │ refresh token ttl 7d │
174
+ │ slide tolerance 0s │
175
+ │ max sessions/user 5 │
176
+ │ redis localhost:6379 │
177
+ │ redis prefix myapp: │
178
+ │ email ✓ smtp — smtp.example.com:587, connected │
179
+ │ connection XEPLR_DB_CONNECTION │
180
+ │ encryption key ✓ set │
181
+ │ jwt secret ✓ set │
182
+ └─────────────────────────────────────────────────────────────┘
183
+ ```
184
+
185
+ `connection` names the variable the connection was resolved through.
186
+
187
+ **The email row is a real check**, made by `@xeplr/utils`' `checkEmail` with a 5-second timeout — SMTP connects and authenticates, Brevo has its API key checked, AWS and Azure have their settings checked (not contacted):
188
+
189
+ | row | meaning |
190
+ |---|---|
191
+ | `✓ smtp — host:port, connected` | mail can go out |
192
+ | `✗ NOT WORKING — reason` | e.g. `not configured (EMAIL_PROVIDER is not set)`, `SMTP_HOST is not set`, a connection error; a warning follows the banner |
193
+ | `? not checked — @xeplr/utils is too old to check` | the installed `@xeplr/utils` has no `checkEmail` |
194
+
195
+ SMTP needs `nodemailer` installed in the app.
196
+
197
+ **Email is never fatal.** Sign-in, refresh and everything behind a token work without it. What cannot work is anything that sends a link:
198
+
199
+ - **Registration currently errors without email.** The account row is inserted first; then a missing activation URL, or a failed send, answers `500` — and the unactivated account stays, so registering again answers `409`.
200
+ - **Invites** (`authService.invite`) throw the same way.
201
+ - **Forgot password** answers `500` for an address that exists (and the usual message for one that does not).
202
+
203
+ ## Migrations
204
+
205
+ Hand-written `.sql` files, applied once each in their own transaction, tracked by filename in `xeplr_migrations`. No `down()`. `boot()` runs them itself; in-process apps run the CLI.
206
+
207
+ ```sh
208
+ AUTH_DB_NAME=myapp_auth xeplr-auth-migrate up --connection-env XEPLR_DB_CONNECTION
209
+ xeplr-auth-migrate status --connection-env XEPLR_DB_CONNECTION # completed, pending, and edited-after-applying
210
+ ```
211
+
212
+ | option | |
213
+ |---|---|
214
+ | `--db <name>` | database; default `AUTH_DB_NAME` |
215
+ | `--extDir <dir>[,<dir>…]` | app migration directories; default `XEPLR_AUTH_MIGRATIONS` |
216
+ | `--connection-env <VAR>` | read the encrypted connection from that variable |
217
+ | `--connection <encrypted>` | the encrypted connection itself |
218
+
219
+ Without `--connection` or `--connection-env`, the CLI reads `AUTH_CONNECTION` — it does not look at `XEPLR_DB_CONNECTION` or `AUTH_DB_CONNECTION_INFO_ENCRYPTED` on its own. It reads `process.env` only.
220
+
221
+ **`XEPLR_AUTH_MIGRATIONS`** is a comma-separated list of directories. Auth's own migrations run first, then each directory in order — this is how an app adds its own `apis`, `menus` and role mappings to the auth database, and how several apps (BI, workflow, jobs) land theirs in one database:
222
+
223
+ ```
224
+ XEPLR_AUTH_MIGRATIONS=./migrations-auth,./node_modules/@xeplr/factory/migrations-auth
225
+ ```
226
+
227
+ - **Filenames must be unique across all the directories.** The ledger is keyed by filename alone: a second `0003_menus.sql` in another directory is treated as already applied and silently skipped.
228
+ - A directory that does not exist is an error, not an empty contribution.
229
+ - `${VAR}` in a file is replaced with `process.env.VAR`; an unset variable fails the migration by name.
230
+
231
+ Auth's own migrations:
232
+
233
+ | file | |
234
+ |---|---|
235
+ | `0001_extensions` | `pgcrypto` |
236
+ | `0002_users` | `users` |
237
+ | `0003_catalog_tables` | `roles`, `apis`, `uiPages`, `uiElements`, `menus` |
238
+ | `0004_role_mappings` | `apisRolesMapping`, `uiPagesRolesMapping`, `uiElementsRolesMapping`, `menuRolesMapping`, `userRolesMapping` |
239
+ | `0005_user_tenants_mapping` | `userTenantsMapping` |
240
+ | `0006_seed_catalog` | roles Super Admin, Admin, Editor, Viewer; auth's own apis, pages, elements, menus; Super Admin and Admin mapped to all of them |
241
+ | `0007_license_module` | `licenseModule` column (default `core`) on apis, menus, uiPages, uiElements |
242
+ | `0008_super_admin` | the first account |
243
+ | `0009_menu_labels` | `label`, `sortOrder`, `isHidden` on `menus` |
244
+ | `0010_system_scope` | `scope` (`system` / `company`) on `apis` and `roles`, `scopeLocked` on `apis`. Super Admin, the role-management routes and the scope switch become `system`; the routes are locked |
245
+ | `0011_verify_api` | the `GET /auth/api/verify` row, public in the catalog |
246
+ | `0012_default_role_access` | auth's own routes mapped to its default roles: `account:*` to every role, `users:*` `access:*` `settings:*` to Admin, system APIs to nobody but Super Admin |
247
+
248
+ ## The first account
249
+
250
+ Migration `0008` creates a user from `AUTH_SUPER_ADMIN_EMAIL` / `AUTH_SUPER_ADMIN_PASSWORD` — name `Super Admin`, activated, bcrypt password, tenant `*` — and maps it to the `Super Admin` role. The migrator refuses to run `0008` while either variable is unset, because an install that migrates cleanly with nobody able to sign in fails much later than its cause.
251
+
252
+ It is created **once**, when migrations first run on that database:
253
+
254
+ - Changing the variables later creates nothing — `0008` is already in the ledger and never runs again. The old account and its password stay.
255
+ - Pointing at an existing database keeps its accounts. If a user with that email already exists when `0008` runs, it keeps its password.
256
+
257
+ To add or change an account afterwards, use the app (or `seedSuperAdmin(knex, { email, password })` from your own migration code).
258
+
259
+ ## Sessions and tokens
260
+
261
+ A session is one login on one device: a JWT **access token** (claims `id`, `email`, `name`, `roles`) and a random **refresh token**, both recorded in Redis.
262
+
263
+ | event | effect |
264
+ |---|---|
265
+ | login | new session; beyond `AUTH_MAX_SESSIONS_PER_USER` the oldest are ended |
266
+ | `POST /refresh` | the old pair is destroyed and a new pair issued, with roles re-read from the database |
267
+ | `POST /logout` | that session ends; its access token stops working immediately |
268
+ | reset or change password | every session of that user ends |
269
+
270
+ `authMiddleware` checks, in order: the signature, then that the session is still live in Redis (a logged-out token is never accepted), then expiry.
271
+
272
+ **Sliding refresh** is on when `AUTH_ACCESS_TOKEN_TOLERANCE_SECONDS` is above `0`. A token that has expired by no more than that many seconds, on a live session, is still served — and the response carries a fresh one:
273
+
274
+ ```
275
+ X-New-Token: eyJhbGciOi…
276
+ Access-Control-Expose-Headers: X-New-Token
277
+ ```
278
+
279
+ Client code must read the header and replace its stored token, or the session ends when the grace runs out. Concurrent requests carrying the same expiring token all get the **same** new token. A slid token copies its roles from the old one; roles are re-read on `/refresh` or the next login. A revoked session is never graced.
280
+
281
+ ## Routes
282
+
283
+ ### `/auth/api`
284
+
285
+ | route | token | body / query → response |
286
+ |---|---|---|
287
+ | `POST /register` | — | `{ email, password, name?, phoneNumber? }` → `201 { message, user }`; `409` if the email is registered. Sends the activation email |
288
+ | `GET /activate` | — | `?token=…&workflowKey=…` → `{ message, user }` |
289
+ | `GET /invite-preview` | — | `?token=…` → `{ email, name }` |
290
+ | `POST /invite-accept` | — | `{ token, password, name? }` → sets the password and activates |
291
+ | `POST /login` | — | `{ email, password }` → `{ accessToken, refreshToken, user, access }`; `401` wrong password or deactivated; `403` not yet activated |
292
+ | `POST /refresh` | — | `{ refreshToken }` → a new `{ accessToken, refreshToken, user, access }` |
293
+ | `POST /logout` | — | `{ refreshToken }` → ends that session |
294
+ | `POST /forgot-password` | — | `{ email }` → the same message whether or not the address exists; emails `<resetBaseUrl>/auth/reset-password?token=…` (the request's own origin when no `resetBaseUrl` is given — `boot()` gives none) |
295
+ | `POST /reset-password` | — | `{ token, newPassword }` |
296
+ | `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims |
297
+ | `GET /verify` | ✓ | the check every app's gate makes on every request — see [Every request is checked](#every-request-is-checked) |
298
+ | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
299
+ | `POST /profile/avatar` | ✓ | multipart `avatar`, an image up to 2 MB; stores the file name only — serving `UPLOAD_DIR` is the app's job |
300
+ | `POST /change-password` | ✓ | `{ oldPassword, newPassword }`; ends every session |
301
+ | `POST /request-phone-otp` | ✓ | `{ phoneNumber? }` — needs an SMS provider registered with `@xeplr/utils` |
302
+ | `POST /verify-phone-otp` | ✓ | `{ code }` → `{ phoneVerified: true }` |
303
+ | `POST /sse-ticket` | ✓ | `{ scopes? }` (default `['user:me:*']`) → `{ ticket, expiresIn: 30 }` |
304
+
305
+ ### `/auth/api/admin`
306
+
307
+ **Every admin route requires a valid token and is checked against the catalog** (`accessGate`, see [Every request is checked](#every-request-is-checked)): a signed-in user without a role mapped to the route gets `403`. System APIs among them (role create, rename, delete and copy) are Super Admin only on top of that — [system scope](#system-scope). So are the `menu-items` routes.
308
+
309
+ | route | |
310
+ |---|---|
311
+ | `GET /users` | users with their roles |
312
+ | `GET /roles` | `[{ id, name, scope, mtId1 }]`: the current company's roles and the generic ones; system roles only for Super Admin |
313
+ | `GET /access-items` | `{ apis, pages, elements, menus }`, each with its roles |
314
+ | `POST /user-role` | `{ userId, roleId, assign }` — grant or remove a role |
315
+ | `POST /access-role` | `{ type: apis\|pages\|elements\|menus, itemId, roleId, assign }` |
316
+ | `POST /module-role` | `{ module, action, roleId, assign }` — every item of every type whose group is `module:action` |
317
+ | `GET /master/<type>` | `<type>` is `roles`, `apis`, `pages`, `elements` or `menus` |
318
+ | `POST /master/<type>` | `{ id?, name, … }` — update with `id`, create without |
319
+ | `POST /master/<type>/delete` | `{ id }` |
320
+ | `POST /master/roles/copy` | Super Admin — `{ roleIds, companyIds }` → `{ copied: [{ roleId, companyId, newRoleId }], skipped: [{ roleId, companyId, reason }] }` |
321
+ | `POST /master/apis/scope` | Super Admin — `{ id, scope: 'system' \| 'company' }`: the "Super Admin only" switch; refused for a locked API |
322
+ | `GET /menu-items` | Super Admin — [menu keys and labels](#menu-keys-and-labels) |
323
+ | `POST /menu-items` | Super Admin — `{ items: [{ name, label, sortOrder, isHidden }] }` |
324
+ | `POST /menu-items/add` | Super Admin — `{ name, label, isPublic? }` |
325
+ | `POST /menu-items/remove` | Super Admin — `{ name }` |
326
+
327
+ ## The access object
328
+
329
+ `/login`, `/refresh` and `/me` return what the user may use — the union of their roles' mappings and every `isPublic` row:
330
+
331
+ ```json
332
+ {
333
+ "roles": ["Admin"],
334
+ "pages": ["Profile", "User Roles"],
335
+ "apis": ["/auth/api/me", "/auth/api/admin/users"],
336
+ "menus": ["Tasks", "Profile"],
337
+ "menuItems": [{ "name": "Tasks", "label": "TSK", "sortOrder": 1 }, { "name": "Profile", "label": "Profile", "sortOrder": null }],
338
+ "elements": ["Assign Role Button"]
339
+ }
340
+ ```
341
+
342
+ - `menus` are **keys** — what app code matches on.
343
+ - `menuItems` are what to show for those keys, **in rail order**: by `sortOrder`, rows without one after, ties by label. `label` falls back to the key. **Hidden items are left out** of both.
344
+
345
+ **Cached in Redis** (under `REDIS_PREFIX`):
346
+
347
+ | key | lifetime | cleared by |
348
+ |---|---|---|
349
+ | `access:user:<id>` — the object above | 5 min | that user's login, `POST /user-role` for that user, any `menu-items` change |
350
+ | `access:userRoles:<id>` — role ids for `accessMiddleware` | 5 min | that user's login, `POST /user-role` |
351
+ | `access:public` — public apis, pages, menus | 10 min | `access-role`, `module-role`, any delete, any `menu-items` change |
352
+ | `access:api:<name>` — one API's rule | 10 min | the same |
353
+
354
+ Menu-item changes clear every cached access object, so the `/me` the UI asks for next already carries them. Other catalog changes clear only the shared rules; another user's own access object can lag by up to 5 minutes.
355
+
356
+ ## Menu keys and labels
357
+
358
+ Migration `0009` splits what code refers to from what people read:
359
+
360
+ | column | |
361
+ |---|---|
362
+ | `name` | the **key**. What app code matches in `drawerItems` / `settingsOverrides`, and what roles are mapped to. Never shown; never renamed |
363
+ | `label` | what people see. Empty shows the key |
364
+ | `sortOrder` | position in the rail; empty sorts after the numbered ones |
365
+ | `isHidden` | kept and still role-mapped, but not shown — reversible, unlike delete |
366
+
367
+ Why the split: renaming a menu in the UI must not break the code that looks it up or the role mappings that grant it.
368
+
369
+ An app's own menu rows come from its `migrations-auth` SQL, with `name` = key. After that, a Super Admin changes how they look from the app:
370
+
371
+ ```
372
+ GET /auth/api/admin/menu-items
373
+ → [{ id, name, label, shown, sortOrder, isHidden, isPublic, menuGroup }] every row, hidden included
374
+
375
+ POST /auth/api/admin/menu-items { "items": [{ "name": "Tasks", "label": "TSK", "sortOrder": 1, "isHidden": false }] }
376
+ → { changed } only label, sortOrder and isHidden change; label null or "" clears it; sortOrder is a whole number or null
377
+
378
+ POST /auth/api/admin/menu-items/add { "name": "form:crop", "label": "Crops", "isPublic": true }
379
+ → { name, created } e.g. a form added to the menu; public unless isPublic is false; placed last;
380
+ an existing key is relabelled and un-hidden instead of duplicated
381
+
382
+ POST /auth/api/admin/menu-items/remove { "name": "form:crop" }
383
+ → { removed } deletes the row and its role mappings
384
+ ```
385
+
386
+ Bad input answers `400` with the reason.
387
+
388
+ ### System scope
389
+
390
+ Some things are not a company's business: managing roles, assigning licences, anything that acts on the whole install. They carry **`scope = 'system'`** (on `apis` and `roles`). Everything else is `company`, the default, and works as before.
391
+
392
+ | | Super Admin | Everyone else |
393
+ |---|---|---|
394
+ | A **system API** | allowed | refused `403` (`code: 'SYSTEM_SCOPE'`), whatever the role mappings say |
395
+ | A **system role** (Super Admin itself) | sees, edits, assigns | never listed, cannot assign or change |
396
+ | Granting a system API to a role | refused: system APIs are never granted | refused |
397
+
398
+ System APIs never appear in the Access Matrix (`/admin/access-items` leaves them out), and `/admin/access-role` and `/admin/module-role` refuse or skip them. The Super Admin role itself cannot be deleted, even by Super Admin.
399
+
400
+ **A row's name** is a path (every method) or `"METHOD path"` (that method only), so a `GET` can stay open on a path whose `POST` is a system action.
401
+
402
+ **Two ways to make an API system:**
403
+
404
+ - **A migration**, which travels with the code to every install (below). Add `"scopeLocked" = true` to pin it: a locked API cannot be switched off from the UI.
405
+ - **Super Admin's "Super Admin only" switch** in Master Settings → APIs, for people building an app without code. It calls `POST /auth/api/admin/master/apis/scope { id, scope: 'system' | 'company' }`, itself a locked system API, and takes effect at once. Only Super Admin sees the switch or may call the route. A locked API cannot be switched off (`400`, `code: 'SCOPE_LOCKED'`). Role mappings are kept, so switching an API back restores who had it.
406
+
407
+ Master Settings refuses to rename or delete a system API's row, since that would leave the route unguarded. `scope` is not an editable field in its ordinary save.
408
+
409
+ **Registering a product's own system API** is one row in the product's `migrations-auth` directory, with no change here:
410
+
411
+ ```sql
412
+ INSERT INTO "apis" (id, name, "apiGroup", "scope", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
413
+ SELECT encode(gen_random_bytes(12), 'hex'), 'POST /api/licences/assign', 'licences:edit', 'system', false, true, '*', now(), now()
414
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" WHERE name = 'POST /api/licences/assign');
415
+ ```
416
+
417
+ To make APIs that are already registered system APIs, update their rows the same way:
418
+
419
+ ```sql
420
+ UPDATE "apis" SET "scope" = 'system'
421
+ WHERE name IN ('POST /api/licences/assign', '/api/companies/create') AND "scope" <> 'system';
422
+ ```
423
+
424
+ and the product mounts the guard in front of its routes, after its auth check:
425
+
426
+ ```js
427
+ const { systemScopeGuard } = require('@xeplr/auth');
428
+ router.use(systemScopeGuard());
429
+ ```
430
+
431
+ The guard reads the catalog (cached with the other access rules, cleared by `clearAccessRules()`) and fails closed: if the catalog cannot be read, it answers `503` rather than letting a request through. The auth service's own admin routes are behind it already.
432
+
433
+ Super Admin is the user `0008_super_admin.sql` creates from `AUTH_SUPER_ADMIN_EMAIL` / `AUTH_SUPER_ADMIN_PASSWORD`, which `@xeplr/cli` fills in for every new app.
434
+
435
+ **The role routes:**
436
+
437
+ ```
438
+ GET /auth/api/admin/master/roles → [{ id, name, scope }] no system roles unless Super Admin
439
+ POST /auth/api/admin/master/roles { "name": "Workspace Admin" } → { id } system: create (scope 'company' unless given)
440
+ POST /auth/api/admin/master/roles { "id": "…", "name": "Workspace Admins" } → { id } system: rename
441
+ POST /auth/api/admin/master/roles/delete { "id": "…" } → { ok } system
442
+ ```
443
+
444
+ A new role appears as a column in the User Roles and Access Matrix screens of `@xeplr/ui-account` with no further change: both read this list.
445
+
446
+ ## Access checks
447
+
448
+ **`accessMiddleware(options)`** guards your own API routes from the `apis` catalog:
449
+
450
+ ```js
451
+ app.use('/api', auth.accessMiddleware()) // API name = req.baseUrl + req.path, e.g. "/api/orders"
452
+ ```
453
+
454
+ | the API is | result |
455
+ |---|---|
456
+ | not in `apis` | open |
457
+ | `isPublic` | open |
458
+ | in `apis` with no roles mapped | open |
459
+ | mapped to roles | Bearer token required (signature and expiry — not the Redis session), then the user's [access state](#access-states) |
460
+
461
+ Pass `apiNameResolver(req)` to name APIs differently. Because unregistered means open, register every route that must be guarded.
462
+
463
+ **`requireRole('Admin', 'Super Admin')`** checks the role names in the token, with no database lookup.
464
+
465
+ ### Access states
466
+
467
+ The gate answers one of three states, not true/false. Only `enabled` goes through:
468
+
469
+ | state | means | `accessMiddleware` |
470
+ |---|---|---|
471
+ | `enabled` | shown and usable | passes |
472
+ | `disabled` | shown, greyed out, not usable | `403 { code: 'DISABLED' }` |
473
+ | `hidden` | not shown | `403 { code: 'HIDDEN' }` |
474
+
475
+ Anything else is refused as well: a state the gate does not know never lets a request through.
476
+
477
+ `accessService.userApiState(userId, apiName)` gives the state; `userHasApiAccess` is still there and is true only for `enabled`. Today a role mapping decides between `enabled` (the user holds a mapped role) and `hidden` (they do not). Nothing yet stores `disabled`, so it does not come out yet; callers should handle it now.
478
+
479
+ ### Every request is checked
480
+
481
+ An app made with `@xeplr/base-apis`' `createApp` never asks auth only "who is this". Its gate calls `GET /auth/api/verify` for every request it serves, naming that request, and auth answers both the token and the access state. The app has no setting that skips the access half.
482
+
483
+ ```
484
+ GET /auth/api/verify
485
+ Authorization: Bearer <the caller's token>
486
+ x-verify-method: GET
487
+ x-verify-path: /widget-templates/abc
488
+ ```
489
+
490
+ | answer | when |
491
+ |---|---|
492
+ | `200 { user, access, state: 'enabled', api }` | token good, API allowed. `api` is the catalog row it matched, or `null` (not registered, so open) |
493
+ | `403 { code: 'DISABLED' }` · `403 { code: 'HIDDEN' }` | token good, API not allowed |
494
+ | `401` | bad or expired token (the same tolerance and `X-New-Token` sliding as every route) |
495
+ | `400 { code: 'NO_REQUEST' }` | no method or path named: nothing to check, so refused |
496
+
497
+ **Which row a request is.** A catalog name is `METHOD path` or a bare path (every method), and a path may hold `:params`: `GET /widget-templates/:id` covers `GET /widget-templates/abc`. When several rows fit, more literal segments win, then a row with a method over one without (`lib/apiMatch.js`). The catalog names are cached under `access:api:catalog`, cleared with the other rules.
498
+
499
+ **Auth's own routes are checked the same way**, in-process: every signed-in route in `/auth/api` and every route in `/auth/api/admin` passes `accessGate()` (exported from `lib/accessMiddleware`) after the token check. Login, register, refresh and the other signed-out routes carry neither.
500
+
501
+ Three kinds of URL, and who gets them by default:
502
+
503
+ | kind | groups | default roles |
504
+ |---|---|---|
505
+ | system | `scope = 'system'` | Super Admin only, never mapped to a company role |
506
+ | admin | `users:*`, `access:*`, `settings:*` | Admin (0012); an app maps its own admin role, e.g. BI's CompanyAdmin |
507
+ | user | `account:*`, and an app's `*:view` / `*:create` / `*:edit` | every role that uses them |
508
+
509
+ These are migration defaults; the Access Matrix changes them.
510
+
511
+ **The consequence of switching this on:** an API mapped only to Super Admin is refused to everyone else. Map each registered API to every role that uses it.
512
+
513
+
514
+ ## Multi-tenancy
515
+
516
+ `userTenantsMapping` records membership: `userId`, `level` (`l1`–`l4`, matching `mtId1`–`mtId4`), `value` (the app's own id at that level — auth owns no tenant tree), an optional `roleId`, `isActive`. One row per user, level and value.
517
+
518
+ `@xeplr/db`'s `mtMiddleware` trusts whatever tenant header it is given. `mtMembershipMiddleware` is what checks it: for each configured slot whose header is present, the caller needs an active membership row with that value, or gets `403 Not authorized for <slot> "<value>"`. An absent header is left alone. It does nothing when multi-tenancy is not enabled.
519
+
520
+ ### Roles belong to a company
521
+
522
+ Two separate questions: **where** a row belongs (`mtId1`) and **who** may use it (`scope`, see [system scope](#system-scope)).
523
+
524
+ | row | `mtId1` |
525
+ |---|---|
526
+ | APIs, menus, pages, elements | `'*'`, generic: every company |
527
+ | System roles (Super Admin) and the seeded roles | `'*'` |
528
+ | Any other role | the company it was created in, from `AUTH_TENANT_HEADER`, even when Super Admin creates it |
529
+
530
+ - Creating a company role with no company selected is refused (`400`, `code: 'NO_COMPANY'`).
531
+ - Lists show the current company's roles and the generic ones. Another company's role is not found (`404`) for rename or delete.
532
+ - A role name is unique within its company (`409` otherwise), not across companies.
533
+ - With `AUTH_TENANT_HEADER=none` every role is generic, as before.
534
+ - Roles saved before this (no `mtId1`) are made generic by migration `0010`, so nothing disappears.
535
+
536
+ **Copy to companies.** Super Admin picks roles in one company and copies them into others: `POST /auth/api/admin/master/roles/copy { roleIds, companyIds }`. Each target gets an **independent** copy, with the same name and the same grants (apis, pages, elements, menus), that it can then change on its own. A company that already has a role of that name keeps its own: the copy is skipped and reported, never overwritten. System roles are not copied.
537
+
538
+ ```js
539
+ app.use(authMiddleware) // needs req.user.id
540
+ app.use(mtMiddleware()) // @xeplr/db
541
+ app.use(auth.mtMembershipMiddleware()) // auth initialised in this process
542
+ // auth running as its own service:
543
+ app.use(auth.mtMembershipMiddleware({ userTenantsMapping: authAttach.model('UserTenantsMapping') }))
544
+ ```
545
+
546
+ ## Hooks
547
+
548
+ ```js
549
+ auth.hooks.on('user', 'create', async function(id) { /* … */ })
550
+ ```
551
+
552
+ One handler per identifier and event — registering again replaces it. A handler that throws is logged and never breaks the operation.
553
+
554
+ | identifier | events |
555
+ |---|---|
556
+ | `user` | `create` (register, invite), `update` (activate, invite accepted, password and profile changes), `login` |
557
+ | `roles` | `create`, `update`, `delete` |
558
+ | `apis`, `pages`, `elements`, `menus` | `create`, `update`, `delete` — the `master` routes |
559
+ | `userRolesMapping` | `create`, `delete` |
560
+ | `apisRolesMapping`, `pagesRolesMapping`, `elementsRolesMapping`, `menusRolesMapping` | `create`, `delete` |
561
+
562
+ Hooks run in the process that did the work — register them in the same script that calls `boot()`, not in your API process.
563
+
564
+ ## Tests
565
+
566
+ ```sh
567
+ npm test # node --test test/*.test.js
568
+ ```
569
+
570
+ `test/menuItems.test.js` needs a local PostgreSQL (the usual `PG*` variables): it creates and drops a throwaway database, and is skipped when none is reachable. The token-decision and `REDIS_PREFIX` tests need nothing.
571
+
572
+ ## License
573
+
574
+ MIT
package/index.js CHANGED
@@ -21,6 +21,7 @@ const hooks = require('./lib/hooks');
21
21
  const mtMembershipMiddleware = require('./lib/mtMembershipMiddleware');
22
22
  const createAuthRouter = require('./lib/authRouter');
23
23
  const createAdminRouter = require('./lib/adminRouter');
24
+ const systemScope = require('./lib/systemScope');
24
25
  const models = require('./models');
25
26
 
26
27
  let _initialized = false;
@@ -372,6 +373,12 @@ var requiredEnv = [
372
373
  // lib/redisPrefix.js. init() also refuses the shared value itself, which a
373
374
  // presence check cannot.
374
375
  'REDIS_PREFIX',
376
+
377
+ // WHICH HEADER NAMES THE COMPANY a role is created in, or 'none' for a
378
+ // single-tenant app. Required with no default: a multi-tenant app that
379
+ // forgot it would create every role as '*' — visible to every company —
380
+ // and nothing would look wrong. See lib/tenant.js.
381
+ 'AUTH_TENANT_HEADER',
375
382
  ];
376
383
 
377
384
  // Read at ACCESS time so it reflects the .env the app has already loaded — the
@@ -409,6 +416,8 @@ module.exports = {
409
416
  authMiddleware,
410
417
  accessMiddleware,
411
418
  requireRole,
419
+ systemScopeGuard: systemScope.systemScopeGuard,
420
+ isSuperAdmin: systemScope.isSuperAdmin,
412
421
  mtMembershipMiddleware,
413
422
  authHelper,
414
423
  seedSuperAdmin,