@xeplr/auth 1.1.3 → 1.1.5

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,442 @@
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`, `userHasApiAccess`, `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_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 |
117
+
118
+ ### Optional
119
+
120
+ | variable | default | meaning |
121
+ |---|---|---|
122
+ | `AUTH_INVITE_URL` | derived | full address of your accept-invite page; `?token=…` is appended |
123
+ | `AUTH_ACTIVATION_BASE_URL` | — | older form: an origin; `/auth/activate` and `/auth/accept-invite` are appended when the two URLs above are unset |
124
+ | `AUTH_ACCESS_TOKEN_TTL_MINUTES` | `15` | access token lifetime |
125
+ | `AUTH_REFRESH_TOKEN_TTL_DAYS` | `7` | refresh token (session) lifetime |
126
+ | `AUTH_ACCESS_TOKEN_TOLERANCE_SECONDS` | `0` | grace after expiry during which a token is still served and slid; `0` turns sliding refresh off |
127
+ | `AUTH_MAX_SESSIONS_PER_USER` | `5` | concurrent sessions; the oldest are evicted |
128
+ | `AUTH_RESET_TOKEN_EXPIRY_MINUTES` | `30` | password reset link lifetime |
129
+ | `AUTH_ENABLE_HOOKS` | on | `false` turns every hook off |
130
+ | `REDIS_HOST` / `REDIS_PORT` | `127.0.0.1` / `6379` | the session store |
131
+ | `REDIS_PASSWORD` / `REDIS_DB` | none / `0` | read by `@xeplr/utils`' cache |
132
+ | `UPLOAD_DIR` | `./uploads` | where avatar uploads are written |
133
+ | `EMAIL_PROVIDER` | not configured | `smtp`, `brevo`, `aws` or `azure` |
134
+ | `SMTP_HOST`, `SMTP_PORT` (587), `SMTP_USER`, `SMTP_PASS`, `SMTP_FROM`, `SMTP_SECURE`, … | | SMTP settings, read by `@xeplr/utils` |
135
+ | `BREVO_API_KEY`, `BREVO_FROM_EMAIL`, `BREVO_FROM_NAME` | | Brevo |
136
+ | `AWS_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SES_FROM` | | Amazon SES |
137
+ | `AZURE_COMMUNICATION_CONNECTION_STRING`, `AZURE_EMAIL_FROM` | | Azure Communication Services |
138
+
139
+ ## REDIS_PREFIX is required
140
+
141
+ 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.
142
+
143
+ 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:
144
+
145
+ - the drawer shows another product's menus and drops its own;
146
+ - 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.
147
+
148
+ 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.
149
+
150
+ ```
151
+ 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.
152
+ ```
153
+
154
+ Fix: `REDIS_PREFIX=myapp:` — one value per app, the same in every process of that app.
155
+
156
+ ## Startup
157
+
158
+ **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.
159
+
160
+ **The banner** shows the effective configuration, defaults resolved, secrets masked:
161
+
162
+ ```
163
+ ┌─────────────────────────────────────────────────────────────┐
164
+ │ xeplr-auth · running │
165
+ ├─────────────────────────────────────────────────────────────┤
166
+ │ port 19001 │
167
+ │ database myapp_auth │
168
+ │ XEPLR_AUTH_MIGRATIONS./migrations-auth │
169
+ │ activation url http://localhost:19100/auth/activate │
170
+ │ invite url (derived) │
171
+ │ access token ttl 15m │
172
+ │ refresh token ttl 7d │
173
+ │ slide tolerance 0s │
174
+ │ max sessions/user 5 │
175
+ │ redis localhost:6379 │
176
+ │ redis prefix myapp: │
177
+ │ email ✓ smtp — smtp.example.com:587, connected │
178
+ │ connection XEPLR_DB_CONNECTION │
179
+ │ encryption key ✓ set │
180
+ │ jwt secret ✓ set │
181
+ └─────────────────────────────────────────────────────────────┘
182
+ ```
183
+
184
+ `connection` names the variable the connection was resolved through.
185
+
186
+ **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):
187
+
188
+ | row | meaning |
189
+ |---|---|
190
+ | `✓ smtp — host:port, connected` | mail can go out |
191
+ | `✗ 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 |
192
+ | `? not checked — @xeplr/utils is too old to check` | the installed `@xeplr/utils` has no `checkEmail` |
193
+
194
+ SMTP needs `nodemailer` installed in the app.
195
+
196
+ **Email is never fatal.** Sign-in, refresh and everything behind a token work without it. What cannot work is anything that sends a link:
197
+
198
+ - **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`.
199
+ - **Invites** (`authService.invite`) throw the same way.
200
+ - **Forgot password** answers `500` for an address that exists (and the usual message for one that does not).
201
+
202
+ ## Migrations
203
+
204
+ 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.
205
+
206
+ ```sh
207
+ AUTH_DB_NAME=myapp_auth xeplr-auth-migrate up --connection-env XEPLR_DB_CONNECTION
208
+ xeplr-auth-migrate status --connection-env XEPLR_DB_CONNECTION # completed, pending, and edited-after-applying
209
+ ```
210
+
211
+ | option | |
212
+ |---|---|
213
+ | `--db <name>` | database; default `AUTH_DB_NAME` |
214
+ | `--extDir <dir>[,<dir>…]` | app migration directories; default `XEPLR_AUTH_MIGRATIONS` |
215
+ | `--connection-env <VAR>` | read the encrypted connection from that variable |
216
+ | `--connection <encrypted>` | the encrypted connection itself |
217
+
218
+ 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.
219
+
220
+ **`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:
221
+
222
+ ```
223
+ XEPLR_AUTH_MIGRATIONS=./migrations-auth,./node_modules/@xeplr/factory/migrations-auth
224
+ ```
225
+
226
+ - **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.
227
+ - A directory that does not exist is an error, not an empty contribution.
228
+ - `${VAR}` in a file is replaced with `process.env.VAR`; an unset variable fails the migration by name.
229
+
230
+ Auth's own migrations:
231
+
232
+ | file | |
233
+ |---|---|
234
+ | `0001_extensions` | `pgcrypto` |
235
+ | `0002_users` | `users` |
236
+ | `0003_catalog_tables` | `roles`, `apis`, `uiPages`, `uiElements`, `menus` |
237
+ | `0004_role_mappings` | `apisRolesMapping`, `uiPagesRolesMapping`, `uiElementsRolesMapping`, `menuRolesMapping`, `userRolesMapping` |
238
+ | `0005_user_tenants_mapping` | `userTenantsMapping` |
239
+ | `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 |
240
+ | `0007_license_module` | `licenseModule` column (default `core`) on apis, menus, uiPages, uiElements |
241
+ | `0008_super_admin` | the first account |
242
+ | `0009_menu_labels` | `label`, `sortOrder`, `isHidden` on `menus` |
243
+
244
+ ## The first account
245
+
246
+ 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.
247
+
248
+ It is created **once**, when migrations first run on that database:
249
+
250
+ - Changing the variables later creates nothing — `0008` is already in the ledger and never runs again. The old account and its password stay.
251
+ - Pointing at an existing database keeps its accounts. If a user with that email already exists when `0008` runs, it keeps its password.
252
+
253
+ To add or change an account afterwards, use the app (or `seedSuperAdmin(knex, { email, password })` from your own migration code).
254
+
255
+ ## Sessions and tokens
256
+
257
+ 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.
258
+
259
+ | event | effect |
260
+ |---|---|
261
+ | login | new session; beyond `AUTH_MAX_SESSIONS_PER_USER` the oldest are ended |
262
+ | `POST /refresh` | the old pair is destroyed and a new pair issued, with roles re-read from the database |
263
+ | `POST /logout` | that session ends; its access token stops working immediately |
264
+ | reset or change password | every session of that user ends |
265
+
266
+ `authMiddleware` checks, in order: the signature, then that the session is still live in Redis (a logged-out token is never accepted), then expiry.
267
+
268
+ **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:
269
+
270
+ ```
271
+ X-New-Token: eyJhbGciOi…
272
+ Access-Control-Expose-Headers: X-New-Token
273
+ ```
274
+
275
+ 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.
276
+
277
+ ## Routes
278
+
279
+ ### `/auth/api`
280
+
281
+ | route | token | body / query → response |
282
+ |---|---|---|
283
+ | `POST /register` | — | `{ email, password, name?, phoneNumber? }` → `201 { message, user }`; `409` if the email is registered. Sends the activation email |
284
+ | `GET /activate` | — | `?token=…&workflowKey=…` → `{ message, user }` |
285
+ | `GET /invite-preview` | — | `?token=…` → `{ email, name }` |
286
+ | `POST /invite-accept` | — | `{ token, password, name? }` → sets the password and activates |
287
+ | `POST /login` | — | `{ email, password }` → `{ accessToken, refreshToken, user, access }`; `401` wrong password or deactivated; `403` not yet activated |
288
+ | `POST /refresh` | — | `{ refreshToken }` → a new `{ accessToken, refreshToken, user, access }` |
289
+ | `POST /logout` | — | `{ refreshToken }` → ends that session |
290
+ | `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) |
291
+ | `POST /reset-password` | — | `{ token, newPassword }` |
292
+ | `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims |
293
+ | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
294
+ | `POST /profile/avatar` | ✓ | multipart `avatar`, an image up to 2 MB; stores the file name only — serving `UPLOAD_DIR` is the app's job |
295
+ | `POST /change-password` | ✓ | `{ oldPassword, newPassword }`; ends every session |
296
+ | `POST /request-phone-otp` | ✓ | `{ phoneNumber? }` — needs an SMS provider registered with `@xeplr/utils` |
297
+ | `POST /verify-phone-otp` | ✓ | `{ code }` → `{ phoneVerified: true }` |
298
+ | `POST /sse-ticket` | ✓ | `{ scopes? }` (default `['user:me:*']`) → `{ ticket, expiresIn: 30 }` |
299
+
300
+ ### `/auth/api/admin`
301
+
302
+ **Every admin route requires a valid token — and most require nothing more.** Any signed-in user can call them unless you mount `accessMiddleware()` or `requireRole()` in front. Only the `menu-items` routes check a role themselves: **Super Admin**, read from the token's `roles` (403 otherwise).
303
+
304
+ | route | |
305
+ |---|---|
306
+ | `GET /users` | users with their roles |
307
+ | `GET /roles` | `[{ id, name }]` |
308
+ | `GET /access-items` | `{ apis, pages, elements, menus }`, each with its roles |
309
+ | `POST /user-role` | `{ userId, roleId, assign }` — grant or remove a role |
310
+ | `POST /access-role` | `{ type: apis\|pages\|elements\|menus, itemId, roleId, assign }` |
311
+ | `POST /module-role` | `{ module, action, roleId, assign }` — every item of every type whose group is `module:action` |
312
+ | `GET /master/<type>` | `<type>` is `roles`, `apis`, `pages`, `elements` or `menus` |
313
+ | `POST /master/<type>` | `{ id?, name, … }` — update with `id`, create without |
314
+ | `POST /master/<type>/delete` | `{ id }` |
315
+ | `GET /menu-items` | Super Admin — [menu keys and labels](#menu-keys-and-labels) |
316
+ | `POST /menu-items` | Super Admin — `{ items: [{ name, label, sortOrder, isHidden }] }` |
317
+ | `POST /menu-items/add` | Super Admin — `{ name, label, isPublic? }` |
318
+ | `POST /menu-items/remove` | Super Admin — `{ name }` |
319
+
320
+ ## The access object
321
+
322
+ `/login`, `/refresh` and `/me` return what the user may use — the union of their roles' mappings and every `isPublic` row:
323
+
324
+ ```json
325
+ {
326
+ "roles": ["Admin"],
327
+ "pages": ["Profile", "User Roles"],
328
+ "apis": ["/auth/api/me", "/auth/api/admin/users"],
329
+ "menus": ["Tasks", "Profile"],
330
+ "menuItems": [{ "name": "Tasks", "label": "TSK", "sortOrder": 1 }, { "name": "Profile", "label": "Profile", "sortOrder": null }],
331
+ "elements": ["Assign Role Button"]
332
+ }
333
+ ```
334
+
335
+ - `menus` are **keys** — what app code matches on.
336
+ - `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.
337
+
338
+ **Cached in Redis** (under `REDIS_PREFIX`):
339
+
340
+ | key | lifetime | cleared by |
341
+ |---|---|---|
342
+ | `access:user:<id>` — the object above | 5 min | that user's login, `POST /user-role` for that user, any `menu-items` change |
343
+ | `access:userRoles:<id>` — role ids for `accessMiddleware` | 5 min | that user's login, `POST /user-role` |
344
+ | `access:public` — public apis, pages, menus | 10 min | `access-role`, `module-role`, any delete, any `menu-items` change |
345
+ | `access:api:<name>` — one API's rule | 10 min | the same |
346
+
347
+ 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.
348
+
349
+ ## Menu keys and labels
350
+
351
+ Migration `0009` splits what code refers to from what people read:
352
+
353
+ | column | |
354
+ |---|---|
355
+ | `name` | the **key**. What app code matches in `drawerItems` / `settingsOverrides`, and what roles are mapped to. Never shown; never renamed |
356
+ | `label` | what people see. Empty shows the key |
357
+ | `sortOrder` | position in the rail; empty sorts after the numbered ones |
358
+ | `isHidden` | kept and still role-mapped, but not shown — reversible, unlike delete |
359
+
360
+ 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.
361
+
362
+ 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:
363
+
364
+ ```
365
+ GET /auth/api/admin/menu-items
366
+ → [{ id, name, label, shown, sortOrder, isHidden, isPublic, menuGroup }] every row, hidden included
367
+
368
+ POST /auth/api/admin/menu-items { "items": [{ "name": "Tasks", "label": "TSK", "sortOrder": 1, "isHidden": false }] }
369
+ → { changed } only label, sortOrder and isHidden change; label null or "" clears it; sortOrder is a whole number or null
370
+
371
+ POST /auth/api/admin/menu-items/add { "name": "form:crop", "label": "Crops", "isPublic": true }
372
+ → { name, created } e.g. a form added to the menu; public unless isPublic is false; placed last;
373
+ an existing key is relabelled and un-hidden instead of duplicated
374
+
375
+ POST /auth/api/admin/menu-items/remove { "name": "form:crop" }
376
+ → { removed } deletes the row and its role mappings
377
+ ```
378
+
379
+ Bad input answers `400` with the reason.
380
+
381
+ ## Access checks
382
+
383
+ **`accessMiddleware(options)`** guards your own API routes from the `apis` catalog:
384
+
385
+ ```js
386
+ app.use('/api', auth.accessMiddleware()) // API name = req.baseUrl + req.path, e.g. "/api/orders"
387
+ ```
388
+
389
+ | the API is | result |
390
+ |---|---|
391
+ | not in `apis` | open |
392
+ | `isPublic` | open |
393
+ | in `apis` with no roles mapped | open |
394
+ | mapped to roles | Bearer token required (signature and expiry — not the Redis session); `403 Access denied` unless the user holds one of those roles |
395
+
396
+ Pass `apiNameResolver(req)` to name APIs differently. Because unregistered means open, register every route that must be guarded.
397
+
398
+ **`requireRole('Admin', 'Super Admin')`** checks the role names in the token, with no database lookup.
399
+
400
+ ## Multi-tenancy
401
+
402
+ `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.
403
+
404
+ `@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.
405
+
406
+ ```js
407
+ app.use(authMiddleware) // needs req.user.id
408
+ app.use(mtMiddleware()) // @xeplr/db
409
+ app.use(auth.mtMembershipMiddleware()) // auth initialised in this process
410
+ // auth running as its own service:
411
+ app.use(auth.mtMembershipMiddleware({ userTenantsMapping: authAttach.model('UserTenantsMapping') }))
412
+ ```
413
+
414
+ ## Hooks
415
+
416
+ ```js
417
+ auth.hooks.on('user', 'create', async function(id) { /* … */ })
418
+ ```
419
+
420
+ One handler per identifier and event — registering again replaces it. A handler that throws is logged and never breaks the operation.
421
+
422
+ | identifier | events |
423
+ |---|---|
424
+ | `user` | `create` (register, invite), `update` (activate, invite accepted, password and profile changes), `login` |
425
+ | `roles` | `create`, `update`, `delete` |
426
+ | `apis`, `pages`, `elements`, `menus` | `create`, `update`, `delete` — the `master` routes |
427
+ | `userRolesMapping` | `create`, `delete` |
428
+ | `apisRolesMapping`, `pagesRolesMapping`, `elementsRolesMapping`, `menusRolesMapping` | `create`, `delete` |
429
+
430
+ Hooks run in the process that did the work — register them in the same script that calls `boot()`, not in your API process.
431
+
432
+ ## Tests
433
+
434
+ ```sh
435
+ npm test # node --test test/*.test.js
436
+ ```
437
+
438
+ `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.
439
+
440
+ ## License
441
+
442
+ MIT
@@ -4,6 +4,7 @@ const Api = require('../models/Api');
4
4
  const UiPage = require('../models/UiPage');
5
5
  const Menu = require('../models/Menu');
6
6
  const UiElement = require('../models/UiElement');
7
+ const { visibleItems } = require('./menuService');
7
8
 
8
9
  // Cache TTLs (seconds)
9
10
  const USER_ACCESS_TTL = 300; // 5 min — user's full access object
@@ -28,7 +29,7 @@ async function getUserAccess(userId) {
28
29
  .withGraphFetched('roles.[apis, uiPages, uiElements, menus]');
29
30
 
30
31
  if (!user || !user.roles) {
31
- const empty = { roles: [], pages: [], apis: [], menus: [], elements: [] };
32
+ const empty = { roles: [], pages: [], apis: [], menus: [], menuItems: [], elements: [] };
32
33
  await cache.set(userAccessKey(userId), empty, USER_ACCESS_TTL);
33
34
  return empty;
34
35
  }
@@ -36,7 +37,7 @@ async function getUserAccess(userId) {
36
37
  const roleNames = new Set();
37
38
  const pages = new Set();
38
39
  const apis = new Set();
39
- const menus = new Set();
40
+ const menuRows = [];
40
41
  const elements = new Set();
41
42
 
42
43
  for (const role of user.roles) {
@@ -49,7 +50,7 @@ async function getUserAccess(userId) {
49
50
  for (const page of role.uiPages) pages.add(page.name);
50
51
  }
51
52
  if (role.menus) {
52
- for (const menu of role.menus) menus.add(menu.name);
53
+ for (const menu of role.menus) menuRows.push(menu);
53
54
  }
54
55
  if (role.uiElements) {
55
56
  for (const el of role.uiElements) elements.add(el.name);
@@ -60,13 +61,19 @@ async function getUserAccess(userId) {
60
61
  const publicItems = await getPublicItems();
61
62
  for (const api of publicItems.apis) apis.add(api);
62
63
  for (const page of publicItems.pages) pages.add(page);
63
- for (const menu of publicItems.menus) menus.add(menu);
64
+ // Rows, not just names: a hidden item is left out, and each keeps its label
65
+ // and position. Caches written before labels existed carry names only.
66
+ for (const menu of publicItems.menuItems || publicItems.menus.map((name) => ({ name }))) menuRows.push(menu);
67
+ const menuItems = visibleItems(menuRows);
64
68
 
65
69
  const access = {
66
70
  roles: [...roleNames],
67
71
  pages: [...pages],
68
72
  apis: [...apis],
69
- menus: [...menus],
73
+ // KEYS — what the app's drawerItems / settingsOverrides match on.
74
+ menus: menuItems.map((m) => m.name),
75
+ // What to SHOW for each key, in rail order: [{ name, label, sortOrder }].
76
+ menuItems,
70
77
  elements: [...elements]
71
78
  };
72
79
 
@@ -90,7 +97,8 @@ async function getPublicItems() {
90
97
  const result = {
91
98
  apis: publicApis.map(a => a.name),
92
99
  pages: publicPages.map(p => p.name),
93
- menus: publicMenus.map(m => m.name)
100
+ menus: publicMenus.filter(m => !m.isHidden).map(m => m.name),
101
+ menuItems: publicMenus.map(m => ({ name: m.name, label: m.label || null, sortOrder: m.sortOrder === undefined ? null : m.sortOrder, isHidden: !!m.isHidden }))
94
102
  };
95
103
 
96
104
  await cache.set(publicItemsKey, result, API_RULES_TTL);
@@ -178,7 +186,16 @@ async function clearAccessRules() {
178
186
  ]);
179
187
  }
180
188
 
189
+ /** Every cached access answer — after the catalog itself changes (a menu renamed, added, hidden). */
190
+ async function clearAllAccess() {
191
+ await Promise.all([
192
+ clearAccessRules(),
193
+ cache.delPattern('access:user:*')
194
+ ]);
195
+ }
196
+
181
197
  module.exports = {
198
+ clearAllAccess,
182
199
  getUserAccess,
183
200
  userHasApiAccess,
184
201
  clearUserAccess,
@@ -1,6 +1,7 @@
1
1
  var express = require('express');
2
2
  var { generateId } = require('./authHelper');
3
- var { clearUserAccess, clearAccessRules } = require('./accessService');
3
+ var { clearUserAccess, clearAccessRules, clearAllAccess } = require('./accessService');
4
+ var { createMenuService } = require('./menuService');
4
5
  var authMiddleware = require('./authMiddleware');
5
6
  var hooks = require('./hooks');
6
7
  var User = require('../models/User');
@@ -248,6 +249,33 @@ function createAdminRouter() {
248
249
  }
249
250
  });
250
251
 
252
+ // ─── Menu items: key, label, order, visibility — Super Admin only ───
253
+ //
254
+ // The key (name) is what code matches on and never changes here; label,
255
+ // sortOrder and isHidden are what the app's "Configure UI" screen edits.
256
+ var menuItems = createMenuService({ Menu: Menu, MenuRolesMapping: MenuRolesMapping, clearAll: clearAllAccess });
257
+
258
+ function superAdminOnly(req, res, next) {
259
+ var roles = (req.user && req.user.roles) || [];
260
+ if (roles.indexOf('Super Admin') === -1) return res.status(403).json({ error: 'Only Super Admin can change the menu' });
261
+ next();
262
+ }
263
+
264
+ function menuRoute(fn) {
265
+ return [superAdminOnly, async function(req, res) {
266
+ try {
267
+ res.json(await fn(req));
268
+ } catch (err) {
269
+ res.status(err.status || 500).json({ error: err.status ? err.message : 'Something went wrong' });
270
+ }
271
+ }];
272
+ }
273
+
274
+ router.get('/menu-items', menuRoute(function() { return menuItems.list(); }));
275
+ router.post('/menu-items', menuRoute(function(req) { return menuItems.update(req.body && req.body.items); }));
276
+ router.post('/menu-items/add', menuRoute(function(req) { return menuItems.add(req.body); }));
277
+ router.post('/menu-items/remove', menuRoute(function(req) { return menuItems.remove(req.body && req.body.name); }));
278
+
251
279
  // ─── Master CRUD factory for APIs, Pages, Elements, Menus ───
252
280
  var masterTypes = {
253
281
  apis: { Model: Api, fields: ['name', 'apiGroup', 'isPublic'] },
@@ -0,0 +1,124 @@
1
+ // MENU ITEMS — key, label, order, visibility.
2
+ //
3
+ // A menu row's `name` is its KEY: what the app's code matches on
4
+ // (drawerItems: { key: 'Tasks' }) and what roles are mapped to. It never
5
+ // changes and is never shown. `label` is what people read — renamed from the
6
+ // app, no code or restart. Empty label shows the key.
7
+ //
8
+ // Everything here writes the catalog and then clears the access caches, so the
9
+ // next /auth/api/me — which the UI asks for straight after — carries the change.
10
+
11
+ var { generateId } = require('./authHelper');
12
+
13
+ var MAX_LABEL = 255;
14
+
15
+ /** { name, label, sortOrder } for the rows a user may see, hidden ones left out, in rail order. */
16
+ function visibleItems(menus) {
17
+ var seen = new Map();
18
+ (menus || []).forEach(function(m) {
19
+ if (!m || !m.name || m.isHidden || seen.has(m.name)) return;
20
+ seen.set(m.name, { name: m.name, label: m.label || m.name, sortOrder: m.sortOrder === undefined ? null : m.sortOrder });
21
+ });
22
+ return Array.from(seen.values()).sort(byOrder);
23
+ }
24
+
25
+ function byOrder(a, b) {
26
+ var ao = a.sortOrder === null || a.sortOrder === undefined ? Infinity : a.sortOrder;
27
+ var bo = b.sortOrder === null || b.sortOrder === undefined ? Infinity : b.sortOrder;
28
+ if (ao !== bo) return ao - bo;
29
+ return String(a.label).localeCompare(String(b.label));
30
+ }
31
+
32
+ function badRequest(message) {
33
+ var e = new Error(message);
34
+ e.status = 400;
35
+ return e;
36
+ }
37
+
38
+ /**
39
+ * @param deps.Menu bound Menu model
40
+ * @param deps.MenuRolesMapping bound MenuRolesMapping model
41
+ * @param deps.clearAll async () → clears every cached access answer
42
+ */
43
+ function createMenuService(deps) {
44
+ var Menu = deps.Menu;
45
+ var MenuRolesMapping = deps.MenuRolesMapping;
46
+
47
+ /** Every menu row, for the admin screen — hidden ones included. */
48
+ async function list() {
49
+ var rows = await Menu.query().select('id', 'name', 'label', 'sortOrder', 'isHidden', 'isPublic', 'menuGroup');
50
+ return rows.map(function(r) {
51
+ return { id: r.id, name: r.name, label: r.label || null, shown: r.label || r.name, sortOrder: r.sortOrder === undefined ? null : r.sortOrder, isHidden: !!r.isHidden, isPublic: !!r.isPublic, menuGroup: r.menuGroup || '' };
52
+ }).sort(function(a, b) { return byOrder({ sortOrder: a.sortOrder, label: a.shown }, { sortOrder: b.sortOrder, label: b.shown }); });
53
+ }
54
+
55
+ /**
56
+ * Rename, reorder, hide — by key. Only label / sortOrder / isHidden change;
57
+ * the key itself cannot, since code and role mappings refer to it.
58
+ * @param items [{ name, label?, sortOrder?, isHidden? }]
59
+ */
60
+ async function update(items) {
61
+ if (!Array.isArray(items) || !items.length) throw badRequest('items: [{ name, label, sortOrder, isHidden }]');
62
+ var changed = 0;
63
+ for (var i = 0; i < items.length; i++) {
64
+ var item = items[i] || {};
65
+ if (!item.name) throw badRequest('items[' + i + '].name is required — it is the key');
66
+ var patch = {};
67
+ if (item.label !== undefined) {
68
+ var label = item.label === null ? '' : String(item.label).trim();
69
+ if (label.length > MAX_LABEL) throw badRequest('items[' + i + '].label is longer than ' + MAX_LABEL);
70
+ patch.label = label || null;
71
+ }
72
+ if (item.sortOrder !== undefined) {
73
+ if (item.sortOrder !== null && !Number.isInteger(item.sortOrder)) throw badRequest('items[' + i + '].sortOrder must be a whole number');
74
+ patch.sortOrder = item.sortOrder;
75
+ }
76
+ if (item.isHidden !== undefined) patch.isHidden = !!item.isHidden;
77
+ if (!Object.keys(patch).length) continue;
78
+ changed += await Menu.query().patch(patch).where({ name: item.name });
79
+ }
80
+ await deps.clearAll();
81
+ return { changed: changed };
82
+ }
83
+
84
+ /**
85
+ * A new menu item — e.g. a form added to the menu from the app. Shown to
86
+ * everyone signed in (isPublic) unless told otherwise; an existing key is
87
+ * relabelled and shown again rather than duplicated.
88
+ */
89
+ async function add(item) {
90
+ item = item || {};
91
+ var name = String(item.name || '').trim();
92
+ if (!name) throw badRequest('name is required — the key the app matches on, e.g. "form:crop"');
93
+ if (name.length > MAX_LABEL) throw badRequest('name is longer than ' + MAX_LABEL);
94
+ var label = item.label ? String(item.label).trim().slice(0, MAX_LABEL) : null;
95
+ var existing = await Menu.query().findOne({ name: name });
96
+ if (existing) {
97
+ await Menu.query().patch({ label: label || existing.label || null, isHidden: false }).where({ name: name });
98
+ } else {
99
+ var top = await Menu.query().max('sortOrder as max').first();
100
+ await Menu.query().insert({
101
+ id: generateId(), name: name, label: label, menuGroup: item.menuGroup || '',
102
+ isPublic: item.isPublic === false ? 0 : 1, isHidden: false, isActive: true, mtId1: '*',
103
+ sortOrder: top && top.max !== null && top.max !== undefined ? Number(top.max) + 1 : null
104
+ });
105
+ }
106
+ await deps.clearAll();
107
+ return { name: name, created: !existing };
108
+ }
109
+
110
+ /** Remove an item the app added (and its role mappings). */
111
+ async function remove(name) {
112
+ if (!name) throw badRequest('name is required');
113
+ var row = await Menu.query().findOne({ name: name });
114
+ if (!row) return { removed: false };
115
+ await MenuRolesMapping.query().delete().where({ menuId: row.id });
116
+ await Menu.query().deleteById(row.id);
117
+ await deps.clearAll();
118
+ return { removed: true };
119
+ }
120
+
121
+ return { list: list, update: update, add: add, remove: remove };
122
+ }
123
+
124
+ module.exports = { createMenuService: createMenuService, visibleItems: visibleItems };
@@ -0,0 +1,13 @@
1
+ -- 0009_menu_labels.sql
2
+ --
3
+ -- A menu item's NAME is its key: what code refers to (drawerItems), what roles
4
+ -- are mapped to, never shown. Its LABEL is what people read, and can be renamed
5
+ -- in the app without touching code. Empty label → the name is shown.
6
+ --
7
+ -- label shown text ("TSK" for the key "Tasks")
8
+ -- sortOrder position in the rail; empty sorts after the numbered ones
9
+ -- isHidden kept, still role-mapped, but not shown — reversible, unlike delete
10
+
11
+ ALTER TABLE "menus" ADD COLUMN IF NOT EXISTS "label" varchar(255);
12
+ ALTER TABLE "menus" ADD COLUMN IF NOT EXISTS "sortOrder" integer;
13
+ ALTER TABLE "menus" ADD COLUMN IF NOT EXISTS "isHidden" boolean NOT NULL DEFAULT false;
package/models/Menu.js CHANGED
@@ -15,6 +15,9 @@ class Menu extends BaseModel {
15
15
  id: { type: 'string', maxLength: 25 },
16
16
  name: { type: ['string', 'null'], maxLength: 255 },
17
17
  menuGroup: { type: ['string', 'null'], maxLength: 255 },
18
+ label: { type: ['string', 'null'], maxLength: 255 },
19
+ sortOrder: { type: ['integer', 'null'] },
20
+ isHidden: { type: 'boolean' },
18
21
  isPublic: { type: 'integer' },
19
22
  recordCreatedDate: { type: ['string', 'null'] },
20
23
  recordModifiedDate: { type: ['string', 'null'] },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.1.3",
3
+ "version": "1.1.5",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [