@xeplr/auth 1.1.5 → 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 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,9 @@ 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 |
243
247
 
244
248
  ## The first account
245
249
 
@@ -290,6 +294,7 @@ Client code must read the header and replace its stored token, or the session en
290
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) |
291
295
  | `POST /reset-password` | — | `{ token, newPassword }` |
292
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) |
293
298
  | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
294
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 |
295
300
  | `POST /change-password` | ✓ | `{ oldPassword, newPassword }`; ends every session |
@@ -299,12 +304,12 @@ Client code must read the header and replace its stored token, or the session en
299
304
 
300
305
  ### `/auth/api/admin`
301
306
 
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).
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.
303
308
 
304
309
  | route | |
305
310
  |---|---|
306
311
  | `GET /users` | users with their roles |
307
- | `GET /roles` | `[{ id, name }]` |
312
+ | `GET /roles` | `[{ id, name, scope, mtId1 }]`: the current company's roles and the generic ones; system roles only for Super Admin |
308
313
  | `GET /access-items` | `{ apis, pages, elements, menus }`, each with its roles |
309
314
  | `POST /user-role` | `{ userId, roleId, assign }` — grant or remove a role |
310
315
  | `POST /access-role` | `{ type: apis\|pages\|elements\|menus, itemId, roleId, assign }` |
@@ -312,6 +317,8 @@ Client code must read the header and replace its stored token, or the session en
312
317
  | `GET /master/<type>` | `<type>` is `roles`, `apis`, `pages`, `elements` or `menus` |
313
318
  | `POST /master/<type>` | `{ id?, name, … }` — update with `id`, create without |
314
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 |
315
322
  | `GET /menu-items` | Super Admin — [menu keys and labels](#menu-keys-and-labels) |
316
323
  | `POST /menu-items` | Super Admin — `{ items: [{ name, label, sortOrder, isHidden }] }` |
317
324
  | `POST /menu-items/add` | Super Admin — `{ name, label, isPublic? }` |
@@ -378,6 +385,64 @@ POST /auth/api/admin/menu-items/remove { "name": "form:crop" }
378
385
 
379
386
  Bad input answers `400` with the reason.
380
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
+
381
446
  ## Access checks
382
447
 
383
448
  **`accessMiddleware(options)`** guards your own API routes from the `apis` catalog:
@@ -391,18 +456,85 @@ app.use('/api', auth.accessMiddleware()) // API name = req.baseUrl + req.p
391
456
  | not in `apis` | open |
392
457
  | `isPublic` | open |
393
458
  | 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 |
459
+ | mapped to roles | Bearer token required (signature and expiry — not the Redis session), then the user's [access state](#access-states) |
395
460
 
396
461
  Pass `apiNameResolver(req)` to name APIs differently. Because unregistered means open, register every route that must be guarded.
397
462
 
398
463
  **`requireRole('Admin', 'Super Admin')`** checks the role names in the token, with no database lookup.
399
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
+
400
514
  ## Multi-tenancy
401
515
 
402
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.
403
517
 
404
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.
405
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
+
406
538
  ```js
407
539
  app.use(authMiddleware) // needs req.user.id
408
540
  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.
@@ -138,30 +140,79 @@ async function getApiRule(apiName) {
138
140
  }
139
141
 
140
142
  /**
141
- * Check if a user has access to a specific API.
142
- * Uses cached API rules and cached user roles.
143
+ * Access states. A gate answers one of these, not true/false:
144
+ *
145
+ * enabled shown and usable
146
+ * disabled shown, greyed out, not usable: the API refuses it
147
+ * hidden not shown: the API refuses it
148
+ *
149
+ * Today only enabled and hidden can come out (a role mapping is there or it
150
+ * is not). disabled is part of the answer so callers handle it now; the
151
+ * stored states that produce it come next.
143
152
  */
144
- async function userHasApiAccess(userId, apiName) {
145
- const rule = await getApiRule(apiName);
153
+ var ACCESS_STATES = ['enabled', 'disabled', 'hidden'];
146
154
 
155
+ /**
156
+ * The state for an API rule and a user's role ids. Pure, so it can be tested
157
+ * without a database.
158
+ */
159
+ function apiStateFor(rule, userRoleIds) {
147
160
  // Not registered in DB, or marked public, or no role mappings = open
148
- if (!rule.exists || rule.isPublic || rule.unmapped) return true;
161
+ if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
162
+ var userRoleSet = new Set(userRoleIds || []);
163
+ return rule.roleIds.some(function(id) { return userRoleSet.has(id); }) ? 'enabled' : 'hidden';
164
+ }
149
165
 
150
- // Get user's role IDs (from user access cache)
151
- const userRoleCacheKey = `access:userRoles:${userId}`;
152
- let userRoleIds = await cache.get(userRoleCacheKey);
166
+ /** The user's role ids, cached for the gate. */
167
+ async function userRoleIdsOf(userId) {
168
+ var userRoleCacheKey = `access:userRoles:${userId}`;
169
+ var userRoleIds = await cache.get(userRoleCacheKey);
170
+ if (userRoleIds) return userRoleIds;
153
171
 
154
- if (!userRoleIds) {
155
- const user = await User.query()
156
- .findById(userId)
157
- .withGraphFetched('roles');
172
+ var user = await User.query()
173
+ .findById(userId)
174
+ .withGraphFetched('roles');
158
175
 
159
- userRoleIds = (user && user.roles) ? user.roles.map(r => r.id) : [];
160
- await cache.set(userRoleCacheKey, userRoleIds, USER_ACCESS_TTL);
161
- }
176
+ userRoleIds = (user && user.roles) ? user.roles.map(function(r) { return r.id; }) : [];
177
+ await cache.set(userRoleCacheKey, userRoleIds, USER_ACCESS_TTL);
178
+ return userRoleIds;
179
+ }
162
180
 
163
- const userRoleSet = new Set(userRoleIds);
164
- return rule.roleIds.some(id => userRoleSet.has(id));
181
+ /**
182
+ * A user's state for a specific API: 'enabled' | 'disabled' | 'hidden'.
183
+ * Uses cached API rules and cached user roles.
184
+ */
185
+ async function userApiState(userId, apiName) {
186
+ var rule = await getApiRule(apiName);
187
+ if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
188
+ return apiStateFor(rule, await userRoleIdsOf(userId));
189
+ }
190
+
191
+ /** Every API name in the catalog, cached like the other access rules. */
192
+ async function catalogApiNames() {
193
+ var cached = await cache.get(catalogKey);
194
+ if (Array.isArray(cached)) return cached;
195
+ var rows = await Api.query().select('name');
196
+ var names = rows.map(function(r) { return r.name; });
197
+ await cache.set(catalogKey, names, API_RULES_TTL);
198
+ return names;
199
+ }
200
+
201
+ /**
202
+ * A user's state for a REQUEST: the catalog row it matches (method, path,
203
+ * :params), then that row's state. Not registered → enabled (open).
204
+ *
205
+ * @returns { api, state } api is the matched name, or null
206
+ */
207
+ async function requestApiState(userId, method, path) {
208
+ var api = matchApi(await catalogApiNames(), method, path);
209
+ if (!api) return { api: null, state: 'enabled' };
210
+ return { api: api, state: await userApiState(userId, api) };
211
+ }
212
+
213
+ /** True only when the state is enabled. Kept for callers that want a yes/no. */
214
+ async function userHasApiAccess(userId, apiName) {
215
+ return (await userApiState(userId, apiName)) === 'enabled';
165
216
  }
166
217
 
167
218
  /**
@@ -195,8 +246,12 @@ async function clearAllAccess() {
195
246
  }
196
247
 
197
248
  module.exports = {
249
+ ACCESS_STATES,
250
+ apiStateFor,
198
251
  clearAllAccess,
199
252
  getUserAccess,
253
+ requestApiState,
254
+ userApiState,
200
255
  userHasApiAccess,
201
256
  clearUserAccess,
202
257
  clearAccessRules,
@@ -1,9 +1,12 @@
1
1
  var express = require('express');
2
2
  var { generateId } = require('./authHelper');
3
3
  var { clearUserAccess, clearAccessRules, clearAllAccess } = require('./accessService');
4
+ var { accessGate } = require('./accessMiddleware');
4
5
  var { createMenuService } = require('./menuService');
5
6
  var authMiddleware = require('./authMiddleware');
6
7
  var hooks = require('./hooks');
8
+ var { isSuperAdmin, systemScopeGuard, SUPER_ADMIN_ROLE } = require('./systemScope');
9
+ var { tenantOf, visibleTenants, GENERIC } = require('./tenant');
7
10
  var User = require('../models/User');
8
11
  var Role = require('../models/Role');
9
12
  var Api = require('../models/Api');
@@ -37,6 +40,62 @@ function createAdminRouter() {
37
40
  // Every admin route requires a valid JWT — populates req.user (with roles).
38
41
  router.use(authMiddleware);
39
42
 
43
+ // SUPER ADMIN ONLY, checked here on the server. Hiding a screen does not
44
+ // stop anyone calling its route, so every route that changes roles carries
45
+ // this guard. (The menu routes below use it too.)
46
+ function requireSuperAdmin(action) {
47
+ return function(req, res, next) {
48
+ if (!isSuperAdmin(req.user)) {
49
+ return res.status(403).json({ error: 'Only Super Admin can ' + action });
50
+ }
51
+ next();
52
+ };
53
+ }
54
+
55
+ // SYSTEM APIs (apis.scope = 'system') are Super Admin only, read from the
56
+ // catalog — so a route becomes a system action by adding its row, with no
57
+ // change here. The explicit requireSuperAdmin on the role routes below
58
+ // stays as a second line: those must hold even before migrations run.
59
+ router.use(systemScopeGuard());
60
+
61
+ // And every admin route is checked against the catalog like any other app's
62
+ // routes: a Viewer cannot call user-role or access-role just by being signed
63
+ // in. Which roles reach which admin route is data (role mappings), set by
64
+ // migrations and changed from the Access Matrix.
65
+ router.use(accessGate());
66
+
67
+ // A system role is seen, edited and assigned by Super Admin only.
68
+ async function refuseSystemRole(req, res, roleId) {
69
+ if (isSuperAdmin(req.user)) return false;
70
+ var role = await Role.query().select('scope').findById(roleId);
71
+ if (role && role.scope === 'system') {
72
+ res.status(403).json({ error: 'This is a system role: only Super Admin can assign or change it', code: 'SYSTEM_SCOPE' });
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+
78
+ // Roles visible to this request: the current company's and the generic
79
+ // ('*') ones — and system roles only to Super Admin.
80
+ function visibleRoles(req) {
81
+ var q = Role.query().select('id', 'name', 'scope', 'mtId1');
82
+ if (!isSuperAdmin(req.user)) q = q.where('scope', '<>', 'system');
83
+ var tenants = visibleTenants(tenantOf(req));
84
+ if (tenants) q = q.whereIn('mtId1', tenants);
85
+ return q;
86
+ }
87
+
88
+ async function findVisibleRole(req, id) {
89
+ return visibleRoles(req).findById(id);
90
+ }
91
+
92
+ // A role name is unique within the company it belongs to.
93
+ async function nameTaken(mtId1, name, exceptId) {
94
+ var q = Role.query().select('id').where('mtId1', mtId1).whereRaw('lower(name) = lower(?)', [name]);
95
+ if (exceptId) q = q.where('id', '<>', exceptId);
96
+ return !!(await q.first());
97
+ }
98
+
40
99
  // ─── Users with their roles ───
41
100
  router.get('/users', async function(req, res) {
42
101
  try {
@@ -52,7 +111,7 @@ function createAdminRouter() {
52
111
  // ─── Roles ───
53
112
  router.get('/roles', async function(req, res) {
54
113
  try {
55
- var roles = await Role.query().select('id', 'name');
114
+ var roles = await visibleRoles(req);
56
115
  res.json(roles);
57
116
  } catch (err) {
58
117
  res.status(500).json({ error: 'Something went wrong' });
@@ -63,7 +122,8 @@ function createAdminRouter() {
63
122
  router.get('/access-items', async function(req, res) {
64
123
  try {
65
124
  var [apis, pages, elements, menus] = await Promise.all([
66
- Api.query().select('id', 'name', 'apiGroup', 'isPublic').withGraphFetched('roles'),
125
+ // System APIs are not granted to roles, so they are not offered here.
126
+ Api.query().select('id', 'name', 'apiGroup', 'isPublic').where('scope', '<>', 'system').withGraphFetched('roles'),
67
127
  UiPage.query().select('id', 'name', 'uiPagesGroup', 'isPublic').withGraphFetched('roles'),
68
128
  UiElement.query().select('id', 'name', 'uiElementsGroup').withGraphFetched('roles'),
69
129
  Menu.query().select('id', 'name', 'menuGroup', 'isPublic').withGraphFetched('roles')
@@ -82,6 +142,7 @@ function createAdminRouter() {
82
142
  if (!userId || !roleId) {
83
143
  return res.status(400).json({ error: 'userId and roleId are required' });
84
144
  }
145
+ if (await refuseSystemRole(req, res, roleId)) return;
85
146
 
86
147
  if (assign) {
87
148
  var existing = await UserRolesMapping.query()
@@ -128,6 +189,13 @@ function createAdminRouter() {
128
189
  if (!mapping) {
129
190
  return res.status(400).json({ error: 'Invalid type. Use: apis, pages, elements, menus' });
130
191
  }
192
+ if (await refuseSystemRole(req, res, roleId)) return;
193
+ if (type === 'apis') {
194
+ var api = await Api.query().select('scope').findById(itemId);
195
+ if (api && api.scope === 'system') {
196
+ return res.status(400).json({ error: 'A system API is not granted to roles: only Super Admin can use it', code: 'SYSTEM_SCOPE' });
197
+ }
198
+ }
131
199
 
132
200
  var where = { roleId: roleId };
133
201
  where[mapping.fk] = itemId;
@@ -163,6 +231,7 @@ function createAdminRouter() {
163
231
  if (!moduleName || !action || !roleId) {
164
232
  return res.status(400).json({ error: 'module, action, and roleId are required' });
165
233
  }
234
+ if (await refuseSystemRole(req, res, roleId)) return;
166
235
 
167
236
  var groupValue = moduleName + ':' + action;
168
237
  var createdBy = req.user ? req.user.id : null;
@@ -177,7 +246,10 @@ function createAdminRouter() {
177
246
  var promises = types.map(async function(cfg) {
178
247
  var where = {};
179
248
  where[cfg.groupField] = groupValue;
180
- var items = await cfg.Model.query().select('id').where(where);
249
+ var q = cfg.Model.query().select('id').where(where);
250
+ // A system API in the same group is still never granted.
251
+ if (cfg.type === 'apis') q = q.where('scope', '<>', 'system');
252
+ var items = await q;
181
253
 
182
254
  for (var i = 0; i < items.length; i++) {
183
255
  var itemWhere = { roleId: roleId };
@@ -209,25 +281,50 @@ function createAdminRouter() {
209
281
  // ─── Master CRUD: Roles ───
210
282
  router.get('/master/roles', async function(req, res) {
211
283
  try {
212
- var items = await Role.query().select('id', 'name');
284
+ var items = await visibleRoles(req);
213
285
  res.json(items);
214
286
  } catch (err) {
215
287
  res.status(500).json({ error: 'Something went wrong' });
216
288
  }
217
289
  });
218
290
 
219
- router.post('/master/roles', async function(req, res) {
291
+ router.post('/master/roles', requireSuperAdmin('create or rename roles'), async function(req, res) {
220
292
  try {
221
- var { id, name } = req.body;
293
+ var { id, name, scope } = req.body;
222
294
  if (!name) return res.status(400).json({ error: 'name is required' });
295
+ if (scope != null && scope !== 'system' && scope !== 'company') {
296
+ return res.status(400).json({ error: "scope must be 'system' or 'company'" });
297
+ }
223
298
 
224
299
  if (id) {
225
- await Role.query().findById(id).patch({ name: name });
300
+ var current = await findVisibleRole(req, id);
301
+ if (!current) return res.status(404).json({ error: 'Role not found in this company' });
302
+ if (await nameTaken(current.mtId1, name, id)) {
303
+ return res.status(409).json({ error: 'A role called "' + name + '" already exists here' });
304
+ }
305
+ var patch = { name: name };
306
+ if (scope) patch.scope = scope;
307
+ await Role.query().findById(id).patch(patch);
226
308
  await hooks.fire('roles', 'update', id);
227
309
  res.json({ id: id });
228
310
  } else {
311
+ // A system role belongs to the whole install. Any other role belongs
312
+ // to the company it is created in — even when Super Admin creates it —
313
+ // so creating one with no company selected is refused.
314
+ var rowScope = scope || 'company';
315
+ var t = tenantOf(req);
316
+ var mtId1 = GENERIC;
317
+ if (rowScope !== 'system' && t.multiTenant) {
318
+ if (!t.companyId) {
319
+ return res.status(400).json({ error: 'Choose a company first: a role belongs to the company it is created in', code: 'NO_COMPANY' });
320
+ }
321
+ mtId1 = t.companyId;
322
+ }
323
+ if (await nameTaken(mtId1, name)) {
324
+ return res.status(409).json({ error: 'A role called "' + name + '" already exists here' });
325
+ }
229
326
  var newId = generateId();
230
- await Role.query().insert({ id: newId, name: name });
327
+ await Role.query().insert({ id: newId, name: name, scope: rowScope, mtId1: mtId1 });
231
328
  await hooks.fire('roles', 'create', newId);
232
329
  res.json({ id: newId });
233
330
  }
@@ -236,10 +333,87 @@ function createAdminRouter() {
236
333
  }
237
334
  });
238
335
 
239
- router.post('/master/roles/delete', async function(req, res) {
336
+ // ─── Copy roles to other companies (Super Admin) ───
337
+ //
338
+ // Five companies wanting the same roles get five independent copies: same
339
+ // name, same grants (apis, pages, elements, menus), each then theirs to
340
+ // change. A company that already has a role of that name keeps its own —
341
+ // the copy is skipped and reported, never overwritten.
342
+ var MAPPINGS = [
343
+ { Model: ApisRolesMapping, fk: 'apiId' },
344
+ { Model: UiPagesRolesMapping, fk: 'uiPageId' },
345
+ { Model: UiElementsRolesMapping, fk: 'uiElementId' },
346
+ { Model: MenuRolesMapping, fk: 'menuId' }
347
+ ];
348
+
349
+ router.post('/master/roles/copy', requireSuperAdmin('copy roles between companies'), async function(req, res) {
350
+ try {
351
+ var roleIds = Array.isArray(req.body.roleIds) ? req.body.roleIds : [];
352
+ var companyIds = Array.isArray(req.body.companyIds) ? req.body.companyIds : [];
353
+ if (!roleIds.length || !companyIds.length) {
354
+ return res.status(400).json({ error: 'roleIds and companyIds are required' });
355
+ }
356
+ var sources = await Role.query().select('id', 'name', 'scope').whereIn('id', roleIds);
357
+ var copied = [], skipped = [];
358
+ roleIds.forEach(function(rid) {
359
+ if (!sources.some(function(r) { return r.id === rid; })) skipped.push({ roleId: rid, reason: 'not found' });
360
+ });
361
+ var by = req.user ? req.user.id : null;
362
+
363
+ for (var i = 0; i < sources.length; i++) {
364
+ var src = sources[i];
365
+ if (src.scope === 'system') {
366
+ skipped.push({ roleId: src.id, reason: 'a system role belongs to the whole install and is not copied' });
367
+ continue;
368
+ }
369
+ var grants = [];
370
+ for (var m = 0; m < MAPPINGS.length; m++) {
371
+ var rows = await MAPPINGS[m].Model.query().select(MAPPINGS[m].fk).where('roleId', src.id);
372
+ grants.push(rows.map(function(r) { return r[MAPPINGS[m].fk]; }));
373
+ }
374
+ for (var c = 0; c < companyIds.length; c++) {
375
+ var companyId = String(companyIds[c] || '').trim();
376
+ if (!companyId || companyId === GENERIC) {
377
+ skipped.push({ roleId: src.id, companyId: companyId, reason: 'not a company id' });
378
+ continue;
379
+ }
380
+ if (await nameTaken(companyId, src.name)) {
381
+ skipped.push({ roleId: src.id, companyId: companyId, reason: 'a role called "' + src.name + '" already exists there' });
382
+ continue;
383
+ }
384
+ var copyId = generateId();
385
+ await Role.transaction(async function(trx) {
386
+ await Role.query(trx).insert({ id: copyId, name: src.name, scope: 'company', mtId1: companyId, recordCreatedBy: by });
387
+ for (var k = 0; k < MAPPINGS.length; k++) {
388
+ for (var g = 0; g < grants[k].length; g++) {
389
+ var row = { id: generateId(), roleId: copyId, isActive: true, recordCreatedBy: by };
390
+ row[MAPPINGS[k].fk] = grants[k][g];
391
+ await MAPPINGS[k].Model.query(trx).insert(row);
392
+ }
393
+ }
394
+ });
395
+ await hooks.fire('roles', 'create', copyId);
396
+ copied.push({ roleId: src.id, companyId: companyId, newRoleId: copyId });
397
+ }
398
+ }
399
+ if (copied.length) await clearAccessRules();
400
+ res.json({ copied: copied, skipped: skipped });
401
+ } catch (err) {
402
+ res.status(500).json({ error: 'Something went wrong' });
403
+ }
404
+ });
405
+
406
+ router.post('/master/roles/delete', requireSuperAdmin('delete roles'), async function(req, res) {
240
407
  try {
241
408
  var { id } = req.body;
242
409
  if (!id) return res.status(400).json({ error: 'id is required' });
410
+ // Deleting the role that holds system scope would leave nobody able to
411
+ // manage the install. Refused, whoever asks.
412
+ var target = await findVisibleRole(req, id);
413
+ if (!target) return res.status(404).json({ error: 'Role not found in this company' });
414
+ if (target.name === SUPER_ADMIN_ROLE) {
415
+ return res.status(400).json({ error: 'The Super Admin role cannot be deleted' });
416
+ }
243
417
  await Role.query().deleteById(id);
244
418
  await clearAccessRules();
245
419
  await hooks.fire('roles', 'delete', id);
@@ -255,11 +429,7 @@ function createAdminRouter() {
255
429
  // sortOrder and isHidden are what the app's "Configure UI" screen edits.
256
430
  var menuItems = createMenuService({ Menu: Menu, MenuRolesMapping: MenuRolesMapping, clearAll: clearAllAccess });
257
431
 
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
- }
432
+ var superAdminOnly = requireSuperAdmin('change the menu');
263
433
 
264
434
  function menuRoute(fn) {
265
435
  return [superAdminOnly, async function(req, res) {
@@ -284,12 +454,53 @@ function createAdminRouter() {
284
454
  menus: { Model: Menu, fields: ['name', 'menuGroup', 'isPublic'] }
285
455
  };
286
456
 
457
+ // A system API row is managed by migrations only. Renaming or deleting it
458
+ // here would leave the route it names unguarded, so both are refused.
459
+ async function refuseSystemApiRow(typeKey, id, res) {
460
+ if (typeKey !== 'apis' || !id) return false;
461
+ var row = await Api.query().select('scope').findById(id);
462
+ if (row && row.scope === 'system') {
463
+ res.status(400).json({ error: 'A system API is managed by migrations and cannot be changed here', code: 'SYSTEM_SCOPE' });
464
+ return true;
465
+ }
466
+ return false;
467
+ }
468
+
469
+ // ─── "Super Admin only": move an API in or out of system scope ───
470
+ //
471
+ // Super Admin's switch in Master Settings, so an API can become system
472
+ // without code or SQL. Effective at once: the guard's cached list is
473
+ // cleared. A locked row (pinned by a migration) cannot be switched off.
474
+ // Role mappings are kept, so switching an API back restores who had it.
475
+ router.post('/master/apis/scope', requireSuperAdmin('change which APIs are Super Admin only'), async function(req, res) {
476
+ try {
477
+ var { id, scope } = req.body;
478
+ if (!id) return res.status(400).json({ error: 'id is required' });
479
+ if (scope !== 'system' && scope !== 'company') {
480
+ return res.status(400).json({ error: "scope must be 'system' or 'company'" });
481
+ }
482
+ var row = await Api.query().select('id', 'scope', 'scopeLocked').findById(id);
483
+ if (!row) return res.status(404).json({ error: 'API not found' });
484
+ if (row.scopeLocked) {
485
+ return res.status(400).json({ error: 'This API is pinned as Super Admin only by a migration and cannot be changed here', code: 'SCOPE_LOCKED' });
486
+ }
487
+ if (row.scope !== scope) {
488
+ await Api.query().findById(id).patch({ scope: scope });
489
+ await clearAccessRules();
490
+ await hooks.fire('apis', 'update', id);
491
+ }
492
+ res.json({ id: id, scope: scope });
493
+ } catch (err) {
494
+ res.status(500).json({ error: 'Something went wrong' });
495
+ }
496
+ });
497
+
287
498
  Object.keys(masterTypes).forEach(function(typeKey) {
288
499
  var cfg = masterTypes[typeKey];
289
500
 
290
501
  router.get('/master/' + typeKey, async function(req, res) {
291
502
  try {
292
- var selectFields = ['id'].concat(cfg.fields);
503
+ var selectFields = ['id'].concat(cfg.fields, typeKey === 'apis' ? ['scope', 'scopeLocked'] : []);
293
504
  var items = await cfg.Model.query().select(selectFields);
294
505
  res.json(items);
295
506
  } catch (err) {
@@ -306,6 +517,7 @@ function createAdminRouter() {
306
517
  });
307
518
 
308
519
  if (!data.name) return res.status(400).json({ error: 'name is required' });
520
+ if (await refuseSystemApiRow(typeKey, id, res)) return;
309
521
 
310
522
  if (id) {
311
523
  await cfg.Model.query().findById(id).patch(data);
@@ -327,6 +539,7 @@ function createAdminRouter() {
327
539
  try {
328
540
  var id = req.body.id;
329
541
  if (!id) return res.status(400).json({ error: 'id is required' });
542
+ if (await refuseSystemApiRow(typeKey, id, res)) return;
330
543
  await cfg.Model.query().deleteById(id);
331
544
  await clearAccessRules();
332
545
  await hooks.fire(typeKey, 'delete', id);
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Which `apis` row a request is. Pure, so it can be tested without a request.
3
+ *
4
+ * A row's name is "METHOD path" (that method only) or a bare path (every
5
+ * method), and a path may hold `:params` — "GET /widget-templates/:id"
6
+ * covers GET /widget-templates/abc. When several rows fit, the most exact
7
+ * wins:
8
+ *
9
+ * 1. more literal segments /dashboards/:id/group beats /dashboards/:id/:x
10
+ * 2. a method over none "POST /x" beats "/x"
11
+ *
12
+ * @param names every API name in the catalog
13
+ * @param method 'GET', 'POST', …
14
+ * @param path the request path, no query string
15
+ * @returns the matching name, or null (not registered)
16
+ */
17
+ function clean(path) {
18
+ return String(path || '').split('?')[0].replace(/\/+$/, '') || '/';
19
+ }
20
+
21
+ function parse(name) {
22
+ var m = /^([A-Z]+)\s+(\S+)$/.exec(String(name || '').trim());
23
+ return m ? { method: m[1], path: clean(m[2]) } : { method: null, path: clean(name) };
24
+ }
25
+
26
+ /** Literal segments matched, or -1 when the pattern does not fit. */
27
+ function fit(pattern, path) {
28
+ var a = pattern.split('/');
29
+ var b = path.split('/');
30
+ if (a.length !== b.length) return -1;
31
+ var literal = 0;
32
+ for (var i = 0; i < a.length; i++) {
33
+ if (a[i].charAt(0) === ':' && b[i] !== '') continue;
34
+ if (a[i] !== b[i]) return -1;
35
+ literal++;
36
+ }
37
+ return literal;
38
+ }
39
+
40
+ function matchApi(names, method, path) {
41
+ var verb = String(method || '').toUpperCase();
42
+ var target = clean(path);
43
+ var best = null;
44
+ var bestScore = -1;
45
+ (names || []).forEach(function(name) {
46
+ var row = parse(name);
47
+ if (row.method && row.method !== verb) return;
48
+ var literal = fit(row.path, target);
49
+ if (literal < 0) return;
50
+ var score = literal * 2 + (row.method ? 1 : 0);
51
+ if (score > bestScore) { best = name; bestScore = score; }
52
+ });
53
+ return best;
54
+ }
55
+
56
+ module.exports = { matchApi: matchApi };
package/lib/authRouter.js CHANGED
@@ -1,10 +1,16 @@
1
1
  const express = require('express');
2
2
  const FileUploader = require('@xeplr/utils/lib/fileUploader');
3
3
  const { register, activate, previewInvite, acceptInvite, login, forgotPassword, resetPassword, requestPhoneOtp, verifyPhoneOtp, getProfile, updateProfile, setProfilePic, changePassword } = require('./authService');
4
- const { getUserAccess } = require('./accessService');
4
+ const { getUserAccess, requestApiState } = require('./accessService');
5
5
  const { getSession, rotateSession, destroySession } = require('./sessionService');
6
6
  const { issueTicket } = require('./ticketService');
7
7
  const authMiddleware = require('./authMiddleware');
8
+ const { accessGate } = require('./accessMiddleware');
9
+
10
+ // Signed in AND allowed this route by the catalog: the same two checks every
11
+ // other app's gate asks /verify for. Login, register, refresh and the rest of
12
+ // the signed-out routes carry neither.
13
+ const signedInAndAllowed = [authMiddleware, accessGate()];
8
14
  const User = require('../models/User');
9
15
 
10
16
  // Avatar uploads — local disk by default (FileUploader's own default:
@@ -205,7 +211,7 @@ function createAuthRouter(options = {}) {
205
211
  }
206
212
  });
207
213
 
208
- router.get('/me', authMiddleware, async function(req, res) {
214
+ router.get('/me', signedInAndAllowed, async function(req, res) {
209
215
  try {
210
216
  const access = await getUserAccess(req.user.id);
211
217
  res.json({
@@ -218,7 +224,34 @@ function createAuthRouter(options = {}) {
218
224
  }
219
225
  });
220
226
 
221
- router.get('/profile', authMiddleware, async function(req, res) {
227
+ // The check every app's gate asks, on every request it serves: who is this
228
+ // (the token, with the same tolerance and sliding refresh as any route) AND
229
+ // may they call this API. Both, always; there is no way to ask one without
230
+ // the other. The app names the request it is serving in two headers.
231
+ router.get('/verify', authMiddleware, async function(req, res) {
232
+ var method = req.headers['x-verify-method'];
233
+ var path = req.headers['x-verify-path'];
234
+ if (!method || !path) {
235
+ return res.status(400).json({ error: 'x-verify-method and x-verify-path are required', code: 'NO_REQUEST' });
236
+ }
237
+ try {
238
+ var answer = await requestApiState(req.user.id, method, path);
239
+ if (answer.state === 'enabled') {
240
+ var access = await getUserAccess(req.user.id);
241
+ return res.json({ user: req.user, access: access, state: 'enabled', api: answer.api });
242
+ }
243
+ if (answer.state === 'disabled') {
244
+ return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED', api: answer.api });
245
+ }
246
+ // hidden, or anything the gate does not know: refused.
247
+ return res.status(403).json({ error: 'Access denied', code: 'HIDDEN', api: answer.api });
248
+ } catch (err) {
249
+ logError(req, err);
250
+ res.status(500).json({ error: 'Something went wrong' });
251
+ }
252
+ });
253
+
254
+ router.get('/profile', signedInAndAllowed, async function(req, res) {
222
255
  try {
223
256
  const profile = await getProfile(req.user.id);
224
257
  res.json(profile);
@@ -228,7 +261,7 @@ function createAuthRouter(options = {}) {
228
261
  }
229
262
  });
230
263
 
231
- router.put('/profile', authMiddleware, async function(req, res) {
264
+ router.put('/profile', signedInAndAllowed, async function(req, res) {
232
265
  try {
233
266
  const profile = await updateProfile(req.user.id, req.body);
234
267
  res.json(profile);
@@ -238,7 +271,7 @@ function createAuthRouter(options = {}) {
238
271
  }
239
272
  });
240
273
 
241
- router.post('/profile/avatar', authMiddleware, ...avatarUploader.single('avatar'), async function(req, res) {
274
+ router.post('/profile/avatar', signedInAndAllowed, ...avatarUploader.single('avatar'), async function(req, res) {
242
275
  try {
243
276
  if (!req.file) return res.status(400).json({ error: 'avatar file is required' });
244
277
  // Store just the generated filename — never the server's filesystem
@@ -253,7 +286,7 @@ function createAuthRouter(options = {}) {
253
286
  }
254
287
  });
255
288
 
256
- router.post('/change-password', authMiddleware, async function(req, res) {
289
+ router.post('/change-password', signedInAndAllowed, async function(req, res) {
257
290
  try {
258
291
  const { oldPassword, newPassword } = req.body;
259
292
  if (!oldPassword || !newPassword) {
@@ -270,7 +303,7 @@ function createAuthRouter(options = {}) {
270
303
  // Additive phone verification — like email activation, but for a phone
271
304
  // number attached to an already-authenticated account. Body: { phoneNumber }
272
305
  // optional (omit to re-send to the number already on file).
273
- router.post('/request-phone-otp', authMiddleware, async function(req, res) {
306
+ router.post('/request-phone-otp', signedInAndAllowed, async function(req, res) {
274
307
  try {
275
308
  const result = await requestPhoneOtp(req.user.id, req.body.phoneNumber);
276
309
  res.json(result);
@@ -280,7 +313,7 @@ function createAuthRouter(options = {}) {
280
313
  }
281
314
  });
282
315
 
283
- router.post('/verify-phone-otp', authMiddleware, async function(req, res) {
316
+ router.post('/verify-phone-otp', signedInAndAllowed, async function(req, res) {
284
317
  try {
285
318
  if (!req.body.code) return res.status(400).json({ error: 'code is required' });
286
319
  const result = await verifyPhoneOtp(req.user.id, req.body.code);
@@ -304,7 +337,7 @@ function createAuthRouter(options = {}) {
304
337
  //
305
338
  // NOTE the scopes are advisory intent — the SSE handler owns the final
306
339
  // authorization check (see xeplr-base-apis/lib/sse.js#createHandler).
307
- router.post('/sse-ticket', authMiddleware, async function(req, res) {
340
+ router.post('/sse-ticket', signedInAndAllowed, async function(req, res) {
308
341
  try {
309
342
  var requested = (req.body && Array.isArray(req.body.scopes)) ? req.body.scopes : ['user:me:*'];
310
343
  var { ticket, expiresIn } = await issueTicket({
@@ -0,0 +1,79 @@
1
+ /**
2
+ * System scope — what only Super Admin may reach, see or hand out.
3
+ *
4
+ * An `apis` row with `scope = 'system'` is a system API: this guard refuses it
5
+ * to anyone who is not Super Admin, whatever the role mappings say. A product
6
+ * registers its own system APIs from its migrations (insert the row with
7
+ * scope 'system') and mounts systemScopeGuard() in front of its routes; no
8
+ * code change here. See migrations/0010_system_scope.sql.
9
+ *
10
+ * A row's name is either a path, which covers every method, or
11
+ * "METHOD path", which covers that method only — so GET can stay open on a
12
+ * path whose POST is a system action.
13
+ */
14
+ var { cache } = require('@xeplr/utils');
15
+ var Api = require('../models/Api');
16
+
17
+ var SUPER_ADMIN_ROLE = 'Super Admin';
18
+ var CACHE_KEY = 'access:api:system'; // under access:api:*, so clearAccessRules() clears it
19
+ var CACHE_TTL = 600;
20
+
21
+ /** Does this signed-in user hold Super Admin? (req.user.roles are names, from the token.) */
22
+ function isSuperAdmin(user) {
23
+ var roles = (user && user.roles) || [];
24
+ return roles.indexOf(SUPER_ADMIN_ROLE) !== -1;
25
+ }
26
+
27
+ /** The names of every system API, cached like the other access rules. */
28
+ async function systemApiNames() {
29
+ var cached = await cache.get(CACHE_KEY);
30
+ if (Array.isArray(cached)) return cached;
31
+ var rows = await Api.query().select('name').where('scope', 'system');
32
+ var names = rows.map(function(r) { return r.name; });
33
+ await cache.set(CACHE_KEY, names, CACHE_TTL);
34
+ return names;
35
+ }
36
+
37
+ /**
38
+ * Is this request a system API? Pure, so it can be tested without a request.
39
+ *
40
+ * @param names system API names ("path" or "METHOD path")
41
+ * @param method 'GET', 'POST', …
42
+ * @param path the full path, e.g. req.baseUrl + req.path
43
+ */
44
+ function isSystemRequest(names, method, path) {
45
+ var clean = String(path || '').replace(/\/+$/, '') || '/';
46
+ var withMethod = String(method || '').toUpperCase() + ' ' + clean;
47
+ return names.some(function(n) {
48
+ var name = String(n || '').replace(/\/+$/, '');
49
+ return name === clean || name === withMethod;
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Express middleware: refuse system APIs to anyone but Super Admin.
55
+ * Mount after the auth check, so req.user is set.
56
+ *
57
+ * Fails CLOSED: if the catalog cannot be read, a request is refused rather
58
+ * than let through, because "cannot tell if this is a system action" must
59
+ * never mean "allowed".
60
+ */
61
+ function systemScopeGuard() {
62
+ return async function(req, res, next) {
63
+ var path = (req.baseUrl || '') + (req.path || '');
64
+ var names;
65
+ try { names = await systemApiNames(); }
66
+ catch (err) { return res.status(503).json({ error: 'Access rules are unavailable; try again shortly' }); }
67
+ if (!isSystemRequest(names, req.method, path)) return next();
68
+ if (isSuperAdmin(req.user)) return next();
69
+ return res.status(403).json({ error: 'This is a system action: only Super Admin can do it', code: 'SYSTEM_SCOPE' });
70
+ };
71
+ }
72
+
73
+ module.exports = {
74
+ SUPER_ADMIN_ROLE: SUPER_ADMIN_ROLE,
75
+ isSuperAdmin: isSuperAdmin,
76
+ isSystemRequest: isSystemRequest,
77
+ systemApiNames: systemApiNames,
78
+ systemScopeGuard: systemScopeGuard
79
+ };
package/lib/tenant.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Which company a request is working in — for the rows auth itself owns
3
+ * (roles today).
4
+ *
5
+ * The auth service runs on its own and does not know an app's tenant levels,
6
+ * so the app tells it with AUTH_TENANT_HEADER: the header that carries the
7
+ * company id (BI: x-company-id), or 'none' for a single-tenant app.
8
+ *
9
+ * '*' a generic row: every company sees it (system roles, APIs, the
10
+ * seeded roles)
11
+ * companyId a company's own row: only that company sees it
12
+ */
13
+
14
+ var GENERIC = '*';
15
+
16
+ /** 'none' → null (single-tenant); otherwise the header name, lower-cased as Node stores headers. */
17
+ function tenantHeader(env) {
18
+ var v = String((env || process.env).AUTH_TENANT_HEADER || '').trim();
19
+ if (!v) throw new Error('AUTH_TENANT_HEADER is not set — the header naming the company (e.g. x-company-id), or none for a single-tenant app');
20
+ return v.toLowerCase() === 'none' ? null : v.toLowerCase();
21
+ }
22
+
23
+ /**
24
+ * The request's company.
25
+ * @returns { multiTenant: boolean, companyId: string|null }
26
+ */
27
+ function tenantOf(req, env) {
28
+ var header = tenantHeader(env);
29
+ if (!header) return { multiTenant: false, companyId: null };
30
+ var raw = req && req.headers ? req.headers[header] : null;
31
+ var id = raw ? String(raw).trim() : '';
32
+ return { multiTenant: true, companyId: id || null };
33
+ }
34
+
35
+ /** Which mtId1 values a request may see: its company and the generic rows. */
36
+ function visibleTenants(t) {
37
+ if (!t.multiTenant) return null; // single-tenant: no filter
38
+ return t.companyId ? [t.companyId, GENERIC] : [GENERIC];
39
+ }
40
+
41
+ module.exports = { GENERIC: GENERIC, tenantHeader: tenantHeader, tenantOf: tenantOf, visibleTenants: visibleTenants };
@@ -0,0 +1,78 @@
1
+ -- 0010_system_scope.sql
2
+ -- SYSTEM SCOPE: what only Super Admin may see, reach or hand out.
3
+ --
4
+ -- Some things are not a company's business at all: creating and deleting
5
+ -- roles, assigning licences, anything that acts on the whole install. They are
6
+ -- `scope = 'system'`, and three rules follow from that, enforced in code
7
+ -- (lib/systemScope.js and lib/adminRouter.js):
8
+ --
9
+ -- a system API is refused to anyone who is not Super Admin, whatever the
10
+ -- role mappings say — it is never granted, so it never
11
+ -- appears in the Access Matrix and the grant routes refuse it
12
+ -- a system role is seen, edited and assigned by Super Admin only
13
+ -- everything else is 'company', the default, and works as before
14
+ --
15
+ -- A product registers its own system APIs the same way, from its own
16
+ -- migrations-auth directory: insert the row with "scope" = 'system' (and
17
+ -- "scopeLocked" = true to pin it). No code change in this library. Super
18
+ -- Admin can also move an API in or out of system scope from Master Settings,
19
+ -- except a locked one.
20
+ --
21
+ -- Idempotent: the columns and constraints are added only if absent, and the
22
+ -- rows only if missing.
23
+
24
+ ALTER TABLE "apis" ADD COLUMN IF NOT EXISTS "scope" varchar(20) NOT NULL DEFAULT 'company';
25
+ ALTER TABLE "roles" ADD COLUMN IF NOT EXISTS "scope" varchar(20) NOT NULL DEFAULT 'company';
26
+
27
+ -- A system API a library or app pinned in its migrations. Super Admin can
28
+ -- move other APIs in and out of system scope from Master Settings; a locked
29
+ -- row cannot be switched off there, so nobody can unguard, say, role
30
+ -- deletion by accident.
31
+ ALTER TABLE "apis" ADD COLUMN IF NOT EXISTS "scopeLocked" boolean NOT NULL DEFAULT false;
32
+
33
+ DO $$
34
+ BEGIN
35
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'apis_scope') THEN
36
+ ALTER TABLE "apis" ADD CONSTRAINT "apis_scope" CHECK ("scope" IN ('system', 'company'));
37
+ END IF;
38
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'roles_scope') THEN
39
+ ALTER TABLE "roles" ADD CONSTRAINT "roles_scope" CHECK ("scope" IN ('system', 'company'));
40
+ END IF;
41
+ END $$;
42
+
43
+ CREATE INDEX IF NOT EXISTS "apis_scope_index" ON "apis" ("scope");
44
+
45
+ -- Roles made before roles belonged to a company were saved with no mtId1,
46
+ -- and every company saw them. They stay generic ('*') rather than vanish from
47
+ -- every list the moment AUTH_TENANT_HEADER is set.
48
+ UPDATE "roles" SET "mtId1" = '*' WHERE "mtId1" IS NULL;
49
+
50
+ -- The role this whole scope exists for.
51
+ UPDATE "roles" SET "scope" = 'system' WHERE "name" = 'Super Admin' AND "scope" <> 'system';
52
+
53
+ -- The first system APIs: managing roles. Creating, renaming and deleting a
54
+ -- role changes what everybody in the install can do.
55
+ --
56
+ -- A name is either a path (every method) or "METHOD path" (that method only).
57
+ --
58
+ -- /auth/api/admin/master/roles/delete already seeded by 0006 as a company
59
+ -- API; it becomes system here
60
+ -- POST /auth/api/admin/master/roles create and rename. It carries the
61
+ -- method because GET on the same path
62
+ -- (0006's listing row) stays open: the
63
+ -- admin screens need the list.
64
+ UPDATE "apis" SET "scope" = 'system', "scopeLocked" = true
65
+ WHERE name = '/auth/api/admin/master/roles/delete' AND ("scope" <> 'system' OR NOT "scopeLocked");
66
+
67
+ INSERT INTO "apis" (id, name, "apiGroup", "scope", "scopeLocked", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
68
+ SELECT encode(gen_random_bytes(12), 'hex'), v.name, v.grp, 'system', true, false, true, '*', now(), now()
69
+ FROM (VALUES
70
+ ('POST /auth/api/admin/master/roles', 'roles:edit'),
71
+ -- Copying roles from one company into others: only Super Admin works
72
+ -- across companies.
73
+ ('/auth/api/admin/master/roles/copy', 'roles:edit'),
74
+ -- Moving an API in or out of system scope (Master Settings' "Super Admin
75
+ -- only" switch). Locked, or it could switch itself off.
76
+ ('/auth/api/admin/master/apis/scope', 'apis:edit')
77
+ ) AS v(name, grp)
78
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" a WHERE a.name = v.name);
@@ -0,0 +1,11 @@
1
+ -- 0011_verify_api.sql
2
+ -- GET /auth/api/verify — the check every app's gate makes on every request:
3
+ -- the token AND the caller's access state for the API being served.
4
+ --
5
+ -- Public in the catalog (like /refresh): it carries its own token check, and
6
+ -- a role mapping on it would make the gate's own question depend on the
7
+ -- answer to itself.
8
+
9
+ INSERT INTO "apis" (id, name, "apiGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
10
+ SELECT encode(gen_random_bytes(12), 'hex'), 'GET /auth/api/verify', '', true, true, '*', now(), now()
11
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" WHERE name = 'GET /auth/api/verify' AND "apiGroup" = '');
@@ -0,0 +1,29 @@
1
+ -- 0012_default_role_access.sql
2
+ -- Auth's own routes, mapped to auth's default roles. Every route is now
3
+ -- checked against these mappings (accessGate), not only for a signed-in token.
4
+ --
5
+ -- Three kinds of URL:
6
+ -- system Super Admin only (apis.scope = 'system'); never mapped to a
7
+ -- company role, and systemScopeGuard refuses it to anyone else
8
+ -- admin users:*, access:*, settings:* → Admin
9
+ -- user account:* (my profile, my password) → every role
10
+ --
11
+ -- These are defaults for a fresh install; change them from the Access Matrix.
12
+ -- An app with its own roles maps them in its own migrations-auth/.
13
+
14
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
15
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
16
+ FROM "roles" r CROSS JOIN "apis" a
17
+ WHERE r.name = 'Admin'
18
+ AND a.scope IS DISTINCT FROM 'system'
19
+ AND (a."apiGroup" LIKE 'account:%' OR a."apiGroup" LIKE 'users:%'
20
+ OR a."apiGroup" LIKE 'access:%' OR a."apiGroup" LIKE 'settings:%')
21
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
22
+
23
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
24
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
25
+ FROM "roles" r CROSS JOIN "apis" a
26
+ WHERE r.name IN ('Editor', 'Viewer')
27
+ AND a.scope IS DISTINCT FROM 'system'
28
+ AND a."apiGroup" LIKE 'account:%'
29
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
package/models/Api.js CHANGED
@@ -15,6 +15,8 @@ class Api extends BaseModel {
15
15
  id: { type: 'string', maxLength: 25 },
16
16
  name: { type: ['string', 'null'], maxLength: 255 },
17
17
  apiGroup: { type: ['string', 'null'], maxLength: 255 },
18
+ scope: { type: 'string', enum: ['system', 'company'] },
19
+ scopeLocked: { type: 'boolean' },
18
20
  isPublic: { type: 'integer' },
19
21
  recordCreatedDate: { type: ['string', 'null'] },
20
22
  recordModifiedDate: { type: ['string', 'null'] },
package/models/Role.js CHANGED
@@ -24,6 +24,7 @@ class Role extends BaseModel {
24
24
  properties: {
25
25
  id: { type: 'string', maxLength: 25 },
26
26
  name: { type: ['string', 'null'], maxLength: 255 },
27
+ scope: { type: 'string', enum: ['system', 'company'] },
27
28
  recordCreatedDate: { type: ['string', 'null'] },
28
29
  recordModifiedDate: { type: ['string', 'null'] },
29
30
  recordCreatedBy: { type: ['string', 'null'], maxLength: 25 },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.1.5",
3
+ "version": "1.1.6",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [