@xeplr/auth 1.5.2 → 1.5.3

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
@@ -78,10 +78,11 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName }) //
78
78
  | `boot()` | the standalone service, env-driven, as above; resolves to the `http.Server` |
79
79
  | `start(config)` | `init(config)` + Express on `config.port` with both routers; no Redis check, no migrations, no banner |
80
80
  | `init(config)` | connect and bind the models, configure JWT and email; checks `REDIS_PREFIX` |
81
- | `attach()` | secondary connection to the auth database from another process: `{ ready, conn, model(name), service }` |
81
+ | `attach()` | secondary connection to the auth database from another process: `{ ready, conn, model(name), service, internalTokenFor(userId, { ttl }) }` |
82
+ | `createInternalToken(user, { ttl })` | an [internal token](#internal-tokens): the server calling its own API as `user` (`{ id, email, name, roles }`) |
82
83
  | `router(options)` | the `/auth/api` router; `options.resetBaseUrl` sets where reset links point |
83
84
  | `adminRouter()` | the `/auth/api/admin` router |
84
- | `authMiddleware` | Bearer token check against the Redis session; sets `req.user`; slides within tolerance |
85
+ | `authMiddleware` | Bearer token check against the Redis session; sets `req.user`; slides within tolerance. An [internal token](#internal-tokens) is served as the user it acts as |
85
86
  | `accessMiddleware(options)` | per-API RBAC from the `apis` catalog — see [Access checks](#access-checks) |
86
87
  | `requireRole(...names)` | 403 unless `req.user.roles` holds one of the names; use after `authMiddleware` |
87
88
  | `mtMembershipMiddleware(options)` | 403 when a tenant header names a value the caller has no membership for |
@@ -284,6 +285,26 @@ Access-Control-Expose-Headers: X-New-Token
284
285
 
285
286
  Client code must read the header and replace its stored token, or the session ends when the grace runs out. Concurrent requests carrying the same expiring token all get the **same** new token. A slid token copies its roles from the old one; roles are re-read on `/refresh` or the next login. A revoked session is never graced.
286
287
 
288
+ ## Internal tokens
289
+
290
+ A token the **server makes for itself**, to call its own API — or another xeplr service — as a user: a scheduled export, a dashboard print, a job step. **A library call, never a route**, so nothing outside the server can make one:
291
+
292
+ ```js
293
+ const auth = require('@xeplr/auth').attach();
294
+ const token = await auth.internalTokenFor(userId); // reads the user and their roles
295
+ // or, with the claims already at hand:
296
+ const token = await require('@xeplr/auth').createInternalToken({ id, email, name, roles });
297
+
298
+ await fetch(api + '/reports/r1/export', { method: 'POST', headers: {
299
+ authorization: 'Bearer ' + token, 'x-company-id': company, 'x-workspace-id': workspace, … } });
300
+ ```
301
+
302
+ - **A long random string** (`xit_` + 32 random bytes), kept in Redis under `REDIS_PREFIX` with the user it acts as, **for 30 seconds** (`ttl`: 1 to 300). Not a short code: it works on the API, so it must not be guessable within its life.
303
+ - **`authMiddleware` knows it by its prefix** and serves the request as that user. So `/verify`, every app's gate, the company membership and the API access rules apply exactly as to a sign-in token: it opens nothing that user could not open. **No code in the app** — the app's gate already asks auth.
304
+ - **Usable for its whole life, not once**: an export is started, waited on and fetched with one token.
305
+ - `internalTokenFor(userId)` refuses a user who is inactive or never activated: a deactivated person's scheduled work does not go on running as them.
306
+ - The server making it and the auth service reading it must share the Redis and `REDIS_PREFIX` — as they already do for sessions.
307
+
287
308
  ## Routes
288
309
 
289
310
  ### Sign-up and activation
@@ -650,6 +671,8 @@ npm test # node --test test/*.test.js
650
671
 
651
672
  `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`.
652
673
 
674
+ `test/internalToken.test.js` (local Redis): a token the server made is served as its user, for its whole life; one nobody made is refused; it ends when its time is up; 30 seconds unless asked, never more than 5 minutes; a sign-in token is checked as before.
675
+
653
676
  `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.
654
677
 
655
678
  ## License
package/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ const internalToken = require('./lib/internalToken');
1
2
  const path = require('path');
2
3
  const { getConnection, bindModels, resolveConfig, sqlMigrator, resolveDbConnection, describeDbConnection, migrationsFor, migrationsVar } = require('@xeplr/db');
3
4
 
@@ -347,7 +348,17 @@ function attach() {
347
348
  if (!M) throw new Error('auth.attach(): unknown auth model "' + name + '"');
348
349
  return M.bindKnex(conn());
349
350
  }
350
- return { ready: function () { return _ready; }, conn: conn, model: model, service: authService };
351
+ // A token the server makes for itself, acting as this user (by id): read
352
+ // with their roles, refused if they are inactive or never activated — a
353
+ // deactivated person's scheduled export must not go on running as them.
354
+ async function internalTokenFor(userId, opts) {
355
+ await _ready;
356
+ var user = await model('User').query().findById(userId).withGraphFetched('roles');
357
+ if (!user || !user.isActive || !user.isActivated) throw new Error('internalTokenFor: no active user "' + userId + '"');
358
+ return internalToken.createInternalToken({ id: user.id, email: user.email, name: user.name, roles: user.roles || [] }, opts);
359
+ }
360
+
361
+ return { ready: function () { return _ready; }, conn: conn, model: model, service: authService, internalTokenFor: internalTokenFor };
351
362
  }
352
363
 
353
364
  // Env vars this library needs — apps spread this into their env.required.js so
@@ -428,6 +439,9 @@ Object.defineProperty(requiredEnv, 'activationLinkVar', {
428
439
  // different question from the SERVER, and services do not share one.
429
440
 
430
441
  module.exports = {
442
+ // A token the server makes for itself (lib/internalToken.js): a library
443
+ // call, never a route. attach().internalTokenFor(userId) reads the user.
444
+ createInternalToken: internalToken.createInternalToken,
431
445
  // Hand in @xeplr-workflow/api's resumeByKey to release a step that is
432
446
  // waiting for someone to activate. Omitted, activation just activates.
433
447
  configureWorkflowResume: authService.configureWorkflowResume,
@@ -1,6 +1,7 @@
1
1
  const { decodeVerified, getToleranceSeconds } = require('./authHelper');
2
2
  const { validateAccessToken, slideAccessToken } = require('./sessionService');
3
3
  const { decide } = require('./tokenDecision');
4
+ const { isInternalToken, readInternalToken } = require('./internalToken');
4
5
 
5
6
  // The ONE place token logic lives. Order (from tokenDecision): signature →
6
7
  // revocation → expiry. Tolerance (ACCESS_TOKEN_TOLERANCE_SECONDS, default 0)
@@ -15,6 +16,16 @@ async function authMiddleware(req, res, next) {
15
16
  }
16
17
  const token = authHeader.split(' ')[1];
17
18
 
19
+ // AN INTERNAL TOKEN — made by the server for itself (lib/internalToken.js):
20
+ // served as the user it acts as while it lives in Redis. Everything after
21
+ // this (membership, the API's access) checks that user as usual.
22
+ if (isInternalToken(token)) {
23
+ const claims = await readInternalToken(token).catch(function() { return null; });
24
+ if (!claims) return res.status(401).json({ error: 'Invalid or expired token' });
25
+ req.user = claims;
26
+ return next();
27
+ }
28
+
18
29
  // Verify signature, ignore expiry (we decide on expiry ourselves).
19
30
  const { decoded, signatureValid } = decodeVerified(token);
20
31
 
@@ -0,0 +1,66 @@
1
+ /**
2
+ * internalToken — a token the SERVER makes for itself, to call its own API
3
+ * (or another xeplr service) as a user: a scheduled export, a print, a job
4
+ * step. A library function, never a route — nothing outside the server can
5
+ * make one.
6
+ *
7
+ * const token = await createInternalToken({ id, email, name, roles })
8
+ * fetch(api + '/reports/r1/export', { headers: { authorization: 'Bearer ' + token, … } })
9
+ *
10
+ * A random string (`xit_` + 32 random bytes) kept in Redis with the user it
11
+ * acts as, for 30 seconds unless asked otherwise. authMiddleware knows it by
12
+ * its prefix and serves the request as that user — so /verify, every app's
13
+ * gate, the company membership and the API access rules apply to it exactly
14
+ * as to a sign-in token: it opens nothing that user could not open.
15
+ *
16
+ * Long and random, not a short code: it works on the API, so it must not be
17
+ * guessable within its life. Not single-use: an export is started, waited on
18
+ * and fetched with one token, within its 30 seconds.
19
+ *
20
+ * Keys go through @xeplr/utils' cache, under REDIS_PREFIX — the same Redis
21
+ * and prefix the auth service reads, as for sessions.
22
+ */
23
+ const crypto = require('crypto');
24
+ const { cache } = require('@xeplr/utils');
25
+
26
+ const KEY = 'token:internal:';
27
+ const PREFIX = 'xit_';
28
+ const DEFAULT_TTL = 30; // seconds
29
+ const MAX_TTL = 300;
30
+
31
+ /** Whether a bearer token is an internal one (by its prefix). */
32
+ function isInternalToken(token) {
33
+ return typeof token === 'string' && token.startsWith(PREFIX);
34
+ }
35
+
36
+ /**
37
+ * Make a token acting as `user` ({ id, email, name, roles: [names] } — the
38
+ * claims a sign-in carries). Throws if Redis is unreachable: an auth surface
39
+ * fails loud.
40
+ *
41
+ * @param {object} user
42
+ * @param {object} [opts] { ttl } seconds, 1–300 (default 30)
43
+ * @returns {Promise<string>}
44
+ */
45
+ async function createInternalToken(user, opts) {
46
+ if (!user || !user.id) throw new Error('createInternalToken: user.id is required');
47
+ const ttl = Math.min(MAX_TTL, Math.max(1, Math.floor(Number((opts && opts.ttl) || DEFAULT_TTL))));
48
+ const token = PREFIX + crypto.randomBytes(32).toString('base64url');
49
+ const claims = {
50
+ id: user.id, email: user.email || null, name: user.name || null,
51
+ roles: Array.isArray(user.roles) ? user.roles.map(function(r) { return typeof r === 'string' ? r : r && r.name; }).filter(Boolean) : [],
52
+ internal: true
53
+ };
54
+ await cache.getClient().set(KEY + token, JSON.stringify(claims), 'EX', ttl);
55
+ return token;
56
+ }
57
+
58
+ /** The user an internal token acts as, or null (unknown, or its time is up). */
59
+ async function readInternalToken(token) {
60
+ if (!isInternalToken(token)) return null;
61
+ const raw = await cache.getClient().get(KEY + token);
62
+ if (!raw) return null;
63
+ try { return JSON.parse(raw); } catch (_) { return null; }
64
+ }
65
+
66
+ module.exports = { createInternalToken, readInternalToken, isInternalToken, DEFAULT_TTL };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.5.2",
3
+ "version": "1.5.3",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [