@xeplr/auth 1.6.1 → 1.8.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
@@ -88,6 +88,7 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName }) //
88
88
  | `mtMembershipMiddleware(options)` | 403 when a tenant header names a value the caller has no membership for |
89
89
  | `authService` | `register`, `activate`, `invite`, `previewInvite`, `acceptInvite`, `login`, `forgotPassword`, `resetPassword`, profile, phone OTP, `changePassword`, `configureActivation`, `configureEmail` |
90
90
  | `signInSteps` | [other ways in](#other-ways-in-a-code-and-the-second-step): `settings`, `checkSettings`, `signInOptions`, `requestSignInCode`, `verifySignInCode`, `afterFirstStep`, `sendSecondStepCode`, `verifySecondStep`, `twoFactorStatus`, `startAuthenticator`, `confirmAuthenticator`, `chooseMethod`, `resetTwoFactor(userId, adminId)`, `cleanPhone`, `findByVerifiedPhone` |
91
+ | `catalogCheck` | `recordRoutes`, `listRoutes`, `buildCatalog`, `loadCatalog`, `findGaps` — [is every route in the catalog?](#is-every-route-in-the-catalog) |
91
92
  | `accessService` | `getUserAccess`, `userApiState`, `userHasApiAccess`, `apiStateFor`, `ACCESS_STATES`, `getApiRule`, `getPublicItems`, `clearUserAccess`, `clearAccessRules`, `clearAllAccess` |
92
93
  | `sessionService` | `createSession`, `getSession`, `validateAccessToken`, `slideAccessToken`, `rotateSession`, `destroySession`, `destroyAllUserSessions` |
93
94
  | `ticketService` | `issueTicket`, `consumeTicket` — single-use 30-second tickets for SSE / WebSocket |
@@ -256,6 +257,7 @@ Auth's own migrations:
256
257
  | `0012_default_role_access` | auth's own routes mapped to its default roles: `account:*` to every role, `users:*` `access:*` `settings:*` to Admin, system APIs to nobody but Super Admin |
257
258
  | `0013_mapping_state` | `state` (`enabled` / `disabled`) on the four role-mapping tables, default `enabled`; the `module-states` and `module-state` rows, mapped to Super Admin and Admin |
258
259
  | `0014_activation_routes` | rows for `resend-activation` (public) and `admin/users/:id/activate` (`users:edit` → Super Admin, Admin), plus three routes that shipped without one: `invite-preview` and `invite-accept` (public) and `sse-ticket` (`account:view` → every base role — before this it was open to anyone); the public `Resend Activation` and `Accept Invite` pages |
260
+ | `0016_catalog_complete` | rows for the `menu-items` routes (shipped without one; system scope, Super Admin), and Super Admin mapped to every system row — 0010's had no mapping at all, which meant open to anyone signed in |
259
261
 
260
262
  ## The first account
261
263
 
@@ -612,7 +614,24 @@ x-verify-tenant: {"l1":"<company>","l2":"<workspace>"} ← when the request
612
614
  | `403 { code: 'NOT_A_MEMBER' }` | token good, but no membership for a company or workspace in `x-verify-tenant` |
613
615
  | `400 { code: 'BAD_TENANT' }` | `x-verify-tenant` is not `{ "l1": "<id>", … }` of known levels: refused, never read past |
614
616
 
615
- **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.
617
+ ### Is every route in the catalog?
618
+
619
+ A route with no `apis` row is **open to anyone signed in**, and nothing reports it. So every app keeps a test that proves its catalog is complete, from the **real routers** and the **real migrations** — never a hand-kept list:
620
+
621
+ ```js
622
+ var check = require('@xeplr/auth').catalogCheck;
623
+ check.recordRoutes(require('express')); // BEFORE any router is built
624
+ var routes = check.listRoutes(buildApp()).routes; // [{ method, path }] — express 4 and 5
625
+ var catalog = await check.buildCatalog({ connectionName: 'auth', dirs: [ /* XEPLR_AUTH_MIGRATIONS dirs */ ] });
626
+ var gaps = check.findGaps({ routes, catalog, publicPaths: ['/public/'] });
627
+ // { notInCatalog, unmapped, superAdminOnly, noGroup } — all four must be empty
628
+ ```
629
+
630
+ `buildCatalog` applies this package's migrations and then `dirs` to a throwaway database on that (already resolved) connection, reads the catalog and drops it. `loadCatalog(knex)` reads an existing auth database instead. `findGaps` skips `publicPaths` (the gate never asks about them) and `isPublic` rows; `superAdminOnly` leaves out system-scope rows, which are Super Admin's alone by design. `listRoutes(app, { mapPath })` takes a `mapPath` for a router that rewrites `req.url`. A router built before `recordRoutes()` is listed under `unknown` rather than skipped.
631
+
632
+ **Planned for 2.0:** the gate refuses a route with no row (`NOT_IN_CATALOG`) or no role (`NOT_MAPPED`). It ships as a major version, once every app's test passes.
633
+
634
+ **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`. A last segment `*` covers one or more segments of any depth, for a route written as a pattern: `GET /factory/files/*` covers `GET /factory/files/a/b/c.png`. When several rows fit, more literal segments win, then a fixed length over `*`, then a row with a method over one without (`lib/apiMatch.js`). In a `catalogCheck` test, give such a route its row's name with `listRoutes(app, { mapPath })`. The catalog names are cached under `access:api:catalog`, cleared with the other rules.
616
635
 
617
636
  **Auth's own routes are checked the same way**, in-process: every signed-in route in `/auth/api` and every route in `/auth/api/admin` passes `accessGate()` (exported from `lib/accessMiddleware`) after the token check. Login, register, refresh and the other signed-out routes carry neither.
618
637
 
package/index.js CHANGED
@@ -487,6 +487,9 @@ module.exports = {
487
487
  // signInOptions(), resetTwoFactor(userId, adminId), cleanPhone() …
488
488
  signInSteps,
489
489
  accessService,
490
+ // Is every route in the catalog? For an app's own test (lib/catalogCheck.js):
491
+ // recordRoutes(express), listRoutes(app), buildCatalog(), findGaps().
492
+ catalogCheck: require('./lib/catalogCheck'),
490
493
  sessionService,
491
494
  ticketService,
492
495
  hooks,
package/lib/apiMatch.js CHANGED
@@ -3,11 +3,14 @@
3
3
  *
4
4
  * A row's name is "METHOD path" (that method only) or a bare path (every
5
5
  * method), and a path may hold `:params` — "GET /widget-templates/:id"
6
- * covers GET /widget-templates/abc. When several rows fit, the most exact
7
- * wins:
6
+ * covers GET /widget-templates/abc. A last segment `*` covers one or more
7
+ * segments of any depth — "GET /factory/files/*" covers
8
+ * GET /factory/files/a/b/c.png — for a route written as a pattern. When
9
+ * several rows fit, the most exact wins:
8
10
  *
9
11
  * 1. more literal segments /dashboards/:id/group beats /dashboards/:id/:x
10
- * 2. a method over none "POST /x" beats "/x"
12
+ * 2. a fixed length over `*` /files/:id beats /files/*
13
+ * 3. a method over none "POST /x" beats "/x"
11
14
  *
12
15
  * @param names every API name in the catalog
13
16
  * @param method 'GET', 'POST', …
@@ -27,7 +30,13 @@ function parse(name) {
27
30
  function fit(pattern, path) {
28
31
  var a = pattern.split('/');
29
32
  var b = path.split('/');
30
- if (a.length !== b.length) return -1;
33
+ var rest = a.length > 1 && a[a.length - 1] === '*';
34
+ if (rest) {
35
+ // `*` takes the remaining segments: at least one, none of them empty.
36
+ a = a.slice(0, -1);
37
+ if (b.length <= a.length || b.slice(a.length).some(function(x) { return x === ''; })) return -1;
38
+ b = b.slice(0, a.length);
39
+ } else if (a.length !== b.length) return -1;
31
40
  var literal = 0;
32
41
  for (var i = 0; i < a.length; i++) {
33
42
  if (a[i].charAt(0) === ':' && b[i] !== '') continue;
@@ -47,7 +56,7 @@ function matchApi(names, method, path) {
47
56
  if (row.method && row.method !== verb) return;
48
57
  var literal = fit(row.path, target);
49
58
  if (literal < 0) return;
50
- var score = literal * 2 + (row.method ? 1 : 0);
59
+ var score = literal * 4 + (/\/\*$/.test(row.path) ? 0 : 2) + (row.method ? 1 : 0);
51
60
  if (score > bestScore) { best = name; bestScore = score; }
52
61
  });
53
62
  return best;
@@ -0,0 +1,214 @@
1
+ /**
2
+ * IS EVERY ROUTE IN THE CATALOG? — for an app's own test.
3
+ *
4
+ * The gate refuses a request that matches no `apis` row, or a row no role is
5
+ * mapped to (NOT_IN_CATALOG / NOT_MAPPED). So a route added without its
6
+ * migration row works for nobody — and nobody finds out until a screen stops.
7
+ * This lets an app's test find that first, from the REAL routers and the
8
+ * REAL migrations, never from a hand-kept list:
9
+ *
10
+ * var check = require('@xeplr/auth').catalogCheck;
11
+ * check.recordRoutes(require('express')); // BEFORE any router is built
12
+ * var app = buildTheApp();
13
+ * var routes = check.listRoutes(app); // [{ method, path }]
14
+ * var catalog = await check.buildCatalog({ connectionName: 'auth', dirs: [...] });
15
+ * var gaps = check.findGaps({ routes, catalog, publicPaths: ['/public/'] });
16
+ * // gaps.notInCatalog, gaps.unmapped, gaps.superAdminOnly, gaps.noGroup
17
+ *
18
+ * Express 4 and 5 both: a router's layers keep no path string, so
19
+ * recordRoutes() wraps Router `use()` / `route()` to note the path each layer
20
+ * was mounted with. Routers built before it are invisible — listRoutes()
21
+ * reports their layers under `unknown` rather than skipping them silently.
22
+ */
23
+ var { matchApi } = require('./apiMatch');
24
+
25
+ var SUPER_ADMIN = 'Super Admin';
26
+ var METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
27
+
28
+ function pathsOf(args) {
29
+ var first = args[0];
30
+ var probe = first;
31
+ while (Array.isArray(probe) && probe.length) probe = probe[0];
32
+ if (typeof probe === 'function' || probe === undefined) return ['/'];
33
+ return Array.isArray(first) ? first : [first];
34
+ }
35
+
36
+ /** Wrap Router use()/route() of this express so every layer notes its path. Idempotent. */
37
+ function recordRoutes(express) {
38
+ // The object that OWNS use(): express 5's Router() is a function whose
39
+ // prototype is a Router instance, express 4's one whose prototype is proto.
40
+ var proto = Object.getPrototypeOf(express.Router());
41
+ while (proto && !Object.prototype.hasOwnProperty.call(proto, 'use')) proto = Object.getPrototypeOf(proto);
42
+ if (proto.__catalogCheck) return;
43
+ var use = proto.use;
44
+ var route = proto.route;
45
+ proto.use = function() {
46
+ var before = this.stack.length;
47
+ var paths = pathsOf(arguments);
48
+ var out = use.apply(this, arguments);
49
+ for (var i = before; i < this.stack.length; i++) this.stack[i].__paths = paths;
50
+ return out;
51
+ };
52
+ proto.route = function(path) {
53
+ var out = route.apply(this, arguments);
54
+ this.stack[this.stack.length - 1].__paths = Array.isArray(path) ? path : [path];
55
+ return out;
56
+ };
57
+ Object.defineProperty(proto, '__catalogCheck', { value: true });
58
+ }
59
+
60
+ function join(prefix, path) {
61
+ var p = typeof path === 'string' ? path : String(path);
62
+ var joined = (prefix.replace(/\/+$/, '') + '/' + p.replace(/^\/+/, '')).replace(/\/+$/, '');
63
+ return joined || '/';
64
+ }
65
+
66
+ function stackOf(handle) {
67
+ if (!handle) return null;
68
+ if (Array.isArray(handle.stack)) return handle.stack;
69
+ return null;
70
+ }
71
+
72
+ /**
73
+ * Every method + path an app (or router) answers.
74
+ * @param appOrRouter an express app (4 or 5) or a Router
75
+ * @param [opts.mapPath] (path) → the path the gate sees, for a router that rewrites req.url
76
+ * @returns { routes: [{ method, path }], unknown: [string] }
77
+ */
78
+ function listRoutes(appOrRouter, opts) {
79
+ opts = opts || {};
80
+ var mapPath = opts.mapPath || function(p) { return p; };
81
+ var root = appOrRouter.router || appOrRouter._router || appOrRouter;
82
+ var routes = [];
83
+ var unknown = [];
84
+ var seen = new Set();
85
+ function walk(stack, prefix) {
86
+ stack.forEach(function(layer) {
87
+ var paths = layer.__paths;
88
+ if (!paths) {
89
+ // A layer we did not see mounted: only interesting if it holds routes.
90
+ if (layer.route || stackOf(layer.handle)) unknown.push(prefix + ' (' + (layer.name || 'layer') + ')');
91
+ return;
92
+ }
93
+ paths.forEach(function(p) {
94
+ var full = join(prefix, p);
95
+ if (layer.route) {
96
+ var methods = Object.keys(layer.route.methods || {}).filter(function(m) { return layer.route.methods[m]; });
97
+ methods.forEach(function(m) {
98
+ var method = m === '_all' ? 'ALL' : m.toUpperCase();
99
+ if (method === 'HEAD' || method === 'OPTIONS') return;
100
+ var path = mapPath(full);
101
+ var key = method + ' ' + path;
102
+ if (seen.has(key)) return;
103
+ seen.add(key);
104
+ routes.push({ method: method, path: path });
105
+ });
106
+ return;
107
+ }
108
+ var inner = stackOf(layer.handle);
109
+ if (inner) walk(inner, full);
110
+ });
111
+ });
112
+ }
113
+ walk(root.stack || [], '');
114
+ return { routes: routes, unknown: unknown };
115
+ }
116
+
117
+ /**
118
+ * The catalog as rows: { name, group, isPublic, scope, roles: [names] }.
119
+ * @param knex a knex on an auth database
120
+ */
121
+ async function loadCatalog(knex) {
122
+ var hasScope = await knex.schema.hasColumn('apis', 'scope');
123
+ var rows = (await knex.raw(
124
+ 'SELECT a.name, a."apiGroup" AS "group", a."isPublic" AS "isPublic", ' + (hasScope ? 'a.scope' : 'NULL AS scope') + ', ' +
125
+ ' array_remove(array_agg(r.name), NULL) AS roles ' +
126
+ 'FROM apis a ' +
127
+ 'LEFT JOIN "apisRolesMapping" m ON m."apiId" = a.id AND m."isActive" IS NOT FALSE ' +
128
+ 'LEFT JOIN roles r ON r.id = m."roleId" ' +
129
+ 'GROUP BY a.id ORDER BY a.name'
130
+ )).rows;
131
+ return rows.map(function(r) {
132
+ return { name: r.name, group: r.group, isPublic: !!r.isPublic, scope: r.scope || null, roles: r.roles || [] };
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Build the catalog a set of migration directories makes: a temporary
138
+ * database on that connection, every directory applied in order (the auth
139
+ * package's own `migrations/` first unless `dirs` says otherwise), read, dropped.
140
+ * `${VAR}` placeholders read process.env, as on a real install.
141
+ *
142
+ * @param opts.connectionName a connection already resolved with @xeplr/db resolveConfig()
143
+ * @param [opts.dirs] extension directories (an app's migrations-auth/, packages' ones)
144
+ */
145
+ async function buildCatalog(opts) {
146
+ var path = require('node:path');
147
+ var knexLib = require('knex');
148
+ var db = require('@xeplr/db');
149
+ var cfg = await db.resolveConfig(opts.connectionName);
150
+ var name = 'xeplr_catalog_check_' + process.pid + '_' + Date.now();
151
+ var conn = { host: cfg.host, port: cfg.port, user: cfg.user, password: cfg.password, ssl: cfg.ssl };
152
+ var admin = knexLib({ client: 'pg', connection: Object.assign({}, conn, { database: 'postgres' }), pool: { min: 0, max: 1 } });
153
+ try {
154
+ await admin.raw('CREATE DATABASE ??', [name]);
155
+ try {
156
+ await db.sqlMigrator.up({
157
+ db: name,
158
+ dir: path.join(__dirname, '..', 'migrations'),
159
+ extDir: (opts.dirs || []).join(','),
160
+ connectionName: opts.connectionName
161
+ });
162
+ var knex = knexLib({ client: 'pg', connection: Object.assign({}, conn, { database: name }), pool: { min: 0, max: 1 } });
163
+ try { return await loadCatalog(knex); } finally { await knex.destroy(); }
164
+ } finally {
165
+ await admin.raw('DROP DATABASE IF EXISTS ?? WITH (FORCE)', [name]);
166
+ }
167
+ } finally {
168
+ await admin.destroy();
169
+ }
170
+ }
171
+
172
+ /**
173
+ * What the gate would refuse to everyone who should reach it.
174
+ *
175
+ * notInCatalog a route no `apis` row matches — refused to everyone (NOT_IN_CATALOG)
176
+ * unmapped matched, but no role mapped — refused to everyone (NOT_MAPPED)
177
+ * superAdminOnly matched, mapped to Super Admin alone, and not a system API
178
+ * noGroup matched, non-public row without an apiGroup
179
+ *
180
+ * Public paths (the app's createApp `publicPaths`, never sent to the gate)
181
+ * and `isPublic` rows are open by design and not reported.
182
+ *
183
+ * @param opts.routes from listRoutes()
184
+ * @param opts.catalog from loadCatalog() / buildCatalog()
185
+ * @param [opts.publicPaths] prefixes the app's gate skips
186
+ * @param [opts.ignore] (route) → true for a route this app deliberately leaves out (say why at the call)
187
+ */
188
+ function findGaps(opts) {
189
+ var publicPaths = opts.publicPaths || [];
190
+ var byName = new Map();
191
+ (opts.catalog || []).forEach(function(row) { byName.set(row.name, row); });
192
+ var names = Array.from(byName.keys());
193
+ var gaps = { notInCatalog: [], unmapped: [], superAdminOnly: [], noGroup: [] };
194
+ (opts.routes || []).forEach(function(route) {
195
+ if (publicPaths.some(function(p) { return route.path === p || route.path.indexOf(p) === 0; })) return;
196
+ if (opts.ignore && opts.ignore(route)) return;
197
+ var methods = route.method === 'ALL' ? METHODS : [route.method];
198
+ methods.forEach(function(method) {
199
+ var label = method + ' ' + route.path;
200
+ var api = matchApi(names, method, route.path);
201
+ if (!api) { gaps.notInCatalog.push(label); return; }
202
+ var row = byName.get(api);
203
+ if (row.isPublic) return;
204
+ if (!row.group) gaps.noGroup.push(label + ' → ' + api);
205
+ if (!row.roles.length) { gaps.unmapped.push(label + ' → ' + api); return; }
206
+ if (row.scope === 'system') return;
207
+ if (!row.roles.some(function(r) { return r !== SUPER_ADMIN; })) gaps.superAdminOnly.push(label + ' → ' + api + ' (' + (row.group || 'no group') + ')');
208
+ });
209
+ });
210
+ Object.keys(gaps).forEach(function(k) { gaps[k] = Array.from(new Set(gaps[k])).sort(); });
211
+ return gaps;
212
+ }
213
+
214
+ module.exports = { recordRoutes: recordRoutes, listRoutes: listRoutes, loadCatalog: loadCatalog, buildCatalog: buildCatalog, findGaps: findGaps, SUPER_ADMIN: SUPER_ADMIN };
@@ -0,0 +1,30 @@
1
+ -- 0016_catalog_complete.sql
2
+ -- Every auth route has a row, and every row a role — before the gate starts
3
+ -- refusing what has neither (NOT_IN_CATALOG / NOT_MAPPED). Found by
4
+ -- test/catalogComplete.test.js, which lists the real routers.
5
+ --
6
+ -- /auth/api/admin/menu-items (GET, POST, add, remove)
7
+ -- shipped with no row: open to anyone signed in at the gate, held back
8
+ -- only by requireSuperAdmin in the route. System scope, Super Admin only.
9
+ --
10
+ -- The system rows from 0010 (POST master/roles, master/roles/copy,
11
+ -- master/apis/scope) were mapped to NO role, which used to mean "open":
12
+ -- Super Admin reached them only through that. Mapped to Super Admin now,
13
+ -- and every other system row the same way, so a closed gate keeps them his.
14
+
15
+ INSERT INTO "apis" (id, name, "apiGroup", "scope", "scopeLocked", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
16
+ SELECT encode(gen_random_bytes(12), 'hex'), v.name, v.grp, 'system', true, false, true, '*', now(), now()
17
+ FROM (VALUES
18
+ ('GET /auth/api/admin/menu-items', 'menus:view'),
19
+ ('POST /auth/api/admin/menu-items', 'menus:edit'),
20
+ ('POST /auth/api/admin/menu-items/add', 'menus:edit'),
21
+ ('POST /auth/api/admin/menu-items/remove', 'menus:edit')
22
+ ) AS v(name, grp)
23
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" a WHERE a.name = v.name AND a."apiGroup" = v.grp);
24
+
25
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
26
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
27
+ FROM "roles" r CROSS JOIN "apis" a
28
+ WHERE r.name = 'Super Admin'
29
+ AND a.scope = 'system'
30
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.6.1",
3
+ "version": "1.8.0",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -44,6 +44,7 @@
44
44
  "bcrypt": "^6.0.0",
45
45
  "ioredis": "^5.6.1",
46
46
  "jsonwebtoken": "^9.0.3",
47
+ "knex": "^3.3.0",
47
48
  "multer": "^2.3.0"
48
49
  },
49
50
  "peerDependencies": {