@xeplr/auth 1.1.5 → 1.1.7

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 CHANGED
@@ -86,7 +86,7 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName })
86
86
  | `requireRole(...names)` | 403 unless `req.user.roles` holds one of the names; use after `authMiddleware` |
87
87
  | `mtMembershipMiddleware(options)` | 403 when a tenant header names a value the caller has no membership for |
88
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` |
89
+ | `accessService` | `getUserAccess`, `userApiState`, `userHasApiAccess`, `apiStateFor`, `ACCESS_STATES`, `getApiRule`, `getPublicItems`, `clearUserAccess`, `clearAccessRules`, `clearAllAccess` |
90
90
  | `sessionService` | `createSession`, `getSession`, `validateAccessToken`, `slideAccessToken`, `rotateSession`, `destroySession`, `destroyAllUserSessions` |
91
91
  | `ticketService` | `issueTicket`, `consumeTicket` — single-use 30-second tickets for SSE / WebSocket |
92
92
  | `authHelper` | `configure`, `hashPassword`, `comparePassword`, `generateAccessToken`, `verifyToken`, `decodeVerified`, `generateId`, … |
@@ -113,6 +113,7 @@ Everything in `requiredEnv`, plus a connection and an activation link.
113
113
  | `AUTH_SUPER_ADMIN_EMAIL` | — | the first account, used by migration `0008` — [details](#the-first-account) |
114
114
  | `AUTH_SUPER_ADMIN_PASSWORD` | — | its password; no quotes, spaces, `$` or `#` (substituted into SQL) |
115
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) |
116
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 |
117
118
 
118
119
  ### Optional
@@ -240,6 +241,10 @@ Auth's own migrations:
240
241
  | `0007_license_module` | `licenseModule` column (default `core`) on apis, menus, uiPages, uiElements |
241
242
  | `0008_super_admin` | the first account |
242
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
+ | `0013_mapping_state` | `state` (`enabled` / `disabled`) on the four role-mapping tables, default `enabled`; the `module-states` and `module-state` rows, mapped to Super Admin and Admin |
243
248
 
244
249
  ## The first account
245
250
 
@@ -290,6 +295,7 @@ Client code must read the header and replace its stored token, or the session en
290
295
  | `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
296
  | `POST /reset-password` | — | `{ token, newPassword }` |
292
297
  | `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims |
298
+ | `GET /verify` | ✓ | the check every app's gate makes on every request — see [Every request is checked](#every-request-is-checked) |
293
299
  | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
294
300
  | `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
301
  | `POST /change-password` | ✓ | `{ oldPassword, newPassword }`; ends every session |
@@ -299,12 +305,12 @@ Client code must read the header and replace its stored token, or the session en
299
305
 
300
306
  ### `/auth/api/admin`
301
307
 
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).
308
+ **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.
303
309
 
304
310
  | route | |
305
311
  |---|---|
306
312
  | `GET /users` | users with their roles |
307
- | `GET /roles` | `[{ id, name }]` |
313
+ | `GET /roles` | `[{ id, name, scope, mtId1 }]`: the current company's roles and the generic ones; system roles only for Super Admin |
308
314
  | `GET /access-items` | `{ apis, pages, elements, menus }`, each with its roles |
309
315
  | `POST /user-role` | `{ userId, roleId, assign }` — grant or remove a role |
310
316
  | `POST /access-role` | `{ type: apis\|pages\|elements\|menus, itemId, roleId, assign }` |
@@ -312,6 +318,8 @@ Client code must read the header and replace its stored token, or the session en
312
318
  | `GET /master/<type>` | `<type>` is `roles`, `apis`, `pages`, `elements` or `menus` |
313
319
  | `POST /master/<type>` | `{ id?, name, … }` — update with `id`, create without |
314
320
  | `POST /master/<type>/delete` | `{ id }` |
321
+ | `POST /master/roles/copy` | Super Admin — `{ roleIds, companyIds }` → `{ copied: [{ roleId, companyId, newRoleId }], skipped: [{ roleId, companyId, reason }] }` |
322
+ | `POST /master/apis/scope` | Super Admin — `{ id, scope: 'system' \| 'company' }`: the "Super Admin only" switch; refused for a locked API |
315
323
  | `GET /menu-items` | Super Admin — [menu keys and labels](#menu-keys-and-labels) |
316
324
  | `POST /menu-items` | Super Admin — `{ items: [{ name, label, sortOrder, isHidden }] }` |
317
325
  | `POST /menu-items/add` | Super Admin — `{ name, label, isPublic? }` |
@@ -378,6 +386,64 @@ POST /auth/api/admin/menu-items/remove { "name": "form:crop" }
378
386
 
379
387
  Bad input answers `400` with the reason.
380
388
 
389
+ ### System scope
390
+
391
+ 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.
392
+
393
+ | | Super Admin | Everyone else |
394
+ |---|---|---|
395
+ | A **system API** | allowed | refused `403` (`code: 'SYSTEM_SCOPE'`), whatever the role mappings say |
396
+ | A **system role** (Super Admin itself) | sees, edits, assigns | never listed, cannot assign or change |
397
+ | Granting a system API to a role | refused: system APIs are never granted | refused |
398
+
399
+ 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.
400
+
401
+ **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.
402
+
403
+ **Two ways to make an API system:**
404
+
405
+ - **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.
406
+ - **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.
407
+
408
+ 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.
409
+
410
+ **Registering a product's own system API** is one row in the product's `migrations-auth` directory, with no change here:
411
+
412
+ ```sql
413
+ INSERT INTO "apis" (id, name, "apiGroup", "scope", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
414
+ SELECT encode(gen_random_bytes(12), 'hex'), 'POST /api/licences/assign', 'licences:edit', 'system', false, true, '*', now(), now()
415
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" WHERE name = 'POST /api/licences/assign');
416
+ ```
417
+
418
+ To make APIs that are already registered system APIs, update their rows the same way:
419
+
420
+ ```sql
421
+ UPDATE "apis" SET "scope" = 'system'
422
+ WHERE name IN ('POST /api/licences/assign', '/api/companies/create') AND "scope" <> 'system';
423
+ ```
424
+
425
+ and the product mounts the guard in front of its routes, after its auth check:
426
+
427
+ ```js
428
+ const { systemScopeGuard } = require('@xeplr/auth');
429
+ router.use(systemScopeGuard());
430
+ ```
431
+
432
+ 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.
433
+
434
+ 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.
435
+
436
+ **The role routes:**
437
+
438
+ ```
439
+ GET /auth/api/admin/master/roles → [{ id, name, scope }] no system roles unless Super Admin
440
+ POST /auth/api/admin/master/roles { "name": "Workspace Admin" } → { id } system: create (scope 'company' unless given)
441
+ POST /auth/api/admin/master/roles { "id": "…", "name": "Workspace Admins" } → { id } system: rename
442
+ POST /auth/api/admin/master/roles/delete { "id": "…" } → { ok } system
443
+ ```
444
+
445
+ 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.
446
+
381
447
  ## Access checks
382
448
 
383
449
  **`accessMiddleware(options)`** guards your own API routes from the `apis` catalog:
@@ -391,18 +457,106 @@ app.use('/api', auth.accessMiddleware()) // API name = req.baseUrl + req.p
391
457
  | not in `apis` | open |
392
458
  | `isPublic` | open |
393
459
  | 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 |
460
+ | mapped to roles | Bearer token required (signature and expiry — not the Redis session), then the user's [access state](#access-states) |
395
461
 
396
462
  Pass `apiNameResolver(req)` to name APIs differently. Because unregistered means open, register every route that must be guarded.
397
463
 
398
464
  **`requireRole('Admin', 'Super Admin')`** checks the role names in the token, with no database lookup.
399
465
 
466
+ ### Access states
467
+
468
+ The gate answers one of three states, not true/false. Only `enabled` goes through:
469
+
470
+ | state | means | `accessMiddleware` |
471
+ |---|---|---|
472
+ | `enabled` | shown and usable | passes |
473
+ | `disabled` | shown, greyed out, not usable | `403 { code: 'DISABLED' }` |
474
+ | `hidden` | not shown | `403 { code: 'HIDDEN' }` |
475
+
476
+ Anything else is refused as well: a state the gate does not know never lets a request through.
477
+
478
+ `accessService.userApiState(userId, apiName)` gives the state; `userHasApiAccess` is still there and is true only for `enabled`.
479
+
480
+ Where each state comes from, for a role:
481
+
482
+ | state | stored as |
483
+ |---|---|
484
+ | `hidden` | no mapping row |
485
+ | `enabled` | a mapping row, `state = 'enabled'` (the default) |
486
+ | `disabled` | a mapping row, `state = 'disabled'` (`0013_mapping_state`) |
487
+
488
+ A user with several roles gets the most open answer: one role with it enabled is enough. Workspace and user overrides are not stored yet.
489
+
490
+ The access object leaves disabled items out of `apis`, `pages` and `elements` (what callers check) and lists them under `disabled: { apis, pages, elements, menus }`. A disabled menu stays in `menuItems` with `disabled: true`, so a UI can grey it out instead of dropping it.
491
+
492
+ Set from the Access Matrix, through two admin routes:
493
+
494
+ | route | |
495
+ |---|---|
496
+ | `GET /module-states?scope=role` | `[{ module, action, roleId, state: 'disabled' }]` for the roles the caller can see |
497
+ | `POST /module-state` | `{ scope: 'role', roleId, module, action, state }`: `disabled` greys out every item of that module/action the role is mapped to; `enabled`, `inherit` or `null` clears it. `hidden` is refused (`BAD_STATE`): hidden is removing the mapping, through `module-role` |
498
+
499
+ Any other `scope` answers `400 SCOPE_NOT_SUPPORTED`.
500
+
501
+ ### Every request is checked
502
+
503
+ 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.
504
+
505
+ ```
506
+ GET /auth/api/verify
507
+ Authorization: Bearer <the caller's token>
508
+ x-verify-method: GET
509
+ x-verify-path: /widget-templates/abc
510
+ ```
511
+
512
+ | answer | when |
513
+ |---|---|
514
+ | `200 { user, access, state: 'enabled', api }` | token good, API allowed. `api` is the catalog row it matched, or `null` (not registered, so open) |
515
+ | `403 { code: 'DISABLED' }` · `403 { code: 'HIDDEN' }` | token good, API not allowed |
516
+ | `401` | bad or expired token (the same tolerance and `X-New-Token` sliding as every route) |
517
+ | `400 { code: 'NO_REQUEST' }` | no method or path named: nothing to check, so refused |
518
+
519
+ **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.
520
+
521
+ **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.
522
+
523
+ Three kinds of URL, and who gets them by default:
524
+
525
+ | kind | groups | default roles |
526
+ |---|---|---|
527
+ | system | `scope = 'system'` | Super Admin only, never mapped to a company role |
528
+ | admin | `users:*`, `access:*`, `settings:*` | Admin (0012); an app maps its own admin role, e.g. BI's CompanyAdmin |
529
+ | user | `account:*`, and an app's `*:view` / `*:create` / `*:edit` | every role that uses them |
530
+
531
+ These are migration defaults; the Access Matrix changes them.
532
+
533
+ **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.
534
+
535
+
400
536
  ## Multi-tenancy
401
537
 
402
538
  `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
539
 
404
540
  `@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
541
 
542
+ ### Roles belong to a company
543
+
544
+ Two separate questions: **where** a row belongs (`mtId1`) and **who** may use it (`scope`, see [system scope](#system-scope)).
545
+
546
+ | row | `mtId1` |
547
+ |---|---|
548
+ | APIs, menus, pages, elements | `'*'`, generic: every company |
549
+ | System roles (Super Admin) and the seeded roles | `'*'` |
550
+ | Any other role | the company it was created in, from `AUTH_TENANT_HEADER`, even when Super Admin creates it |
551
+
552
+ - Creating a company role with no company selected is refused (`400`, `code: 'NO_COMPANY'`).
553
+ - Lists show the current company's roles and the generic ones. Another company's role is not found (`404`) for rename or delete.
554
+ - A role name is unique within its company (`409` otherwise), not across companies.
555
+ - With `AUTH_TENANT_HEADER=none` every role is generic, as before.
556
+ - Roles saved before this (no `mtId1`) are made generic by migration `0010`, so nothing disappears.
557
+
558
+ **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.
559
+
406
560
  ```js
407
561
  app.use(authMiddleware) // needs req.user.id
408
562
  app.use(mtMiddleware()) // @xeplr/db
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,
@@ -1,9 +1,12 @@
1
1
  const { verifyToken } = require('./authHelper');
2
- const { getApiRule, userHasApiAccess } = require('./accessService');
2
+ const accessService = require('./accessService');
3
+ const { getApiRule, userApiState } = accessService;
3
4
 
4
5
  /**
5
6
  * Access-aware middleware.
6
- * Uses Redis-cached API rules: isPublic → unmapped → role check.
7
+ * Uses Redis-cached API rules: isPublic → unmapped → the user's state.
8
+ * Only 'enabled' goes through; 'disabled' and 'hidden' are refused, each with
9
+ * its own code so a UI can tell them apart.
7
10
  *
8
11
  * Usage:
9
12
  * app.use('/api', accessMiddleware());
@@ -42,13 +45,39 @@ function accessMiddleware(options = {}) {
42
45
 
43
46
  req.user = decoded;
44
47
 
45
- // Check role-based access (also cached)
46
- const hasAccess = await userHasApiAccess(decoded.id, apiName);
47
- if (!hasAccess) {
48
- return res.status(403).json({ error: 'Access denied' });
48
+ // The user's state for this API (also cached)
49
+ var state = await userApiState(decoded.id, apiName);
50
+ if (state === 'enabled') return next();
51
+ if (state === 'disabled') {
52
+ return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
49
53
  }
54
+ return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
55
+ };
56
+ }
50
57
 
51
- next();
58
+ /**
59
+ * The access check for auth's OWN routes, in-process. The same answer the
60
+ * other apps get from GET /verify: the catalog row this request matches
61
+ * (method, path, :params), then the user's state for it. Mount after the
62
+ * token check, so req.user is set.
63
+ *
64
+ * Refuses on error: "cannot tell" is never "allowed".
65
+ */
66
+ function accessGate() {
67
+ return async function(req, res, next) {
68
+ var path = (req.baseUrl || '') + (req.path || '');
69
+ var answer;
70
+ try {
71
+ answer = await accessService.requestApiState(req.user && req.user.id, req.method, path);
72
+ } catch (err) {
73
+ if (req.log) req.log.error('access check failed: ' + err.message);
74
+ return res.status(503).json({ error: 'Access rules are unavailable; try again shortly' });
75
+ }
76
+ if (answer.state === 'enabled') return next();
77
+ if (answer.state === 'disabled') {
78
+ return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
79
+ }
80
+ return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
52
81
  };
53
82
  }
54
83
 
@@ -76,4 +105,4 @@ function requireRole(...roles) {
76
105
  };
77
106
  }
78
107
 
79
- module.exports = { accessMiddleware, requireRole };
108
+ module.exports = { accessMiddleware, accessGate, requireRole };
@@ -5,6 +5,7 @@ const UiPage = require('../models/UiPage');
5
5
  const Menu = require('../models/Menu');
6
6
  const UiElement = require('../models/UiElement');
7
7
  const { visibleItems } = require('./menuService');
8
+ const { matchApi } = require('./apiMatch');
8
9
 
9
10
  // Cache TTLs (seconds)
10
11
  const USER_ACCESS_TTL = 300; // 5 min — user's full access object
@@ -14,6 +15,7 @@ const API_RULES_TTL = 600; // 10 min — api public/role data (changes rare
14
15
  const userAccessKey = (userId) => `access:user:${userId}`;
15
16
  const apiRulesKey = (apiName) => `access:api:${encodeURIComponent(apiName)}`;
16
17
  const publicItemsKey = 'access:public';
18
+ const catalogKey = 'access:api:catalog'; // under access:api:*, so clearAccessRules() clears it
17
19
 
18
20
  /**
19
21
  * Fetch the full access object for a user.
@@ -40,21 +42,31 @@ async function getUserAccess(userId) {
40
42
  const menuRows = [];
41
43
  const elements = new Set();
42
44
 
45
+ // A DISABLED mapping (the row's state) is shown but not usable: it stays
46
+ // out of apis / pages / elements, which is what callers check, and is
47
+ // listed under `disabled` instead. A menu stays on the rail, marked
48
+ // disabled, so the UI can grey it out rather than drop it.
49
+ const disabledApis = new Set();
50
+ const disabledPages = new Set();
51
+ const disabledElements = new Set();
52
+ const disabledMenus = new Set();
53
+ const enabledMenus = new Set();
54
+ function sortInto(rows, enabled, disabled) {
55
+ for (const row of rows || []) {
56
+ if (row.state === 'disabled') disabled.add(row.name);
57
+ else enabled.add(row.name);
58
+ }
59
+ }
60
+
43
61
  for (const role of user.roles) {
44
62
  roleNames.add(role.name);
45
-
46
- if (role.apis) {
47
- for (const api of role.apis) apis.add(api.name);
48
- }
49
- if (role.uiPages) {
50
- for (const page of role.uiPages) pages.add(page.name);
51
- }
63
+ sortInto(role.apis, apis, disabledApis);
64
+ sortInto(role.uiPages, pages, disabledPages);
65
+ sortInto(role.uiElements, elements, disabledElements);
66
+ sortInto(role.menus, enabledMenus, disabledMenus);
52
67
  if (role.menus) {
53
68
  for (const menu of role.menus) menuRows.push(menu);
54
69
  }
55
- if (role.uiElements) {
56
- for (const el of role.uiElements) elements.add(el.name);
57
- }
58
70
  }
59
71
 
60
72
  // Add public items
@@ -64,7 +76,12 @@ async function getUserAccess(userId) {
64
76
  // Rows, not just names: a hidden item is left out, and each keeps its label
65
77
  // and position. Caches written before labels existed carry names only.
66
78
  for (const menu of publicItems.menuItems || publicItems.menus.map((name) => ({ name }))) menuRows.push(menu);
67
- const menuItems = visibleItems(menuRows);
79
+ for (const name of publicItems.menus || []) enabledMenus.add(name);
80
+ // Enabled through any role (or public) beats disabled through another.
81
+ const menuItems = visibleItems(menuRows).map(function(m) {
82
+ return (disabledMenus.has(m.name) && !enabledMenus.has(m.name)) ? Object.assign({}, m, { disabled: true }) : m;
83
+ });
84
+ function notIn(set, enabled) { return [...set].filter(function(n) { return !enabled.has(n); }); }
68
85
 
69
86
  const access = {
70
87
  roles: [...roleNames],
@@ -74,7 +91,14 @@ async function getUserAccess(userId) {
74
91
  menus: menuItems.map((m) => m.name),
75
92
  // What to SHOW for each key, in rail order: [{ name, label, sortOrder }].
76
93
  menuItems,
77
- elements: [...elements]
94
+ elements: [...elements],
95
+ // Shown greyed out, not usable: { apis, pages, elements, menus } names.
96
+ disabled: {
97
+ apis: notIn(disabledApis, apis),
98
+ pages: notIn(disabledPages, pages),
99
+ elements: notIn(disabledElements, elements),
100
+ menus: notIn(disabledMenus, enabledMenus)
101
+ }
78
102
  };
79
103
 
80
104
  await cache.set(userAccessKey(userId), access, USER_ACCESS_TTL);
@@ -125,12 +149,17 @@ async function getApiRule(apiName) {
125
149
  return rule;
126
150
  }
127
151
 
128
- const roleIds = (api.roles || []).map(r => r.id);
152
+ // roleIds: roles that may use it. disabledRoleIds: roles that see it
153
+ // greyed out (the mapping row's state). Unmapped only when neither has any.
154
+ var mapped = api.roles || [];
155
+ var roleIds = mapped.filter(function(r) { return r.state !== 'disabled'; }).map(function(r) { return r.id; });
156
+ var disabledRoleIds = mapped.filter(function(r) { return r.state === 'disabled'; }).map(function(r) { return r.id; });
129
157
  const rule = {
130
158
  exists: true,
131
159
  isPublic: !!api.isPublic,
132
- unmapped: roleIds.length === 0,
133
- roleIds
160
+ unmapped: mapped.length === 0,
161
+ roleIds,
162
+ disabledRoleIds
134
163
  };
135
164
 
136
165
  await cache.set(cacheKey, rule, API_RULES_TTL);
@@ -138,30 +167,83 @@ async function getApiRule(apiName) {
138
167
  }
139
168
 
140
169
  /**
141
- * Check if a user has access to a specific API.
142
- * Uses cached API rules and cached user roles.
170
+ * Access states. A gate answers one of these, not true/false:
171
+ *
172
+ * enabled shown and usable
173
+ * disabled shown, greyed out, not usable: the API refuses it
174
+ * hidden not shown: the API refuses it
175
+ *
176
+ * A role mapping row decides: no row → hidden; a row → its state (enabled,
177
+ * or disabled from the Access Matrix). Several roles: the most open wins.
143
178
  */
144
- async function userHasApiAccess(userId, apiName) {
145
- const rule = await getApiRule(apiName);
179
+ var ACCESS_STATES = ['enabled', 'disabled', 'hidden'];
146
180
 
181
+ /**
182
+ * The state for an API rule and a user's role ids. Pure, so it can be tested
183
+ * without a database.
184
+ */
185
+ function apiStateFor(rule, userRoleIds) {
147
186
  // Not registered in DB, or marked public, or no role mappings = open
148
- if (!rule.exists || rule.isPublic || rule.unmapped) return true;
187
+ if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
188
+ var userRoleSet = new Set(userRoleIds || []);
189
+ function holds(ids) { return (ids || []).some(function(id) { return userRoleSet.has(id); }); }
190
+ // One role that may use it is enough; disabled only when every role the
191
+ // user holds for it has it disabled.
192
+ if (holds(rule.roleIds)) return 'enabled';
193
+ if (holds(rule.disabledRoleIds)) return 'disabled';
194
+ return 'hidden';
195
+ }
149
196
 
150
- // Get user's role IDs (from user access cache)
151
- const userRoleCacheKey = `access:userRoles:${userId}`;
152
- let userRoleIds = await cache.get(userRoleCacheKey);
197
+ /** The user's role ids, cached for the gate. */
198
+ async function userRoleIdsOf(userId) {
199
+ var userRoleCacheKey = `access:userRoles:${userId}`;
200
+ var userRoleIds = await cache.get(userRoleCacheKey);
201
+ if (userRoleIds) return userRoleIds;
153
202
 
154
- if (!userRoleIds) {
155
- const user = await User.query()
156
- .findById(userId)
157
- .withGraphFetched('roles');
203
+ var user = await User.query()
204
+ .findById(userId)
205
+ .withGraphFetched('roles');
158
206
 
159
- userRoleIds = (user && user.roles) ? user.roles.map(r => r.id) : [];
160
- await cache.set(userRoleCacheKey, userRoleIds, USER_ACCESS_TTL);
161
- }
207
+ userRoleIds = (user && user.roles) ? user.roles.map(function(r) { return r.id; }) : [];
208
+ await cache.set(userRoleCacheKey, userRoleIds, USER_ACCESS_TTL);
209
+ return userRoleIds;
210
+ }
211
+
212
+ /**
213
+ * A user's state for a specific API: 'enabled' | 'disabled' | 'hidden'.
214
+ * Uses cached API rules and cached user roles.
215
+ */
216
+ async function userApiState(userId, apiName) {
217
+ var rule = await getApiRule(apiName);
218
+ if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
219
+ return apiStateFor(rule, await userRoleIdsOf(userId));
220
+ }
162
221
 
163
- const userRoleSet = new Set(userRoleIds);
164
- return rule.roleIds.some(id => userRoleSet.has(id));
222
+ /** Every API name in the catalog, cached like the other access rules. */
223
+ async function catalogApiNames() {
224
+ var cached = await cache.get(catalogKey);
225
+ if (Array.isArray(cached)) return cached;
226
+ var rows = await Api.query().select('name');
227
+ var names = rows.map(function(r) { return r.name; });
228
+ await cache.set(catalogKey, names, API_RULES_TTL);
229
+ return names;
230
+ }
231
+
232
+ /**
233
+ * A user's state for a REQUEST: the catalog row it matches (method, path,
234
+ * :params), then that row's state. Not registered → enabled (open).
235
+ *
236
+ * @returns { api, state } api is the matched name, or null
237
+ */
238
+ async function requestApiState(userId, method, path) {
239
+ var api = matchApi(await catalogApiNames(), method, path);
240
+ if (!api) return { api: null, state: 'enabled' };
241
+ return { api: api, state: await userApiState(userId, api) };
242
+ }
243
+
244
+ /** True only when the state is enabled. Kept for callers that want a yes/no. */
245
+ async function userHasApiAccess(userId, apiName) {
246
+ return (await userApiState(userId, apiName)) === 'enabled';
165
247
  }
166
248
 
167
249
  /**
@@ -195,8 +277,12 @@ async function clearAllAccess() {
195
277
  }
196
278
 
197
279
  module.exports = {
280
+ ACCESS_STATES,
281
+ apiStateFor,
198
282
  clearAllAccess,
199
283
  getUserAccess,
284
+ requestApiState,
285
+ userApiState,
200
286
  userHasApiAccess,
201
287
  clearUserAccess,
202
288
  clearAccessRules,