@xeplr/auth 1.3.0 → 1.4.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
@@ -522,15 +522,20 @@ GET /auth/api/verify
522
522
  Authorization: Bearer <the caller's token>
523
523
  x-verify-method: GET
524
524
  x-verify-path: /widget-templates/abc
525
+ x-verify-tenant: {"l1":"<company>","l2":"<workspace>"} ← when the request names one
525
526
  ```
526
527
 
528
+ **And whether the user belongs to the company and workspace the request names.** The gate sends them as `x-verify-tenant`, by level (`l1`–`l4`, as memberships are kept — auth needs no app's header names). A user without an active membership for each is refused here, `403 NOT_A_MEMBER`, before the app sees the request; Super Admin belongs to every one. This is the same check as `mtMembershipMiddleware` (`refusedTenant`, one function), so an app on `createApp` never adds it route by route. The answer carries `tenant: 'checked'` whenever it checked, so a gate can refuse an older auth that would have ignored the header.
529
+
527
530
  | answer | when |
528
531
  |---|---|
529
- | `200 { user, access, state: 'enabled', api }` | token good, API allowed. `api` is the catalog row it matched, or `null` (not registered, so open) |
532
+ | `200 { user, access, state: 'enabled', api, tenant? }` | token good, API allowed (and, with `x-verify-tenant`, a member of each: `tenant: 'checked'`). `api` is the catalog row it matched, or `null` (not registered, so open) |
530
533
  | `403 { code: 'DISABLED' }` · `403 { code: 'HIDDEN' }` | token good, API not allowed |
531
534
  | `403 { code: 'UNLICENSED' }` | token good, but the API belongs to a module the user's licence does not include |
532
535
  | `401` | bad or expired token (the same tolerance and `X-New-Token` sliding as every route) |
533
536
  | `400 { code: 'NO_REQUEST' }` | no method or path named: nothing to check, so refused |
537
+ | `403 { code: 'NOT_A_MEMBER' }` | token good, but no membership for a company or workspace in `x-verify-tenant` |
538
+ | `400 { code: 'BAD_TENANT' }` | `x-verify-tenant` is not `{ "l1": "<id>", … }` of known levels: refused, never read past |
534
539
 
535
540
  **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.
536
541
 
@@ -631,6 +636,8 @@ npm test # node --test test/*.test.js
631
636
 
632
637
  `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.
633
638
 
639
+ `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
+
634
641
  `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.
635
642
 
636
643
  ## License
package/lib/authRouter.js CHANGED
@@ -5,6 +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
9
  const { accessGate } = require('./accessMiddleware');
9
10
 
10
11
  // Signed in AND allowed this route by the catalog: the same two checks every
@@ -18,6 +19,24 @@ const User = require('../models/User');
18
19
  // path on the user; serving it back over HTTP is the consuming app's concern
19
20
  // (same as any other uploaded asset), so wire a static route to the same
20
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
+
21
40
  const avatarUploader = new FileUploader({ allowedTypes: ['image/*'], maxSize: 2 * 1024 * 1024 });
22
41
 
23
42
  function logError(req, err) {
@@ -259,17 +278,37 @@ function createAuthRouter(options = {}) {
259
278
  // (the token, with the same tolerance and sliding refresh as any route) AND
260
279
  // may they call this API. Both, always; there is no way to ask one without
261
280
  // the other. The app names the request it is serving in two headers.
281
+ //
282
+ // AND, when the request names a company or workspace, whether this user
283
+ // belongs to it: x-verify-tenant, { "l1": "<company>", "l2": "<workspace>" }
284
+ // (the levels as memberships are kept, so auth needs no app's header names).
285
+ // Not a member → 403 NOT_A_MEMBER, before the app sees the request. The
286
+ // answer says `tenant: 'checked'`, so a gate can tell this from an older
287
+ // auth that ignored the header. Super Admin belongs to every one.
262
288
  router.get('/verify', authMiddleware, async function(req, res) {
263
289
  var method = req.headers['x-verify-method'];
264
290
  var path = req.headers['x-verify-path'];
265
291
  if (!method || !path) {
266
292
  return res.status(400).json({ error: 'x-verify-method and x-verify-path are required', code: 'NO_REQUEST' });
267
293
  }
294
+ var tenants = null;
295
+ if (req.headers['x-verify-tenant']) {
296
+ tenants = readTenants(req.headers['x-verify-tenant']);
297
+ if (!tenants) return res.status(400).json({ error: 'x-verify-tenant must be { "l1": "<id>", … }', code: 'BAD_TENANT' });
298
+ }
268
299
  try {
300
+ if (tenants) {
301
+ var refused = await refusedTenant(req.user, tenants);
302
+ if (refused) {
303
+ return res.status(403).json({ error: 'Not a member of ' + refused.level + ' "' + refused.value + '"', code: 'NOT_A_MEMBER' });
304
+ }
305
+ }
269
306
  var answer = await requestApiState(req.user.id, method, path);
270
307
  if (answer.state === 'enabled') {
271
308
  var access = await getUserAccess(req.user.id);
272
- return res.json({ user: req.user, access: access, state: 'enabled', api: answer.api });
309
+ var ok = { user: req.user, access: access, state: 'enabled', api: answer.api };
310
+ if (tenants) ok.tenant = 'checked';
311
+ return res.json(ok);
273
312
  }
274
313
  if (answer.state === 'unlicensed') {
275
314
  return res.status(403).json({ error: 'This is not part of your licence', code: 'UNLICENSED', api: answer.api });
@@ -28,6 +28,32 @@ var SLOT_KEYS = ['l1', 'l2', 'l3', 'l4'];
28
28
  * app.use(mtMiddleware()); // @xeplr/db — sets mtId context
29
29
  * app.use(mtMembershipMiddleware()); // this — rejects forged values
30
30
  */
31
+ /**
32
+ * THE ONE MEMBERSHIP CHECK — this middleware's, and GET /verify's (which
33
+ * every app's gate asks on every request, @xeplr/base-apis remoteAuth).
34
+ *
35
+ * @param user the signed-in user ({ id, roles })
36
+ * @param tenants { l1: 'c1', l2: 'w1' } — a level absent or empty is not asked
37
+ * @param Model a bound UserTenantsMapping (default: this package's)
38
+ * @returns null when the user may use every value; else { level, value }, the
39
+ * first one refused. Super Admin may use any: running the whole
40
+ * install is the role. Everyone else needs a membership row per value.
41
+ */
42
+ async function refusedTenant(user, tenants, Model) {
43
+ Model = Model || UserTenantsMapping;
44
+ if (isSuperAdmin(user)) return null;
45
+ for (var i = 0; i < SLOT_KEYS.length; i++) {
46
+ var key = SLOT_KEYS[i];
47
+ var value = tenants && tenants[key];
48
+ if (value === undefined || value === null || value === '') continue;
49
+ var grant = await Model.query()
50
+ .where({ userId: user.id, level: key, value: String(value), isActive: true })
51
+ .first();
52
+ if (!grant) return { level: key, value: String(value) };
53
+ }
54
+ return null;
55
+ }
56
+
31
57
  function mtMembershipMiddleware(options) {
32
58
  options = options || {};
33
59
  var Model = options.userTenantsMapping || UserTenantsMapping;
@@ -36,27 +62,16 @@ function mtMembershipMiddleware(options) {
36
62
  try {
37
63
  var mtConfig = getMtConfig();
38
64
  if (!mtConfig.enabled || !req.user || !req.user.id) return next();
39
- // Super Admin goes into any company and workspace: running the whole
40
- // install is the role. Everyone else needs a membership row per value.
41
- if (isSuperAdmin(req.user)) return next();
42
-
43
- for (var i = 0; i < SLOT_KEYS.length; i++) {
44
- var key = SLOT_KEYS[i];
65
+ var tenants = {};
66
+ SLOT_KEYS.forEach(function(key) {
45
67
  var slot = mtConfig.slots[key];
46
- if (!slot) continue;
47
-
48
- var value = req.headers[slot.header];
49
- if (!value) continue;
50
-
51
- var grant = await Model.query()
52
- .where({ userId: req.user.id, level: key, value: value, isActive: true })
53
- .first();
54
-
55
- if (!grant) {
56
- return res.status(403).json({ error: 'Not authorized for ' + (slot.name || key) + ' "' + value + '"' });
57
- }
68
+ if (slot) tenants[key] = req.headers[slot.header];
69
+ });
70
+ var refused = await refusedTenant(req.user, tenants, Model);
71
+ if (refused) {
72
+ var slot = mtConfig.slots[refused.level];
73
+ return res.status(403).json({ error: 'Not authorized for ' + ((slot && slot.name) || refused.level) + ' "' + refused.value + '"' });
58
74
  }
59
-
60
75
  next();
61
76
  } catch (err) {
62
77
  if (req.log) req.log.error(err.message, { stack: err.stack });
@@ -66,3 +81,5 @@ function mtMembershipMiddleware(options) {
66
81
  }
67
82
 
68
83
  module.exports = mtMembershipMiddleware;
84
+ module.exports.refusedTenant = refusedTenant;
85
+ module.exports.SLOT_KEYS = SLOT_KEYS;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [