@xeplr/auth 1.1.5 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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);
@@ -0,0 +1,44 @@
1
+ -- 0013_mapping_state.sql
2
+ -- DISABLED: shown, greyed out, not usable.
3
+ --
4
+ -- A role mapping used to say only yes (a row) or no (no row): Enabled or
5
+ -- Hidden. `state` on the row is the third answer. A mapped item is
6
+ -- enabled usable (the default: every existing row stays as it was)
7
+ -- disabled shown, but the API refuses it
8
+ -- Hidden stays what it was: no row.
9
+ --
10
+ -- Set from the Access Matrix (POST /auth/api/admin/module-state), for a role.
11
+ -- Workspace and user overrides are not stored here.
12
+ --
13
+ -- Idempotent: columns and constraints added only if absent, rows only if
14
+ -- missing.
15
+
16
+ ALTER TABLE "apisRolesMapping" ADD COLUMN IF NOT EXISTS "state" varchar(10) NOT NULL DEFAULT 'enabled';
17
+ ALTER TABLE "uiPagesRolesMapping" ADD COLUMN IF NOT EXISTS "state" varchar(10) NOT NULL DEFAULT 'enabled';
18
+ ALTER TABLE "uiElementsRolesMapping" ADD COLUMN IF NOT EXISTS "state" varchar(10) NOT NULL DEFAULT 'enabled';
19
+ ALTER TABLE "menuRolesMapping" ADD COLUMN IF NOT EXISTS "state" varchar(10) NOT NULL DEFAULT 'enabled';
20
+
21
+ DO $$
22
+ DECLARE t text;
23
+ BEGIN
24
+ FOREACH t IN ARRAY ARRAY['apisRolesMapping', 'uiPagesRolesMapping', 'uiElementsRolesMapping', 'menuRolesMapping'] LOOP
25
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = t || '_state_check') THEN
26
+ EXECUTE format('ALTER TABLE %I ADD CONSTRAINT %I CHECK ("state" IN (''enabled'', ''disabled''))', t, t || '_state_check');
27
+ END IF;
28
+ END LOOP;
29
+ END $$;
30
+
31
+ -- The routes that read and set it, with their catalog rows: reading is
32
+ -- access:view, setting is access:edit, like the rest of the Access Matrix.
33
+ INSERT INTO "apis" (id, name, "apiGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
34
+ SELECT encode(gen_random_bytes(12), 'hex'), v.name, v.grp, false, true, '*', now(), now()
35
+ FROM (VALUES ('GET /auth/api/admin/module-states', 'access:view'),
36
+ ('POST /auth/api/admin/module-state', 'access:edit')) AS v(name, grp)
37
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" a WHERE a.name = v.name AND a."apiGroup" = v.grp);
38
+
39
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
40
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
41
+ FROM "roles" r CROSS JOIN "apis" a
42
+ WHERE r.name IN ('Super Admin', 'Admin')
43
+ AND a.name IN ('GET /auth/api/admin/module-states', 'POST /auth/api/admin/module-state')
44
+ 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'] },
@@ -37,7 +39,7 @@ class Api extends BaseModel {
37
39
  modelClass: Role,
38
40
  join: {
39
41
  from: 'apis.id',
40
- through: { from: 'apisRolesMapping.apiId', to: 'apisRolesMapping.roleId' },
42
+ through: { from: 'apisRolesMapping.apiId', to: 'apisRolesMapping.roleId', extra: ['state'] },
41
43
  to: 'roles.id'
42
44
  }
43
45
  }
@@ -20,6 +20,7 @@ class ApisRolesMapping extends BaseModel {
20
20
  recordCreatedBy: { type: ['string', 'null'], maxLength: 25 },
21
21
  recordModifiedBy: { type: ['string', 'null'], maxLength: 25 },
22
22
  isActive: { type: 'boolean' },
23
+ state: { type: 'string', enum: ['enabled', 'disabled'] },
23
24
  mtId1: { type: ['string', 'null'], maxLength: 25 },
24
25
  mtId2: { type: ['string', 'null'], maxLength: 25 },
25
26
  mtId3: { type: ['string', 'null'], maxLength: 25 },
@@ -20,6 +20,7 @@ class MenuRolesMapping extends BaseModel {
20
20
  recordCreatedBy: { type: ['string', 'null'], maxLength: 25 },
21
21
  recordModifiedBy: { type: ['string', 'null'], maxLength: 25 },
22
22
  isActive: { type: 'boolean' },
23
+ state: { type: 'string', enum: ['enabled', 'disabled'] },
23
24
  mtId1: { type: ['string', 'null'], maxLength: 25 },
24
25
  mtId2: { type: ['string', 'null'], maxLength: 25 },
25
26
  mtId3: { type: ['string', 'null'], maxLength: 25 },
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 },
@@ -59,7 +60,7 @@ class Role extends BaseModel {
59
60
  modelClass: Api,
60
61
  join: {
61
62
  from: 'roles.id',
62
- through: { from: 'apisRolesMapping.roleId', to: 'apisRolesMapping.apiId' },
63
+ through: { from: 'apisRolesMapping.roleId', to: 'apisRolesMapping.apiId', extra: ['state'] },
63
64
  to: 'apis.id'
64
65
  }
65
66
  },
@@ -68,7 +69,7 @@ class Role extends BaseModel {
68
69
  modelClass: UiPage,
69
70
  join: {
70
71
  from: 'roles.id',
71
- through: { from: 'uiPagesRolesMapping.roleId', to: 'uiPagesRolesMapping.uiPageId' },
72
+ through: { from: 'uiPagesRolesMapping.roleId', to: 'uiPagesRolesMapping.uiPageId', extra: ['state'] },
72
73
  to: 'uiPages.id'
73
74
  }
74
75
  },
@@ -77,7 +78,7 @@ class Role extends BaseModel {
77
78
  modelClass: UiElement,
78
79
  join: {
79
80
  from: 'roles.id',
80
- through: { from: 'uiElementsRolesMapping.roleId', to: 'uiElementsRolesMapping.uiElementId' },
81
+ through: { from: 'uiElementsRolesMapping.roleId', to: 'uiElementsRolesMapping.uiElementId', extra: ['state'] },
81
82
  to: 'uiElements.id'
82
83
  }
83
84
  },
@@ -86,7 +87,7 @@ class Role extends BaseModel {
86
87
  modelClass: Menu,
87
88
  join: {
88
89
  from: 'roles.id',
89
- through: { from: 'menuRolesMapping.roleId', to: 'menuRolesMapping.menuId' },
90
+ through: { from: 'menuRolesMapping.roleId', to: 'menuRolesMapping.menuId', extra: ['state'] },
90
91
  to: 'menus.id'
91
92
  }
92
93
  }
@@ -20,6 +20,7 @@ class UiElementsRolesMapping extends BaseModel {
20
20
  recordCreatedBy: { type: ['string', 'null'], maxLength: 25 },
21
21
  recordModifiedBy: { type: ['string', 'null'], maxLength: 25 },
22
22
  isActive: { type: 'boolean' },
23
+ state: { type: 'string', enum: ['enabled', 'disabled'] },
23
24
  mtId1: { type: ['string', 'null'], maxLength: 25 },
24
25
  mtId2: { type: ['string', 'null'], maxLength: 25 },
25
26
  mtId3: { type: ['string', 'null'], maxLength: 25 },
@@ -20,6 +20,7 @@ class UiPagesRolesMapping extends BaseModel {
20
20
  recordCreatedBy: { type: ['string', 'null'], maxLength: 25 },
21
21
  recordModifiedBy: { type: ['string', 'null'], maxLength: 25 },
22
22
  isActive: { type: 'boolean' },
23
+ state: { type: 'string', enum: ['enabled', 'disabled'] },
23
24
  mtId1: { type: ['string', 'null'], maxLength: 25 },
24
25
  mtId2: { type: ['string', 'null'], maxLength: 25 },
25
26
  mtId3: { 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.7",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [