@xeplr/auth 1.1.4 → 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/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.4",
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": [