@xeplr/auth 1.4.0 → 1.5.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
@@ -307,7 +307,7 @@ Client code must read the header and replace its stored token, or the session en
307
307
  | `POST /logout` | — | `{ refreshToken }` → ends that session |
308
308
  | `POST /forgot-password` | — | `{ email }` → the same message whether or not the address exists; emails `AUTH_RESET_URL?token=…` (or `<resetBaseUrl>/auth/reset-password` when the router is given `resetBaseUrl`). `503` for every address alike when the reset address or mail is not set up |
309
309
  | `POST /reset-password` | — | `{ token, newPassword }`; `400` once the link is older than `AUTH_RESET_TOKEN_EXPIRY_MINUTES` |
310
- | `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims |
310
+ | `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims. With `x-verify-tenant` (`{ "l1": "<company>", "l2": "<workspace>" }`), `access` is as the user is there: their own roles plus the ones their membership gives them ([roles held in a company](#roles-held-in-a-company-or-workspace)). Not a member: `403 NOT_A_MEMBER`; unreadable: `400 BAD_TENANT` |
311
311
  | `GET /verify` | ✓ | the check every app's gate makes on every request — see [Every request is checked](#every-request-is-checked) |
312
312
  | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
313
313
  | `POST /profile/avatar` | ✓ | multipart `avatar`, an image up to 2 MB; stores the file name only — serving `UPLOAD_DIR` is the app's job |
@@ -584,6 +584,15 @@ auth.boot()
584
584
 
585
585
  `@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. **Super Admin passes whatever the headers say**: the role runs the whole install, so it goes into every company and workspace without a membership row.
586
586
 
587
+ ### Roles held in a company or workspace
588
+
589
+ A membership row's `roleId` is the role the user holds **there**. Whenever a request names that company or workspace, the roles that count are the user's own roles **plus** the roles on their own membership rows for the values it names. Outside it they don't apply. **Whoever creates a company is its CompanyAdmin this way** (Xeplr BI grants it when the company is made), while their own role stays what it was everywhere else: a self-registered Viewer is a Viewer on the platform and the admin of the one company they made.
590
+
591
+ - **Where it counts:** `/verify` (with `x-verify-tenant`, as an app's gate sends it), `/me` (with the same header), `accessMiddleware` and `accessGate` (`x-verify-tenant`, else the app's own MT headers when the process registered them, `tenantsOfRequest`). One function, `accessService.tenantRoleIdsOf(userId, tenants)`.
592
+ - **Naming a company gives nothing by itself.** Only the user's own active rows are read, so a header naming another company finds no role there; `/verify` and `/me` refuse it as `NOT_A_MEMBER` first.
593
+ - **A company role counts in all of its workspaces**, a workspace role only in that workspace: a request naming `{ l1, l2 }` reads both rows.
594
+ - **Cached per user and tenant** under `access:user:<id>:…`, 5 minutes. After changing a membership's role, `clearUserAccess(userId)` makes it count at once.
595
+
587
596
  ### Roles belong to a company
588
597
 
589
598
  Two separate questions: **where** a row belongs (`mtId1`) and **who** may use it (`scope`, see [system scope](#system-scope)).
@@ -636,6 +645,8 @@ npm test # node --test test/*.test.js
636
645
 
637
646
  `test/signUpFlow.test.js` runs the whole sign-up flow over HTTP against a local PostgreSQL and Redis, with real mail: nodemailer (the workspace dev dependency) talks SMTP to a small listener inside the test. It is skipped when any of the three is missing.
638
647
 
648
+ `test/scopedRoles.test.js` checks roles held in a company or workspace (local PostgreSQL and Redis; skipped without either): the company a Viewer created lets them import there and only there (`HIDDEN` naming none, or another company where they are a plain member; `NOT_A_MEMBER` naming a stranger's); a workspace role counts in that workspace and the company role in all of its workspaces; `/me` answers as the user is in the company named; a role taken away is gone after `clearUserAccess`; an app running auth in-process (`accessMiddleware`) reads the company from the request.
649
+
639
650
  `test/verifyTenant.test.js` checks the membership answer on real memberships (local PostgreSQL and Redis; skipped without either): a member of company and workspace passes and is told `tenant: 'checked'`; another company, another workspace and a switched-off membership are `403 NOT_A_MEMBER`; Super Admin passes; a request naming none is not checked and does not claim to be; an unreadable `x-verify-tenant` is `400 BAD_TENANT`.
640
651
 
641
652
  `test/menuItems.test.js` needs a local PostgreSQL (the usual `PG*` variables): it creates and drops a throwaway database, and is skipped when none is reachable. The token-decision and `REDIS_PREFIX` tests need nothing.
@@ -2,6 +2,7 @@ const { verifyToken } = require('./authHelper');
2
2
  const accessService = require('./accessService');
3
3
  const { getApiRule, userApiState } = accessService;
4
4
  const licence = require('./licence');
5
+ const { tenantsOfRequest } = require('./mtMembershipMiddleware');
5
6
 
6
7
  /** The 403 for a state that is not 'enabled'. Anything unknown is HIDDEN: refused. */
7
8
  function refuse(res, state) {
@@ -55,8 +56,11 @@ function accessMiddleware(options = {}) {
55
56
 
56
57
  req.user = decoded;
57
58
 
58
- // The user's state for this API (also cached)
59
- var state = await userApiState(decoded.id, apiName);
59
+ // The user's state for this API (also cached) — in the company/workspace
60
+ // the request names, where their membership may give them a role.
61
+ var tenants = tenantsOfRequest(req);
62
+ if (tenants === false) return res.status(400).json({ error: 'x-verify-tenant must be { "l1": "<id>", … }', code: 'BAD_TENANT' });
63
+ var state = await userApiState(decoded.id, apiName, tenants);
60
64
  if (state === 'enabled') return next();
61
65
  refuse(res, state);
62
66
  };
@@ -73,9 +77,11 @@ function accessMiddleware(options = {}) {
73
77
  function accessGate() {
74
78
  return async function(req, res, next) {
75
79
  var path = (req.baseUrl || '') + (req.path || '');
80
+ var tenants = tenantsOfRequest(req);
81
+ if (tenants === false) return res.status(400).json({ error: 'x-verify-tenant must be { "l1": "<id>", … }', code: 'BAD_TENANT' });
76
82
  var answer;
77
83
  try {
78
- answer = await accessService.requestApiState(req.user && req.user.id, req.method, path);
84
+ answer = await accessService.requestApiState(req.user && req.user.id, req.method, path, tenants);
79
85
  } catch (err) {
80
86
  if (req.log) req.log.error('access check failed: ' + err.message);
81
87
  return res.status(503).json({ error: 'Access rules are unavailable; try again shortly' });
@@ -4,6 +4,8 @@ const Api = require('../models/Api');
4
4
  const UiPage = require('../models/UiPage');
5
5
  const Menu = require('../models/Menu');
6
6
  const UiElement = require('../models/UiElement');
7
+ const Role = require('../models/Role');
8
+ const UserTenantsMapping = require('../models/UserTenantsMapping');
7
9
  const { visibleItems } = require('./menuService');
8
10
  const { matchApi } = require('./apiMatch');
9
11
  const licence = require('./licence');
@@ -13,18 +15,61 @@ const USER_ACCESS_TTL = 300; // 5 min — user's full access object
13
15
  const API_RULES_TTL = 600; // 10 min — api public/role data (changes rarely)
14
16
 
15
17
  // Cache key helpers
16
- const userAccessKey = (userId) => `access:user:${userId}`;
18
+ // With a company/workspace named, the answer includes the roles held there,
19
+ // so it is cached per tenant too. Both stay under access:user:<id>, which
20
+ // clearUserAccess() and clearAllAccess() clear.
21
+ const SLOT_KEYS = ['l1', 'l2', 'l3', 'l4'];
22
+ function tenantSuffix(tenants) {
23
+ if (!tenants) return '';
24
+ var parts = SLOT_KEYS.filter(function(k) { return tenants[k]; }).map(function(k) { return k + '=' + encodeURIComponent(String(tenants[k])); });
25
+ return parts.length ? ':t:' + parts.join('&') : '';
26
+ }
27
+ const userAccessKey = (userId, tenants) => `access:user:${userId}${tenantSuffix(tenants)}`;
28
+ const tenantRolesKey = (userId, tenants) => `access:user:${userId}:roles${tenantSuffix(tenants)}`;
17
29
  const apiRulesKey = (apiName) => `access:api:${encodeURIComponent(apiName)}`;
18
30
  const publicItemsKey = 'access:public';
19
31
  const catalogKey = 'access:api:catalog'; // under access:api:*, so clearAccessRules() clears it
20
32
 
21
33
  /**
22
- * Fetch the full access object for a user.
34
+ * THE ROLES A USER HOLDS IN A COMPANY OR WORKSPACE — the roleId on their own
35
+ * membership rows (userTenantsMapping) for the values a request names.
36
+ * Whoever creates a company is its CompanyAdmin this way: in that company
37
+ * only, while their own role stays what it was everywhere else.
38
+ *
39
+ * Only the user's OWN rows count, so naming a company in a header can never
40
+ * give a role: without a membership row there, there is nothing to read
41
+ * (and /verify refuses the request as NOT_A_MEMBER first).
42
+ *
43
+ * @param tenants { l1: '<company>', l2: '<workspace>' }; absent → none
44
+ * @returns role ids, cached per user and tenant
45
+ */
46
+ async function tenantRoleIdsOf(userId, tenants) {
47
+ if (!userId || !tenantSuffix(tenants)) return [];
48
+ var key = tenantRolesKey(userId, tenants);
49
+ var cached = await cache.get(key);
50
+ if (Array.isArray(cached)) return cached;
51
+ var rows = await UserTenantsMapping.query()
52
+ .where({ userId: userId, isActive: true })
53
+ .whereNotNull('roleId')
54
+ .where(function(q) {
55
+ SLOT_KEYS.forEach(function(k) {
56
+ if (tenants[k]) q.orWhere({ level: k, value: String(tenants[k]) });
57
+ });
58
+ })
59
+ .select('roleId');
60
+ var ids = [...new Set(rows.map(function(r) { return r.roleId; }))];
61
+ await cache.set(key, ids, USER_ACCESS_TTL);
62
+ return ids;
63
+ }
64
+
65
+ /**
66
+ * Fetch the full access object for a user — with `tenants`, as they are in
67
+ * that company/workspace: their own roles plus the ones held there.
23
68
  * Cached in Redis. Use clearUserAccess() to invalidate.
24
69
  */
25
- async function getUserAccess(userId) {
70
+ async function getUserAccess(userId, tenants) {
26
71
  // Check cache first
27
- const cached = await cache.get(userAccessKey(userId));
72
+ const cached = await cache.get(userAccessKey(userId, tenants));
28
73
  if (cached) return cached;
29
74
 
30
75
  const user = await User.query()
@@ -33,10 +78,18 @@ async function getUserAccess(userId) {
33
78
 
34
79
  if (!user || !user.roles) {
35
80
  const empty = { roles: [], pages: [], apis: [], menus: [], menuItems: [], elements: [] };
36
- await cache.set(userAccessKey(userId), empty, USER_ACCESS_TTL);
81
+ await cache.set(userAccessKey(userId, tenants), empty, USER_ACCESS_TTL);
37
82
  return empty;
38
83
  }
39
84
 
85
+ // The roles held in the named company/workspace, beside the user's own.
86
+ const own = new Set(user.roles.map(function(r) { return r.id; }));
87
+ const scopedIds = (await tenantRoleIdsOf(userId, tenants)).filter(function(id) { return !own.has(id); });
88
+ const scoped = scopedIds.length
89
+ ? await Role.query().findByIds(scopedIds).withGraphFetched('[apis, uiPages, uiElements, menus]')
90
+ : [];
91
+ const roles = user.roles.concat(scoped);
92
+
40
93
  // Rows of a module this user is not licensed for are left out entirely:
41
94
  // not greyed, not usable. See lib/licence.js.
42
95
  const modules = await licence.modulesFor(userId);
@@ -65,7 +118,7 @@ async function getUserAccess(userId) {
65
118
  }
66
119
  }
67
120
 
68
- for (const role of user.roles) {
121
+ for (const role of roles) {
69
122
  roleNames.add(role.name);
70
123
  sortInto(role.apis, apis, disabledApis);
71
124
  sortInto(role.uiPages, pages, disabledPages);
@@ -112,7 +165,7 @@ async function getUserAccess(userId) {
112
165
  }
113
166
  };
114
167
 
115
- await cache.set(userAccessKey(userId), access, USER_ACCESS_TTL);
168
+ await cache.set(userAccessKey(userId, tenants), access, USER_ACCESS_TTL);
116
169
  return access;
117
170
  }
118
171
 
@@ -231,13 +284,15 @@ async function userRoleIdsOf(userId) {
231
284
 
232
285
  /**
233
286
  * A user's state for a specific API: 'enabled' | 'disabled' | 'hidden'.
234
- * Uses cached API rules and cached user roles.
287
+ * Uses cached API rules and cached user roles — with `tenants`, the roles
288
+ * held in that company/workspace as well (tenantRoleIdsOf).
235
289
  */
236
- async function userApiState(userId, apiName) {
290
+ async function userApiState(userId, apiName, tenants) {
237
291
  var rule = await getApiRule(apiName);
238
292
  if (rule.exists && !licence.allows(await licence.modulesFor(userId), rule.licenseModule)) return 'unlicensed';
239
293
  if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
240
- return apiStateFor(rule, await userRoleIdsOf(userId));
294
+ var ids = (await userRoleIdsOf(userId)).concat(await tenantRoleIdsOf(userId, tenants));
295
+ return apiStateFor(rule, ids);
241
296
  }
242
297
 
243
298
  /** Every API name in the catalog, cached like the other access rules. */
@@ -256,15 +311,15 @@ async function catalogApiNames() {
256
311
  *
257
312
  * @returns { api, state } api is the matched name, or null
258
313
  */
259
- async function requestApiState(userId, method, path) {
314
+ async function requestApiState(userId, method, path, tenants) {
260
315
  var api = matchApi(await catalogApiNames(), method, path);
261
316
  if (!api) return { api: null, state: 'enabled' };
262
- return { api: api, state: await userApiState(userId, api) };
317
+ return { api: api, state: await userApiState(userId, api, tenants) };
263
318
  }
264
319
 
265
320
  /** True only when the state is enabled. Kept for callers that want a yes/no. */
266
- async function userHasApiAccess(userId, apiName) {
267
- return (await userApiState(userId, apiName)) === 'enabled';
321
+ async function userHasApiAccess(userId, apiName, tenants) {
322
+ return (await userApiState(userId, apiName, tenants)) === 'enabled';
268
323
  }
269
324
 
270
325
  /**
@@ -274,6 +329,8 @@ async function userHasApiAccess(userId, apiName) {
274
329
  async function clearUserAccess(userId) {
275
330
  await Promise.all([
276
331
  cache.del(userAccessKey(userId)),
332
+ // Per company/workspace, and the roles held there.
333
+ cache.delPattern(`access:user:${userId}:*`),
277
334
  cache.del(`access:userRoles:${userId}`)
278
335
  ]);
279
336
  }
@@ -303,6 +360,7 @@ module.exports = {
303
360
  clearAllAccess,
304
361
  getUserAccess,
305
362
  requestApiState,
363
+ tenantRoleIdsOf,
306
364
  userApiState,
307
365
  userHasApiAccess,
308
366
  clearUserAccess,
package/lib/authRouter.js CHANGED
@@ -5,7 +5,7 @@ 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 { refusedTenant, SLOT_KEYS } = require('./mtMembershipMiddleware');
8
+ const { refusedTenant, readTenants } = require('./mtMembershipMiddleware');
9
9
  const { accessGate } = require('./accessMiddleware');
10
10
 
11
11
  // Signed in AND allowed this route by the catalog: the same two checks every
@@ -19,24 +19,6 @@ const User = require('../models/User');
19
19
  // path on the user; serving it back over HTTP is the consuming app's concern
20
20
  // (same as any other uploaded asset), so wire a static route to the same
21
21
  // directory wherever it makes sense for your deployment.
22
- /**
23
- * x-verify-tenant → { l1: '…', … }, or null when it is not one: an object of
24
- * known levels (l1–l4), each a non-empty id. Anything else is refused rather
25
- * than read past — a check that cannot read what it was asked must not pass.
26
- */
27
- function readTenants(header) {
28
- var parsed;
29
- try { parsed = JSON.parse(header); } catch (e) { return null; }
30
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
31
- var keys = Object.keys(parsed);
32
- if (!keys.length) return null;
33
- for (var i = 0; i < keys.length; i++) {
34
- var v = parsed[keys[i]];
35
- if (SLOT_KEYS.indexOf(keys[i]) === -1 || typeof v !== 'string' || !v || v.length > 255) return null;
36
- }
37
- return parsed;
38
- }
39
-
40
22
  const avatarUploader = new FileUploader({ allowedTypes: ['image/*'], maxSize: 2 * 1024 * 1024 });
41
23
 
42
24
  function logError(req, err) {
@@ -261,9 +243,20 @@ function createAuthRouter(options = {}) {
261
243
  }
262
244
  });
263
245
 
246
+ // What this user may see and do — with x-verify-tenant ({ "l1": "<company>",
247
+ // "l2": "<workspace>" }), as they are THERE: their own roles plus the ones
248
+ // their membership gives them (the company they created: CompanyAdmin).
249
+ // Not a member → 403 NOT_A_MEMBER, as /verify answers.
264
250
  router.get('/me', signedInAndAllowed, async function(req, res) {
265
251
  try {
266
- const access = await getUserAccess(req.user.id);
252
+ var tenants = null;
253
+ if (req.headers['x-verify-tenant']) {
254
+ tenants = readTenants(req.headers['x-verify-tenant']);
255
+ if (!tenants) return res.status(400).json({ error: 'x-verify-tenant must be { "l1": "<id>", … }', code: 'BAD_TENANT' });
256
+ var notMember = await refusedTenant(req.user, tenants);
257
+ if (notMember) return res.status(403).json({ error: 'Not a member of ' + notMember.level + ' "' + notMember.value + '"', code: 'NOT_A_MEMBER' });
258
+ }
259
+ const access = await getUserAccess(req.user.id, tenants);
267
260
  res.json({
268
261
  user: req.user,
269
262
  access
@@ -303,9 +296,12 @@ function createAuthRouter(options = {}) {
303
296
  return res.status(403).json({ error: 'Not a member of ' + refused.level + ' "' + refused.value + '"', code: 'NOT_A_MEMBER' });
304
297
  }
305
298
  }
306
- var answer = await requestApiState(req.user.id, method, path);
299
+ // The roles held in the named company/workspace count too: whoever
300
+ // created a company is its CompanyAdmin there (accessService
301
+ // tenantRoleIdsOf), and only there.
302
+ var answer = await requestApiState(req.user.id, method, path, tenants);
307
303
  if (answer.state === 'enabled') {
308
- var access = await getUserAccess(req.user.id);
304
+ var access = await getUserAccess(req.user.id, tenants);
309
305
  var ok = { user: req.user, access: access, state: 'enabled', api: answer.api };
310
306
  if (tenants) ok.tenant = 'checked';
311
307
  return res.json(ok);
@@ -54,6 +54,45 @@ async function refusedTenant(user, tenants, Model) {
54
54
  return null;
55
55
  }
56
56
 
57
+ /**
58
+ * x-verify-tenant → { l1: '…', … }, or null when it is not one: an object of
59
+ * known levels (l1–l4), each a non-empty id. Anything else is refused rather
60
+ * than read past — a check that cannot read what it was asked must not pass.
61
+ */
62
+ function readTenants(header) {
63
+ var parsed;
64
+ try { parsed = JSON.parse(header); } catch (e) { return null; }
65
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
66
+ var keys = Object.keys(parsed);
67
+ if (!keys.length) return null;
68
+ for (var i = 0; i < keys.length; i++) {
69
+ var v = parsed[keys[i]];
70
+ if (SLOT_KEYS.indexOf(keys[i]) === -1 || typeof v !== 'string' || !v || v.length > 255) return null;
71
+ }
72
+ return parsed;
73
+ }
74
+
75
+ /**
76
+ * The company/workspace a request is about, as levels: x-verify-tenant when
77
+ * it says (an app's gate asking /verify, a UI asking /me), else the app's own
78
+ * MT headers when this process registered them. null when neither names one;
79
+ * false when x-verify-tenant is there but unreadable.
80
+ */
81
+ function tenantsOfRequest(req) {
82
+ var header = req.headers && req.headers['x-verify-tenant'];
83
+ if (header) return readTenants(header) || false;
84
+ var mtConfig;
85
+ try { mtConfig = getMtConfig(); } catch (e) { return null; }
86
+ if (!mtConfig || !mtConfig.enabled) return null;
87
+ var tenants = {};
88
+ SLOT_KEYS.forEach(function(key) {
89
+ var slot = mtConfig.slots[key];
90
+ var value = slot && req.headers[slot.header];
91
+ if (typeof value === 'string' && value) tenants[key] = value;
92
+ });
93
+ return Object.keys(tenants).length ? tenants : null;
94
+ }
95
+
57
96
  function mtMembershipMiddleware(options) {
58
97
  options = options || {};
59
98
  var Model = options.userTenantsMapping || UserTenantsMapping;
@@ -83,3 +122,5 @@ function mtMembershipMiddleware(options) {
83
122
  module.exports = mtMembershipMiddleware;
84
123
  module.exports.refusedTenant = refusedTenant;
85
124
  module.exports.SLOT_KEYS = SLOT_KEYS;
125
+ module.exports.readTenants = readTenants;
126
+ module.exports.tenantsOfRequest = tenantsOfRequest;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [