@xeplr/auth 1.1.8 → 1.2.0

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
@@ -91,6 +91,7 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName })
91
91
  | `ticketService` | `issueTicket`, `consumeTicket` — single-use 30-second tickets for SSE / WebSocket |
92
92
  | `authHelper` | `configure`, `hashPassword`, `comparePassword`, `generateAccessToken`, `verifyToken`, `decodeVerified`, `generateId`, … |
93
93
  | `hooks` | `on(identifier, event, fn)`, `fire`, `setHooksEnabled` |
94
+ | `licence` | `use({ modulesFor })`: which sold modules a user may use — see [Licensed modules](#licensed-modules) |
94
95
  | `seedSuperAdmin(knex, { email, password, name? })` | insert-if-absent super admin user + role mapping, for apps seeding from JS |
95
96
  | `configureWorkflowResume(fn)` | hand in `@xeplr-workflow/api`'s `resumeByKey`; activation with a `workflowKey` then resumes that workflow (best-effort) |
96
97
  | `requiredEnv` | the env names this package needs, for an app's `env.required.js`; `requiredEnv.activationLinkVar` names the activation-link variable in use |
@@ -465,13 +466,14 @@ Pass `apiNameResolver(req)` to name APIs differently. Because unregistered means
465
466
 
466
467
  ### Access states
467
468
 
468
- The gate answers one of three states, not true/false. Only `enabled` goes through:
469
+ The gate answers one of four states, not true/false. Only `enabled` goes through:
469
470
 
470
471
  | state | means | `accessMiddleware` |
471
472
  |---|---|---|
472
473
  | `enabled` | shown and usable | passes |
473
474
  | `disabled` | shown, greyed out, not usable | `403 { code: 'DISABLED' }` |
474
475
  | `hidden` | not shown | `403 { code: 'HIDDEN' }` |
476
+ | `unlicensed` | not shown: the API's module is not in the user's licence | `403 { code: 'UNLICENSED' }` |
475
477
 
476
478
  Anything else is refused as well: a state the gate does not know never lets a request through.
477
479
 
@@ -513,6 +515,7 @@ x-verify-path: /widget-templates/abc
513
515
  |---|---|
514
516
  | `200 { user, access, state: 'enabled', api }` | token good, API allowed. `api` is the catalog row it matched, or `null` (not registered, so open) |
515
517
  | `403 { code: 'DISABLED' }` · `403 { code: 'HIDDEN' }` | token good, API not allowed |
518
+ | `403 { code: 'UNLICENSED' }` | token good, but the API belongs to a module the user's licence does not include |
516
519
  | `401` | bad or expired token (the same tolerance and `X-New-Token` sliding as every route) |
517
520
  | `400 { code: 'NO_REQUEST' }` | no method or path named: nothing to check, so refused |
518
521
 
@@ -533,6 +536,30 @@ These are migration defaults; the Access Matrix changes them.
533
536
  **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
537
 
535
538
 
539
+ ### Licensed modules
540
+
541
+ Every catalog row (`apis`, `menus`, `uiPages`, `uiElements`) carries a `licenseModule` (`0007_license_module`):
542
+ - **`core`** is the default: sign-in, company selection, and anything that belongs to no product.
543
+ - **Anything else** names the product the row was sold as: `bi`, `warehouse`, `xflow`, and so on.
544
+
545
+ Roles say what a user's job lets them do; the licence says what was paid for. Access needs both.
546
+
547
+ What was paid for is the host's to say, not this library's. An on-premises install reads it from its licence, and a SaaS app from its billing. The host registers one function in the auth process, in the same boot file as [hooks](#hooks):
548
+
549
+ ```js
550
+ var auth = require('@xeplr/auth')
551
+ auth.licence.use({
552
+ modulesFor: async function(userId) { return ['bi', 'warehouse'] } // this user's modules
553
+ })
554
+ auth.boot()
555
+ ```
556
+
557
+ - **Nothing registered:** no filtering. Every module is allowed, exactly as before.
558
+ - **`core` is always allowed,** whatever the function answers: a user who cannot sign in cannot be told they are unlicensed.
559
+ - **APIs:** an API of another module is `unlicensed`, which `/verify`, `accessMiddleware` and `accessGate` answer with `403 UNLICENSED`. This is checked before roles, so no role mapping, public flag or missing mapping gets past it.
560
+ - **The access object:** it leaves those rows out entirely (`apis`, `pages`, `elements`, `menus`, public ones included). They are not greyed out: the product was not bought.
561
+ - **Timing:** the answer is folded into the user's cached access (5 minutes). A change, such as a seat given or taken, reaches the user within that, or at once after `accessService.clearUserAccess(userId)`.
562
+
536
563
  ## Multi-tenancy
537
564
 
538
565
  `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.
package/index.js CHANGED
@@ -18,6 +18,7 @@ const { accessMiddleware, requireRole } = require('./lib/accessMiddleware');
18
18
  const sessionService = require('./lib/sessionService');
19
19
  const ticketService = require('./lib/ticketService');
20
20
  const hooks = require('./lib/hooks');
21
+ const licence = require('./lib/licence');
21
22
  const mtMembershipMiddleware = require('./lib/mtMembershipMiddleware');
22
23
  const createAuthRouter = require('./lib/authRouter');
23
24
  const createAdminRouter = require('./lib/adminRouter');
@@ -426,5 +427,6 @@ module.exports = {
426
427
  sessionService,
427
428
  ticketService,
428
429
  hooks,
430
+ licence,
429
431
  models
430
432
  };
@@ -1,12 +1,20 @@
1
1
  const { verifyToken } = require('./authHelper');
2
2
  const accessService = require('./accessService');
3
3
  const { getApiRule, userApiState } = accessService;
4
+ const licence = require('./licence');
5
+
6
+ /** The 403 for a state that is not 'enabled'. Anything unknown is HIDDEN: refused. */
7
+ function refuse(res, state) {
8
+ if (state === 'unlicensed') return res.status(403).json({ error: 'This is not part of your licence', code: 'UNLICENSED' });
9
+ if (state === 'disabled') return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
10
+ return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
11
+ }
4
12
 
5
13
  /**
6
14
  * Access-aware middleware.
7
15
  * 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.
16
+ * Only 'enabled' goes through; 'disabled', 'hidden' and 'unlicensed' are
17
+ * refused, each with its own code so a UI can tell them apart.
10
18
  *
11
19
  * Usage:
12
20
  * app.use('/api', accessMiddleware());
@@ -26,8 +34,10 @@ function accessMiddleware(options = {}) {
26
34
  // Single cached lookup for API rule (public flag + role IDs)
27
35
  const rule = await getApiRule(apiName);
28
36
 
29
- // Not in DB, or marked public, or no role mappings = open
30
- if (!rule.exists || rule.isPublic || rule.unmapped) return next();
37
+ // Not in DB, or marked public, or no role mappings = open — unless the
38
+ // row belongs to a sold module, which needs a user to check the licence of.
39
+ var open = !rule.exists || rule.isPublic || rule.unmapped;
40
+ if (open && (!rule.exists || rule.licenseModule === licence.CORE || !rule.licenseModule)) return next();
31
41
 
32
42
  // From here, auth is required
33
43
  const authHeader = req.headers.authorization;
@@ -48,10 +58,7 @@ function accessMiddleware(options = {}) {
48
58
  // The user's state for this API (also cached)
49
59
  var state = await userApiState(decoded.id, apiName);
50
60
  if (state === 'enabled') return next();
51
- if (state === 'disabled') {
52
- return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
53
- }
54
- return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
61
+ refuse(res, state);
55
62
  };
56
63
  }
57
64
 
@@ -74,10 +81,7 @@ function accessGate() {
74
81
  return res.status(503).json({ error: 'Access rules are unavailable; try again shortly' });
75
82
  }
76
83
  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' });
84
+ refuse(res, answer.state);
81
85
  };
82
86
  }
83
87
 
@@ -6,6 +6,7 @@ const Menu = require('../models/Menu');
6
6
  const UiElement = require('../models/UiElement');
7
7
  const { visibleItems } = require('./menuService');
8
8
  const { matchApi } = require('./apiMatch');
9
+ const licence = require('./licence');
9
10
 
10
11
  // Cache TTLs (seconds)
11
12
  const USER_ACCESS_TTL = 300; // 5 min — user's full access object
@@ -36,6 +37,11 @@ async function getUserAccess(userId) {
36
37
  return empty;
37
38
  }
38
39
 
40
+ // Rows of a module this user is not licensed for are left out entirely:
41
+ // not greyed, not usable. See lib/licence.js.
42
+ const modules = await licence.modulesFor(userId);
43
+ function licensed(row) { return licence.allows(modules, row.licenseModule); }
44
+
39
45
  const roleNames = new Set();
40
46
  const pages = new Set();
41
47
  const apis = new Set();
@@ -53,6 +59,7 @@ async function getUserAccess(userId) {
53
59
  const enabledMenus = new Set();
54
60
  function sortInto(rows, enabled, disabled) {
55
61
  for (const row of rows || []) {
62
+ if (!licensed(row)) continue;
56
63
  if (row.state === 'disabled') disabled.add(row.name);
57
64
  else enabled.add(row.name);
58
65
  }
@@ -65,18 +72,22 @@ async function getUserAccess(userId) {
65
72
  sortInto(role.uiElements, elements, disabledElements);
66
73
  sortInto(role.menus, enabledMenus, disabledMenus);
67
74
  if (role.menus) {
68
- for (const menu of role.menus) menuRows.push(menu);
75
+ for (const menu of role.menus) if (licensed(menu)) menuRows.push(menu);
69
76
  }
70
77
  }
71
78
 
72
- // Add public items
79
+ // Add public items — public to every role, still only within the licence.
73
80
  const publicItems = await getPublicItems();
74
- for (const api of publicItems.apis) apis.add(api);
75
- for (const page of publicItems.pages) pages.add(page);
81
+ const publicModules = publicItems.licenseModules || {};
82
+ function licensedPublic(kind, name) { return licence.allows(modules, publicModules[kind + ':' + name]); }
83
+ for (const api of publicItems.apis) if (licensedPublic('api', api)) apis.add(api);
84
+ for (const page of publicItems.pages) if (licensedPublic('page', page)) pages.add(page);
76
85
  // Rows, not just names: a hidden item is left out, and each keeps its label
77
86
  // and position. Caches written before labels existed carry names only.
78
- for (const menu of publicItems.menuItems || publicItems.menus.map((name) => ({ name }))) menuRows.push(menu);
79
- for (const name of publicItems.menus || []) enabledMenus.add(name);
87
+ for (const menu of publicItems.menuItems || publicItems.menus.map((name) => ({ name }))) {
88
+ if (licensedPublic('menu', menu.name)) menuRows.push(menu);
89
+ }
90
+ for (const name of publicItems.menus || []) if (licensedPublic('menu', name)) enabledMenus.add(name);
80
91
  // Enabled through any role (or public) beats disabled through another.
81
92
  const menuItems = visibleItems(menuRows).map(function(m) {
82
93
  return (disabledMenus.has(m.name) && !enabledMenus.has(m.name)) ? Object.assign({}, m, { disabled: true }) : m;
@@ -122,8 +133,13 @@ async function getPublicItems() {
122
133
  apis: publicApis.map(a => a.name),
123
134
  pages: publicPages.map(p => p.name),
124
135
  menus: publicMenus.filter(m => !m.isHidden).map(m => m.name),
125
- menuItems: publicMenus.map(m => ({ name: m.name, label: m.label || null, sortOrder: m.sortOrder === undefined ? null : m.sortOrder, isHidden: !!m.isHidden }))
136
+ menuItems: publicMenus.map(m => ({ name: m.name, label: m.label || null, sortOrder: m.sortOrder === undefined ? null : m.sortOrder, isHidden: !!m.isHidden })),
137
+ // 'api:<name>' / 'page:<name>' / 'menu:<name>' → licenseModule, for rows of a product.
138
+ licenseModules: {}
126
139
  };
140
+ publicApis.forEach(function(a) { if (a.licenseModule && a.licenseModule !== licence.CORE) result.licenseModules['api:' + a.name] = a.licenseModule; });
141
+ publicPages.forEach(function(p) { if (p.licenseModule && p.licenseModule !== licence.CORE) result.licenseModules['page:' + p.name] = p.licenseModule; });
142
+ publicMenus.forEach(function(m) { if (m.licenseModule && m.licenseModule !== licence.CORE) result.licenseModules['menu:' + m.name] = m.licenseModule; });
127
143
 
128
144
  await cache.set(publicItemsKey, result, API_RULES_TTL);
129
145
  return result;
@@ -144,7 +160,7 @@ async function getApiRule(apiName) {
144
160
 
145
161
  if (!api) {
146
162
  // Not registered = open
147
- const rule = { exists: false, isPublic: true, roleIds: [] };
163
+ const rule = { exists: false, isPublic: true, roleIds: [], licenseModule: licence.CORE };
148
164
  await cache.set(cacheKey, rule, API_RULES_TTL);
149
165
  return rule;
150
166
  }
@@ -159,7 +175,8 @@ async function getApiRule(apiName) {
159
175
  isPublic: !!api.isPublic,
160
176
  unmapped: mapped.length === 0,
161
177
  roleIds,
162
- disabledRoleIds
178
+ disabledRoleIds,
179
+ licenseModule: api.licenseModule || licence.CORE
163
180
  };
164
181
 
165
182
  await cache.set(cacheKey, rule, API_RULES_TTL);
@@ -169,14 +186,17 @@ async function getApiRule(apiName) {
169
186
  /**
170
187
  * Access states. A gate answers one of these, not true/false:
171
188
  *
172
- * enabled shown and usable
173
- * disabled shown, greyed out, not usable: the API refuses it
174
- * hidden not shown: the API refuses it
189
+ * enabled shown and usable
190
+ * disabled shown, greyed out, not usable: the API refuses it
191
+ * hidden not shown: the API refuses it
192
+ * unlicensed not shown: the API belongs to a module the user's licence
193
+ * does not include (lib/licence.js). Checked before roles, so
194
+ * no role, public flag or missing mapping gets past it.
175
195
  *
176
196
  * A role mapping row decides: no row → hidden; a row → its state (enabled,
177
197
  * or disabled from the Access Matrix). Several roles: the most open wins.
178
198
  */
179
- var ACCESS_STATES = ['enabled', 'disabled', 'hidden'];
199
+ var ACCESS_STATES = ['enabled', 'disabled', 'hidden', 'unlicensed'];
180
200
 
181
201
  /**
182
202
  * The state for an API rule and a user's role ids. Pure, so it can be tested
@@ -215,6 +235,7 @@ async function userRoleIdsOf(userId) {
215
235
  */
216
236
  async function userApiState(userId, apiName) {
217
237
  var rule = await getApiRule(apiName);
238
+ if (rule.exists && !licence.allows(await licence.modulesFor(userId), rule.licenseModule)) return 'unlicensed';
218
239
  if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
219
240
  return apiStateFor(rule, await userRoleIdsOf(userId));
220
241
  }
package/lib/authRouter.js CHANGED
@@ -240,6 +240,9 @@ function createAuthRouter(options = {}) {
240
240
  var access = await getUserAccess(req.user.id);
241
241
  return res.json({ user: req.user, access: access, state: 'enabled', api: answer.api });
242
242
  }
243
+ if (answer.state === 'unlicensed') {
244
+ return res.status(403).json({ error: 'This is not part of your licence', code: 'UNLICENSED', api: answer.api });
245
+ }
243
246
  if (answer.state === 'disabled') {
244
247
  return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED', api: answer.api });
245
248
  }
package/lib/licence.js ADDED
@@ -0,0 +1,47 @@
1
+ // WHICH SOLD MODULES A USER MAY USE.
2
+ //
3
+ // Every catalog row (apis, menus, uiPages, uiElements) carries a licenseModule
4
+ // (0007): 'core' for sign-in and everything that belongs to no product, or the
5
+ // product it was sold as ('bi', 'warehouse', 'xflow', ...). Roles say what a
6
+ // user's job lets them do; this says what was paid for. Access is both.
7
+ //
8
+ // What was paid for is the host app's to say, not this library's: an
9
+ // on-premises install reads it from its signed licence, a SaaS app from its
10
+ // billing. So the host registers one function, in the auth process (the same
11
+ // file that calls boot(), as for hooks):
12
+ //
13
+ // require('@xeplr/auth').licence.use({
14
+ // modulesFor: async function(userId) { return ['bi', 'warehouse']; }
15
+ // });
16
+ //
17
+ // Nothing registered: no filtering at all, as before this existed. 'core' is
18
+ // always allowed, whatever the function answers: a user who cannot sign in
19
+ // cannot be told they are unlicensed.
20
+ //
21
+ // The answer is folded into the user's cached access (5 minutes), so a seat
22
+ // given or taken reaches the user within that, or at once after
23
+ // clearUserAccess(userId).
24
+
25
+ var CORE = 'core';
26
+ var _modulesFor = null;
27
+
28
+ function use(options) {
29
+ var fn = options && options.modulesFor;
30
+ if (fn !== undefined && fn !== null && typeof fn !== 'function') throw new Error('licence.use: modulesFor must be a function');
31
+ _modulesFor = fn || null;
32
+ }
33
+
34
+ /** The Set of modules this user may use, or null when no host registered one (everything allowed). */
35
+ async function modulesFor(userId) {
36
+ if (!_modulesFor) return null;
37
+ var modules = new Set((await _modulesFor(userId)) || []);
38
+ modules.add(CORE);
39
+ return modules;
40
+ }
41
+
42
+ /** Is a row of this licenseModule allowed under these modules? */
43
+ function allows(modules, licenseModule) {
44
+ return !modules || modules.has(licenseModule || CORE);
45
+ }
46
+
47
+ module.exports = { use: use, modulesFor: modulesFor, allows: allows, CORE: CORE };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.1.8",
3
+ "version": "1.2.0",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [