@xeplr/auth 1.1.8 → 1.3.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
@@ -91,6 +91,7 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName })
91
91
  | `ticketService` | `issueTicket`, `consumeTicket` — single-use 30-second tickets for SSE / WebSocket |
92
92
  | `authHelper` | `configure`, `hashPassword`, `comparePassword`, `generateAccessToken`, `verifyToken`, `decodeVerified`, `generateId`, … |
93
93
  | `hooks` | `on(identifier, event, fn)`, `fire`, `setHooksEnabled` |
94
+ | `licence` | `use({ modulesFor })`: which sold modules a user may use — see [Licensed modules](#licensed-modules) |
94
95
  | `seedSuperAdmin(knex, { email, password, name? })` | insert-if-absent super admin user + role mapping, for apps seeding from JS |
95
96
  | `configureWorkflowResume(fn)` | hand in `@xeplr-workflow/api`'s `resumeByKey`; activation with a `workflowKey` then resumes that workflow (best-effort) |
96
97
  | `requiredEnv` | the env names this package needs, for an app's `env.required.js`; `requiredEnv.activationLinkVar` names the activation-link variable in use |
@@ -100,7 +101,7 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName })
100
101
 
101
102
  ### Required
102
103
 
103
- Everything in `requiredEnv`, plus a connection and an activation link.
104
+ Everything in `requiredEnv`, plus a connection. `requiredEnv` includes the sign-up settings — `AUTH_REGISTER_ROLES`, `AUTH_ACTIVATION_URL` and `AUTH_RESET_URL` — so an app that spreads it into its `env.required.js` refuses to start (and `check-env` fails) without them: the sign-in service would run, but nobody new could get in. The two link settings are asked for as `AUTH_ACTIVATION_BASE_URL` instead when an install uses that older form. Started without them anyway, each flow refuses with `503` naming the variable, and the banner shows `✗ NOT SET`.
104
105
 
105
106
  | variable | default in code | meaning |
106
107
  |---|---|---|
@@ -114,14 +115,17 @@ Everything in `requiredEnv`, plus a connection and an activation link.
114
115
  | `AUTH_SUPER_ADMIN_PASSWORD` | — | its password; no quotes, spaces, `$` or `#` (substituted into SQL) |
115
116
  | `XEPLR_AUTH_MIGRATIONS` | none | comma-separated app migration directories, run after auth's own — [details](#migrations) |
116
117
  | `AUTH_TENANT_HEADER` | — | the header that names the company a role is created in (e.g. `x-company-id`), or `none` for a single-tenant app. No default: a multi-tenant app that forgot it would make every role visible to every company — [details](#roles-belong-to-a-company) |
117
- | `AUTH_ACTIVATION_URL` | — | full address of your activation page, e.g. `http://localhost:19100/auth/activate`; `?token=…` is appended. The older `AUTH_ACTIVATION_BASE_URL` (below) also satisfies it — `requiredEnv.activationLinkVar` names whichever the install uses. The service starts without it, but registration fails |
118
+ | `AUTH_ACTIVATION_URL` | — | full address of your activation page, e.g. `http://localhost:19100/auth/activate`; `?token=…` is appended. The older `AUTH_ACTIVATION_BASE_URL` (below) also satisfies it — `requiredEnv.activationLinkVar` names whichever the install uses. Without it registration and resend-activation are refused |
119
+ | `AUTH_REGISTER_ROLES` | — (refused) | the role(s) a self-registered account gets when it is activated, comma-separated, e.g. `Viewer`. **No default, on purpose:** an account with no role has every role-mapped API hidden — its own profile included — so it can sign in and do nothing. Which role fits is each app's decision. Unset, a name that is not a generic (`mtId1 = '*'`) role, or a system role (Super Admin) → registration is refused |
120
+ | `AUTH_RESET_URL` | — (refused) | full address of your reset-password page, e.g. `http://localhost:19100/auth/reset-password`; `?token=…` is appended. Derived from `AUTH_ACTIVATION_BASE_URL` when only that is set. **Never taken from the request:** a link built from the `Host` header lets anyone have us mail a real user a reset link to their own site. Unset → forgot-password is refused |
121
+ | email (`EMAIL_PROVIDER` + its settings, below) | — | registration, resend-activation, invites and password reset all send a link. `boot()` checks mail at startup; when it is known not to work those routes refuse up front (`503`, `EMAIL_NOT_SET_UP`) rather than create an account whose link never goes out |
118
122
 
119
123
  ### Optional
120
124
 
121
125
  | variable | default | meaning |
122
126
  |---|---|---|
123
127
  | `AUTH_INVITE_URL` | derived | full address of your accept-invite page; `?token=…` is appended |
124
- | `AUTH_ACTIVATION_BASE_URL` | — | older form: an origin; `/auth/activate` and `/auth/accept-invite` are appended when the two URLs above are unset |
128
+ | `AUTH_ACTIVATION_BASE_URL` | — | older form: an origin; `/auth/activate`, `/auth/accept-invite` and `/auth/reset-password` are appended when the URLs above are unset |
125
129
  | `AUTH_ACCESS_TOKEN_TTL_MINUTES` | `15` | access token lifetime |
126
130
  | `AUTH_REFRESH_TOKEN_TTL_DAYS` | `7` | refresh token (session) lifetime |
127
131
  | `AUTH_ACCESS_TOKEN_TOLERANCE_SECONDS` | `0` | grace after expiry during which a token is still served and slid; `0` turns sliding refresh off |
@@ -245,6 +249,7 @@ Auth's own migrations:
245
249
  | `0011_verify_api` | the `GET /auth/api/verify` row, public in the catalog |
246
250
  | `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 |
247
251
  | `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 |
252
+ | `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 |
248
253
 
249
254
  ## The first account
250
255
 
@@ -281,19 +286,27 @@ Client code must read the header and replace its stored token, or the session en
281
286
 
282
287
  ## Routes
283
288
 
289
+ ### Sign-up and activation
290
+
291
+ 1. **Register** — every check that can refuse runs *before* the account is written, and the activation mail is sent inside the same transaction, so a refusal or a failed send leaves nothing behind.
292
+ 2. **Activate** — by the emailed link, or by an admin (`POST /admin/users/:id/activate`). Both grant the `AUTH_REGISTER_ROLES` roles in the same transaction, so an activated account always has a role.
293
+ 3. **Lost the mail?** `POST /resend-activation` sends a new link.
294
+ 4. **Invited people** set their password on the accept-invite page (`/invite-preview`, `/invite-accept`); they get whatever roles the inviter grants, not the sign-up roles.
295
+
284
296
  ### `/auth/api`
285
297
 
286
298
  | route | token | body / query → response |
287
299
  |---|---|---|
288
- | `POST /register` | — | `{ email, password, name?, phoneNumber? }` → `201 { message, user }`; `409` if the email is registered. Sends the activation email |
289
- | `GET /activate` | — | `?token=…&workflowKey=…` → `{ message, user }` |
300
+ | `POST /register` | — | `{ email, password, name?, phoneNumber? }` → `201 { message, user }`; `409` if the email is registered. Sends the activation email. `503 { error, code }` when a sign-up setting is missing or the mail cannot be sent — in every such case **no account is created**, so trying again works |
301
+ | `POST /resend-activation` | — | `{ email }` → the same message whether or not the address has an account waiting; sends a new link and the old one stops working. Invited accounts are skipped (they use their invite link) |
302
+ | `GET /activate` | — | `?token=…&workflowKey=…` → `{ message, user }`; grants the `AUTH_REGISTER_ROLES` roles. An invite token is refused here (it would leave an account with no password) |
290
303
  | `GET /invite-preview` | — | `?token=…` → `{ email, name }` |
291
304
  | `POST /invite-accept` | — | `{ token, password, name? }` → sets the password and activates |
292
- | `POST /login` | — | `{ email, password }` → `{ accessToken, refreshToken, user, access }`; `401` wrong password or deactivated; `403` not yet activated |
305
+ | `POST /login` | — | `{ email, password }` → `{ accessToken, refreshToken, user, access }`; `401` wrong password or deactivated (an invited account with no password yet is a wrong password); `403 { error, code: 'NOT_ACTIVATED' }` not yet activated — check `code`, not the wording |
293
306
  | `POST /refresh` | — | `{ refreshToken }` → a new `{ accessToken, refreshToken, user, access }` |
294
307
  | `POST /logout` | — | `{ refreshToken }` → ends that session |
295
- | `POST /forgot-password` | — | `{ email }` → the same message whether or not the address exists; emails `<resetBaseUrl>/auth/reset-password?token=…` (the request's own origin when no `resetBaseUrl` is given — `boot()` gives none) |
296
- | `POST /reset-password` | — | `{ token, newPassword }` |
308
+ | `POST /forgot-password` | — | `{ email }` → the same message whether or not the address exists; emails `AUTH_RESET_URL?token=…` (or `<resetBaseUrl>/auth/reset-password` when the router is given `resetBaseUrl`). `503` for every address alike when the reset address or mail is not set up |
309
+ | `POST /reset-password` | — | `{ token, newPassword }`; `400` once the link is older than `AUTH_RESET_TOKEN_EXPIRY_MINUTES` |
297
310
  | `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims |
298
311
  | `GET /verify` | ✓ | the check every app's gate makes on every request — see [Every request is checked](#every-request-is-checked) |
299
312
  | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
@@ -309,7 +322,8 @@ Client code must read the header and replace its stored token, or the session en
309
322
 
310
323
  | route | |
311
324
  |---|---|
312
- | `GET /users` | users with their roles |
325
+ | `GET /users` | users with their roles, `isActivated`, and `invitePending` (invited, no password set yet — they activate by accepting the invite) |
326
+ | `POST /users/:id/activate` | `users:edit` — activates an account without its emailed link and grants the `AUTH_REGISTER_ROLES` roles; `409` if already activated or invited without a password yet |
313
327
  | `GET /roles` | `[{ id, name, scope, mtId1 }]`: the current company's roles and the generic ones; system roles only for Super Admin |
314
328
  | `GET /access-items` | `{ apis, pages, elements, menus }`, each with its roles |
315
329
  | `POST /user-role` | `{ userId, roleId, assign }` — grant or remove a role |
@@ -465,13 +479,14 @@ Pass `apiNameResolver(req)` to name APIs differently. Because unregistered means
465
479
 
466
480
  ### Access states
467
481
 
468
- The gate answers one of three states, not true/false. Only `enabled` goes through:
482
+ The gate answers one of four states, not true/false. Only `enabled` goes through:
469
483
 
470
484
  | state | means | `accessMiddleware` |
471
485
  |---|---|---|
472
486
  | `enabled` | shown and usable | passes |
473
487
  | `disabled` | shown, greyed out, not usable | `403 { code: 'DISABLED' }` |
474
488
  | `hidden` | not shown | `403 { code: 'HIDDEN' }` |
489
+ | `unlicensed` | not shown: the API's module is not in the user's licence | `403 { code: 'UNLICENSED' }` |
475
490
 
476
491
  Anything else is refused as well: a state the gate does not know never lets a request through.
477
492
 
@@ -513,6 +528,7 @@ x-verify-path: /widget-templates/abc
513
528
  |---|---|
514
529
  | `200 { user, access, state: 'enabled', api }` | token good, API allowed. `api` is the catalog row it matched, or `null` (not registered, so open) |
515
530
  | `403 { code: 'DISABLED' }` · `403 { code: 'HIDDEN' }` | token good, API not allowed |
531
+ | `403 { code: 'UNLICENSED' }` | token good, but the API belongs to a module the user's licence does not include |
516
532
  | `401` | bad or expired token (the same tolerance and `X-New-Token` sliding as every route) |
517
533
  | `400 { code: 'NO_REQUEST' }` | no method or path named: nothing to check, so refused |
518
534
 
@@ -533,6 +549,30 @@ These are migration defaults; the Access Matrix changes them.
533
549
  **The consequence of switching this on:** an API mapped only to Super Admin is refused to everyone else. Map each registered API to every role that uses it.
534
550
 
535
551
 
552
+ ### Licensed modules
553
+
554
+ Every catalog row (`apis`, `menus`, `uiPages`, `uiElements`) carries a `licenseModule` (`0007_license_module`):
555
+ - **`core`** is the default: sign-in, company selection, and anything that belongs to no product.
556
+ - **Anything else** names the product the row was sold as: `bi`, `warehouse`, `xflow`, and so on.
557
+
558
+ Roles say what a user's job lets them do; the licence says what was paid for. Access needs both.
559
+
560
+ What was paid for is the host's to say, not this library's. An on-premises install reads it from its licence, and a SaaS app from its billing. The host registers one function in the auth process, in the same boot file as [hooks](#hooks):
561
+
562
+ ```js
563
+ var auth = require('@xeplr/auth')
564
+ auth.licence.use({
565
+ modulesFor: async function(userId) { return ['bi', 'warehouse'] } // this user's modules
566
+ })
567
+ auth.boot()
568
+ ```
569
+
570
+ - **Nothing registered:** no filtering. Every module is allowed, exactly as before.
571
+ - **`core` is always allowed,** whatever the function answers: a user who cannot sign in cannot be told they are unlicensed.
572
+ - **APIs:** an API of another module is `unlicensed`, which `/verify`, `accessMiddleware` and `accessGate` answer with `403 UNLICENSED`. This is checked before roles, so no role mapping, public flag or missing mapping gets past it.
573
+ - **The access object:** it leaves those rows out entirely (`apis`, `pages`, `elements`, `menus`, public ones included). They are not greyed out: the product was not bought.
574
+ - **Timing:** the answer is folded into the user's cached access (5 minutes). A change, such as a seat given or taken, reaches the user within that, or at once after `accessService.clearUserAccess(userId)`.
575
+
536
576
  ## Multi-tenancy
537
577
 
538
578
  `userTenantsMapping` records membership: `userId`, `level` (`l1`–`l4`, matching `mtId1`–`mtId4`), `value` (the app's own id at that level — auth owns no tenant tree), an optional `roleId`, `isActive`. One row per user, level and value.
@@ -589,6 +629,8 @@ Hooks run in the process that did the work — register them in the same script
589
629
  npm test # node --test test/*.test.js
590
630
  ```
591
631
 
632
+ `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
+
592
634
  `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.
593
635
 
594
636
  ## License
package/index.js CHANGED
@@ -18,6 +18,7 @@ const { accessMiddleware, requireRole } = require('./lib/accessMiddleware');
18
18
  const sessionService = require('./lib/sessionService');
19
19
  const ticketService = require('./lib/ticketService');
20
20
  const hooks = require('./lib/hooks');
21
+ const licence = require('./lib/licence');
21
22
  const mtMembershipMiddleware = require('./lib/mtMembershipMiddleware');
22
23
  const createAuthRouter = require('./lib/authRouter');
23
24
  const createAdminRouter = require('./lib/adminRouter');
@@ -110,8 +111,8 @@ async function start(config = {}) {
110
111
  //
111
112
  // Not a hole. createAuthRouter gates its own protected routes per-route
112
113
  // with authMiddleware (/me, /profile, /change-password, /sse-ticket, and
113
- // all of /admin). What is left open — login, register, activate, refresh,
114
- // forgot/reset-password — is open by design, because it is how a caller
114
+ // all of /admin). What is left open — login, register, resend-activation,
115
+ // activate, refresh, forgot/reset-password — is open by design, because it is how a caller
115
116
  // obtains a token in the first place.
116
117
  auth: false,
117
118
  corsOptions: config.corsOptions,
@@ -216,11 +217,15 @@ async function boot() {
216
217
  // reset) cannot be sent, and the banner says so rather than the first
217
218
  // person to register finding out.
218
219
  var email = await emailStatus();
220
+ // Registration and reset refuse up front when mail is known not to work,
221
+ // instead of creating an account whose link never goes out.
222
+ authService.configureEmailStatus(email.unknown ? null : email.ok);
219
223
  authService.configureActivation({
220
224
  // Fully qualified, one per link — the token is the only thing appended.
221
225
  // AUTH_ACTIVATION_BASE_URL still works as an origin; see configureActivation.
222
226
  activationUrl: process.env.AUTH_ACTIVATION_URL || null,
223
227
  inviteUrl: process.env.AUTH_INVITE_URL || null,
228
+ resetUrl: process.env.AUTH_RESET_URL || null,
224
229
  baseUrl: process.env.AUTH_ACTIVATION_BASE_URL || null
225
230
  });
226
231
 
@@ -250,9 +255,9 @@ async function emailStatus() {
250
255
 
251
256
  function warnNoEmail(email) {
252
257
  console.warn('[xeplr-auth] EMAIL IS NOT WORKING — ' + String(email.detail).replace(/\.$/, '') + '.');
253
- console.warn(' Sign-in keeps working. Registration, invites and password');
254
- console.warn(' resets cannot send their links until this is fixed: set');
255
- console.warn(' EMAIL_PROVIDER (smtp, brevo, aws or azure) and its settings.\n');
258
+ console.warn(' Sign-in keeps working. Registration, resending activation links,');
259
+ console.warn(' invites and password resets are refused until this is fixed:');
260
+ console.warn(' set EMAIL_PROVIDER (smtp, brevo, aws or azure) and its settings.\n');
256
261
  }
257
262
 
258
263
  function describeEmail(email) {
@@ -273,6 +278,8 @@ function banner(email) {
273
278
  [migrationsVar('auth'), migrationsFor('auth') || '(none)'],
274
279
  ['activation url', process.env.AUTH_ACTIVATION_URL || process.env.AUTH_ACTIVATION_BASE_URL || '(none)'],
275
280
  ['invite url', process.env.AUTH_INVITE_URL || '(derived)'],
281
+ ['reset url', process.env.AUTH_RESET_URL || (process.env.AUTH_ACTIVATION_BASE_URL ? '(derived)' : '✗ NOT SET, password reset refused')],
282
+ ['sign-up roles', process.env.AUTH_REGISTER_ROLES || '✗ NOT SET, registration refused'],
276
283
  ['access token ttl', (process.env.AUTH_ACCESS_TOKEN_TTL_MINUTES || '15') + 'm'],
277
284
  ['refresh token ttl', (process.env.AUTH_REFRESH_TOKEN_TTL_DAYS || '7') + 'd'],
278
285
  ['slide tolerance', (process.env.AUTH_ACCESS_TOKEN_TOLERANCE_SECONDS || '0') + 's'],
@@ -325,6 +332,7 @@ function attach() {
325
332
  // AUTH_ACTIVATION_BASE_URL still works as an origin; see configureActivation.
326
333
  activationUrl: process.env.AUTH_ACTIVATION_URL || null,
327
334
  inviteUrl: process.env.AUTH_INVITE_URL || null,
335
+ resetUrl: process.env.AUTH_RESET_URL || null,
328
336
  baseUrl: process.env.AUTH_ACTIVATION_BASE_URL || null
329
337
  });
330
338
  return _conn;
@@ -347,11 +355,6 @@ function attach() {
347
355
  var requiredEnv = [
348
356
  'ENCRYPTION_KEY',
349
357
  'AUTH_JWT_SECRET',
350
- // NOT listed literally: the activation link can be given either as
351
- // AUTH_ACTIVATION_URL (fully qualified, preferred) or as the older
352
- // AUTH_ACTIVATION_BASE_URL (an origin). checkEnv takes a list of names and
353
- // demands every one, which would refuse to boot an install that configured
354
- // the new form. The getter below asks for whichever is actually in use.
355
358
  'AUTH_PORT',
356
359
  'AUTH_DB_NAME', // auth db (api reaches it via attach())
357
360
  'XEPLR_AUTH_MIGRATIONS', // migrations run via migrate:up
@@ -379,11 +382,33 @@ var requiredEnv = [
379
382
  // forgot it would create every role as '*' — visible to every company —
380
383
  // and nothing would look wrong. See lib/tenant.js.
381
384
  'AUTH_TENANT_HEADER',
385
+
386
+ // THE SIGN-UP FLOW. Without these the service starts and signs people in,
387
+ // but nobody new can get in: registration, activation and password reset
388
+ // each refuse. That shows up as the first person to register finding out,
389
+ // so it is refused here, before anything starts. See README "Sign-up and
390
+ // activation".
391
+ //
392
+ // The role a new account gets when it is activated — no default, each app
393
+ // names its own (e.g. Viewer).
394
+ 'AUTH_REGISTER_ROLES',
395
+
396
+ // The two links that go out by email. Each can be given fully qualified
397
+ // (preferred) or derived from the older AUTH_ACTIVATION_BASE_URL origin, so
398
+ // the name asked for is whichever form this install uses: demanding the new
399
+ // name would refuse an install correctly configured the old way.
400
+ linkVar('AUTH_ACTIVATION_URL'),
401
+ linkVar('AUTH_RESET_URL'),
382
402
  ];
383
403
 
384
- // Read at ACCESS time so it reflects the .env the app has already loaded — the
385
- // same reason @xeplr/email's requiredEnv is a getter. Names the form the
386
- // install is actually using, and asks for the new one when neither is set.
404
+ // Decided when this module loads, which is after the launcher (dotenv -e …)
405
+ // has filled process.env — so the list names the form actually in use.
406
+ function linkVar(name) {
407
+ return process.env.AUTH_ACTIVATION_BASE_URL && !process.env[name] ? 'AUTH_ACTIVATION_BASE_URL' : name;
408
+ }
409
+
410
+ // Kept for callers that read it; the list above now carries the same name.
411
+ // Read at ACCESS time so it reflects the .env the app has already loaded.
387
412
  Object.defineProperty(requiredEnv, 'activationLinkVar', {
388
413
  enumerable: false,
389
414
  get: function () {
@@ -426,5 +451,6 @@ module.exports = {
426
451
  sessionService,
427
452
  ticketService,
428
453
  hooks,
454
+ licence,
429
455
  models
430
456
  };
@@ -1,12 +1,20 @@
1
1
  const { verifyToken } = require('./authHelper');
2
2
  const accessService = require('./accessService');
3
3
  const { getApiRule, userApiState } = accessService;
4
+ const licence = require('./licence');
5
+
6
+ /** The 403 for a state that is not 'enabled'. Anything unknown is HIDDEN: refused. */
7
+ function refuse(res, state) {
8
+ if (state === 'unlicensed') return res.status(403).json({ error: 'This is not part of your licence', code: 'UNLICENSED' });
9
+ if (state === 'disabled') return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
10
+ return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
11
+ }
4
12
 
5
13
  /**
6
14
  * Access-aware middleware.
7
15
  * Uses Redis-cached API rules: isPublic → unmapped → the user's state.
8
- * Only 'enabled' goes through; 'disabled' and 'hidden' are refused, each with
9
- * its own code so a UI can tell them apart.
16
+ * Only 'enabled' goes through; 'disabled', 'hidden' and 'unlicensed' are
17
+ * refused, each with its own code so a UI can tell them apart.
10
18
  *
11
19
  * Usage:
12
20
  * app.use('/api', accessMiddleware());
@@ -26,8 +34,10 @@ function accessMiddleware(options = {}) {
26
34
  // Single cached lookup for API rule (public flag + role IDs)
27
35
  const rule = await getApiRule(apiName);
28
36
 
29
- // Not in DB, or marked public, or no role mappings = open
30
- if (!rule.exists || rule.isPublic || rule.unmapped) return next();
37
+ // Not in DB, or marked public, or no role mappings = open — unless the
38
+ // row belongs to a sold module, which needs a user to check the licence of.
39
+ var open = !rule.exists || rule.isPublic || rule.unmapped;
40
+ if (open && (!rule.exists || rule.licenseModule === licence.CORE || !rule.licenseModule)) return next();
31
41
 
32
42
  // From here, auth is required
33
43
  const authHeader = req.headers.authorization;
@@ -48,10 +58,7 @@ function accessMiddleware(options = {}) {
48
58
  // The user's state for this API (also cached)
49
59
  var state = await userApiState(decoded.id, apiName);
50
60
  if (state === 'enabled') return next();
51
- if (state === 'disabled') {
52
- return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
53
- }
54
- return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
61
+ refuse(res, state);
55
62
  };
56
63
  }
57
64
 
@@ -74,10 +81,7 @@ function accessGate() {
74
81
  return res.status(503).json({ error: 'Access rules are unavailable; try again shortly' });
75
82
  }
76
83
  if (answer.state === 'enabled') return next();
77
- if (answer.state === 'disabled') {
78
- return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
79
- }
80
- return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
84
+ refuse(res, answer.state);
81
85
  };
82
86
  }
83
87
 
@@ -6,6 +6,7 @@ const Menu = require('../models/Menu');
6
6
  const UiElement = require('../models/UiElement');
7
7
  const { visibleItems } = require('./menuService');
8
8
  const { matchApi } = require('./apiMatch');
9
+ const licence = require('./licence');
9
10
 
10
11
  // Cache TTLs (seconds)
11
12
  const USER_ACCESS_TTL = 300; // 5 min — user's full access object
@@ -36,6 +37,11 @@ async function getUserAccess(userId) {
36
37
  return empty;
37
38
  }
38
39
 
40
+ // Rows of a module this user is not licensed for are left out entirely:
41
+ // not greyed, not usable. See lib/licence.js.
42
+ const modules = await licence.modulesFor(userId);
43
+ function licensed(row) { return licence.allows(modules, row.licenseModule); }
44
+
39
45
  const roleNames = new Set();
40
46
  const pages = new Set();
41
47
  const apis = new Set();
@@ -53,6 +59,7 @@ async function getUserAccess(userId) {
53
59
  const enabledMenus = new Set();
54
60
  function sortInto(rows, enabled, disabled) {
55
61
  for (const row of rows || []) {
62
+ if (!licensed(row)) continue;
56
63
  if (row.state === 'disabled') disabled.add(row.name);
57
64
  else enabled.add(row.name);
58
65
  }
@@ -65,18 +72,22 @@ async function getUserAccess(userId) {
65
72
  sortInto(role.uiElements, elements, disabledElements);
66
73
  sortInto(role.menus, enabledMenus, disabledMenus);
67
74
  if (role.menus) {
68
- for (const menu of role.menus) menuRows.push(menu);
75
+ for (const menu of role.menus) if (licensed(menu)) menuRows.push(menu);
69
76
  }
70
77
  }
71
78
 
72
- // Add public items
79
+ // Add public items — public to every role, still only within the licence.
73
80
  const publicItems = await getPublicItems();
74
- for (const api of publicItems.apis) apis.add(api);
75
- for (const page of publicItems.pages) pages.add(page);
81
+ const publicModules = publicItems.licenseModules || {};
82
+ function licensedPublic(kind, name) { return licence.allows(modules, publicModules[kind + ':' + name]); }
83
+ for (const api of publicItems.apis) if (licensedPublic('api', api)) apis.add(api);
84
+ for (const page of publicItems.pages) if (licensedPublic('page', page)) pages.add(page);
76
85
  // Rows, not just names: a hidden item is left out, and each keeps its label
77
86
  // and position. Caches written before labels existed carry names only.
78
- for (const menu of publicItems.menuItems || publicItems.menus.map((name) => ({ name }))) menuRows.push(menu);
79
- for (const name of publicItems.menus || []) enabledMenus.add(name);
87
+ for (const menu of publicItems.menuItems || publicItems.menus.map((name) => ({ name }))) {
88
+ if (licensedPublic('menu', menu.name)) menuRows.push(menu);
89
+ }
90
+ for (const name of publicItems.menus || []) if (licensedPublic('menu', name)) enabledMenus.add(name);
80
91
  // Enabled through any role (or public) beats disabled through another.
81
92
  const menuItems = visibleItems(menuRows).map(function(m) {
82
93
  return (disabledMenus.has(m.name) && !enabledMenus.has(m.name)) ? Object.assign({}, m, { disabled: true }) : m;
@@ -122,8 +133,13 @@ async function getPublicItems() {
122
133
  apis: publicApis.map(a => a.name),
123
134
  pages: publicPages.map(p => p.name),
124
135
  menus: publicMenus.filter(m => !m.isHidden).map(m => m.name),
125
- menuItems: publicMenus.map(m => ({ name: m.name, label: m.label || null, sortOrder: m.sortOrder === undefined ? null : m.sortOrder, isHidden: !!m.isHidden }))
136
+ menuItems: publicMenus.map(m => ({ name: m.name, label: m.label || null, sortOrder: m.sortOrder === undefined ? null : m.sortOrder, isHidden: !!m.isHidden })),
137
+ // 'api:<name>' / 'page:<name>' / 'menu:<name>' → licenseModule, for rows of a product.
138
+ licenseModules: {}
126
139
  };
140
+ publicApis.forEach(function(a) { if (a.licenseModule && a.licenseModule !== licence.CORE) result.licenseModules['api:' + a.name] = a.licenseModule; });
141
+ publicPages.forEach(function(p) { if (p.licenseModule && p.licenseModule !== licence.CORE) result.licenseModules['page:' + p.name] = p.licenseModule; });
142
+ publicMenus.forEach(function(m) { if (m.licenseModule && m.licenseModule !== licence.CORE) result.licenseModules['menu:' + m.name] = m.licenseModule; });
127
143
 
128
144
  await cache.set(publicItemsKey, result, API_RULES_TTL);
129
145
  return result;
@@ -144,7 +160,7 @@ async function getApiRule(apiName) {
144
160
 
145
161
  if (!api) {
146
162
  // Not registered = open
147
- const rule = { exists: false, isPublic: true, roleIds: [] };
163
+ const rule = { exists: false, isPublic: true, roleIds: [], licenseModule: licence.CORE };
148
164
  await cache.set(cacheKey, rule, API_RULES_TTL);
149
165
  return rule;
150
166
  }
@@ -159,7 +175,8 @@ async function getApiRule(apiName) {
159
175
  isPublic: !!api.isPublic,
160
176
  unmapped: mapped.length === 0,
161
177
  roleIds,
162
- disabledRoleIds
178
+ disabledRoleIds,
179
+ licenseModule: api.licenseModule || licence.CORE
163
180
  };
164
181
 
165
182
  await cache.set(cacheKey, rule, API_RULES_TTL);
@@ -169,14 +186,17 @@ async function getApiRule(apiName) {
169
186
  /**
170
187
  * Access states. A gate answers one of these, not true/false:
171
188
  *
172
- * enabled shown and usable
173
- * disabled shown, greyed out, not usable: the API refuses it
174
- * hidden not shown: the API refuses it
189
+ * enabled shown and usable
190
+ * disabled shown, greyed out, not usable: the API refuses it
191
+ * hidden not shown: the API refuses it
192
+ * unlicensed not shown: the API belongs to a module the user's licence
193
+ * does not include (lib/licence.js). Checked before roles, so
194
+ * no role, public flag or missing mapping gets past it.
175
195
  *
176
196
  * A role mapping row decides: no row → hidden; a row → its state (enabled,
177
197
  * or disabled from the Access Matrix). Several roles: the most open wins.
178
198
  */
179
- var ACCESS_STATES = ['enabled', 'disabled', 'hidden'];
199
+ var ACCESS_STATES = ['enabled', 'disabled', 'hidden', 'unlicensed'];
180
200
 
181
201
  /**
182
202
  * The state for an API rule and a user's role ids. Pure, so it can be tested
@@ -215,6 +235,7 @@ async function userRoleIdsOf(userId) {
215
235
  */
216
236
  async function userApiState(userId, apiName) {
217
237
  var rule = await getApiRule(apiName);
238
+ if (rule.exists && !licence.allows(await licence.modulesFor(userId), rule.licenseModule)) return 'unlicensed';
218
239
  if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
219
240
  return apiStateFor(rule, await userRoleIdsOf(userId));
220
241
  }
@@ -5,6 +5,8 @@ var { accessGate } = require('./accessMiddleware');
5
5
  var { createMenuService } = require('./menuService');
6
6
  var authMiddleware = require('./authMiddleware');
7
7
  var hooks = require('./hooks');
8
+ var { grantRoles } = require('./userRoles');
9
+ var { adminActivate } = require('./authService');
8
10
  var { isSuperAdmin, systemScopeGuard, SUPER_ADMIN_ROLE } = require('./systemScope');
9
11
  var { tenantOf, visibleTenants, GENERIC } = require('./tenant');
10
12
  var User = require('../models/User');
@@ -99,8 +101,10 @@ function createAdminRouter() {
99
101
  // ─── Users with their roles ───
100
102
  router.get('/users', async function(req, res) {
101
103
  try {
104
+ // invitePending: invited and has not set a password yet — activated by
105
+ // accepting the invite, never by an admin. Only the fact leaves here.
102
106
  var users = await User.query()
103
- .select('id', 'email', 'name', 'isActive', 'isActivated')
107
+ .select('id', 'email', 'name', 'isActive', 'isActivated', User.raw('("pwd" IS NULL) as "invitePending"'))
104
108
  .withGraphFetched('roles');
105
109
  res.json(users);
106
110
  } catch (err) {
@@ -108,6 +112,26 @@ function createAdminRouter() {
108
112
  }
109
113
  });
110
114
 
115
+ // ─── Activate an account by hand ───
116
+ // For someone whose activation mail never arrived, or an app that approves
117
+ // sign-ups itself. Gives the account the same sign-up roles the emailed
118
+ // link would (AUTH_REGISTER_ROLES).
119
+ router.post('/users/:id/activate', async function(req, res) {
120
+ try {
121
+ var user = await adminActivate(req.params.id, req.user ? req.user.id : null);
122
+ res.json({ message: 'Account activated', user: user });
123
+ } catch (err) {
124
+ if (err.code === 'USER_NOT_FOUND') return res.status(404).json({ error: err.message, code: err.code });
125
+ if (err.code === 'ALREADY_ACTIVATED' || err.code === 'INVITE_PENDING') {
126
+ return res.status(409).json({ error: err.message, code: err.code });
127
+ }
128
+ if (err.code && err.code.indexOf('REGISTER_ROLES_') === 0) {
129
+ return res.status(503).json({ error: err.message, code: err.code });
130
+ }
131
+ res.status(500).json({ error: 'Something went wrong' });
132
+ }
133
+ });
134
+
111
135
  // ─── Roles ───
112
136
  router.get('/roles', async function(req, res) {
113
137
  try {
@@ -145,23 +169,14 @@ function createAdminRouter() {
145
169
  if (await refuseSystemRole(req, res, roleId)) return;
146
170
 
147
171
  if (assign) {
148
- var existing = await UserRolesMapping.query()
149
- .findOne({ userId: userId, roleId: roleId });
150
- if (!existing) {
151
- await UserRolesMapping.query().insert({
152
- id: generateId(),
153
- userId: userId,
154
- roleId: roleId,
155
- recordCreatedBy: req.user ? req.user.id : null
156
- });
157
- }
172
+ await grantRoles(userId, [roleId], { by: req.user ? req.user.id : null });
158
173
  } else {
159
174
  await UserRolesMapping.query()
160
175
  .delete()
161
176
  .where({ userId: userId, roleId: roleId });
177
+ await clearUserAccess(userId);
162
178
  }
163
179
 
164
- await clearUserAccess(userId);
165
180
  await hooks.fire('userRolesMapping', assign ? 'create' : 'delete', userId);
166
181
  res.json({ ok: true });
167
182
  } catch (err) {
package/lib/authRouter.js CHANGED
@@ -1,6 +1,6 @@
1
1
  const express = require('express');
2
2
  const FileUploader = require('@xeplr/utils/lib/fileUploader');
3
- const { register, activate, previewInvite, acceptInvite, login, forgotPassword, resetPassword, requestPhoneOtp, verifyPhoneOtp, getProfile, updateProfile, setProfilePic, changePassword } = require('./authService');
3
+ const { register, resendActivation, activate, previewInvite, acceptInvite, login, forgotPassword, resetPassword, requestPhoneOtp, verifyPhoneOtp, getProfile, updateProfile, setProfilePic, changePassword } = require('./authService');
4
4
  const { getUserAccess, requestApiState } = require('./accessService');
5
5
  const { getSession, rotateSession, destroySession } = require('./sessionService');
6
6
  const { issueTicket } = require('./ticketService');
@@ -24,6 +24,18 @@ function logError(req, err) {
24
24
  if (req.log) req.log.error(err.message, { stack: err.stack });
25
25
  }
26
26
 
27
+ // A refusal the person cannot fix by retrying: the server is missing a
28
+ // setting or cannot send mail. 503 with the reason, so whoever runs the app
29
+ // sees which setting to fix instead of a bare "Something went wrong".
30
+ var SERVER_NOT_READY = ['EMAIL_NOT_SET_UP', 'EMAIL_SEND_FAILED', 'ACTIVATION_URL_NOT_SET', 'RESET_URL_NOT_SET',
31
+ 'REGISTER_ROLES_NOT_SET', 'REGISTER_ROLES_UNKNOWN', 'REGISTER_ROLES_SYSTEM'];
32
+
33
+ function sendNotReady(res, err) {
34
+ if (SERVER_NOT_READY.indexOf(err.code) === -1) return false;
35
+ res.status(503).json({ error: err.message, code: err.code });
36
+ return true;
37
+ }
38
+
27
39
  function createAuthRouter(options = {}) {
28
40
  const router = express.Router();
29
41
  const resetBaseUrl = options.resetBaseUrl || null;
@@ -43,6 +55,21 @@ function createAuthRouter(options = {}) {
43
55
  if (err.message === 'Email already registered') {
44
56
  return res.status(409).json({ error: err.message });
45
57
  }
58
+ if (sendNotReady(res, err)) return;
59
+ res.status(500).json({ error: 'Something went wrong' });
60
+ }
61
+ });
62
+
63
+ // Same answer whether or not the address has an account.
64
+ router.post('/resend-activation', async function(req, res) {
65
+ try {
66
+ var email = req.body && req.body.email;
67
+ if (!email) return res.status(400).json({ error: 'Email is required' });
68
+ await resendActivation({ email: email });
69
+ res.json({ message: 'If that account is waiting for activation, a new link has been sent.' });
70
+ } catch (err) {
71
+ logError(req, err);
72
+ if (sendNotReady(res, err)) return;
46
73
  res.status(500).json({ error: 'Something went wrong' });
47
74
  }
48
75
  });
@@ -61,6 +88,7 @@ function createAuthRouter(options = {}) {
61
88
  res.json({ message: 'Account activated successfully', user: result });
62
89
  } catch (err) {
63
90
  logError(req, err);
91
+ if (sendNotReady(res, err)) return;
64
92
  res.status(400).json({ error: err.message });
65
93
  }
66
94
  });
@@ -104,7 +132,10 @@ function createAuthRouter(options = {}) {
104
132
  } catch (err) {
105
133
  logError(req, err);
106
134
  if (err.message === 'NOT_ACTIVATED') {
107
- return res.status(403).json({ error: 'Please wait, someone will activate you.' });
135
+ return res.status(403).json({
136
+ error: 'Your account is not activated yet. Open the activation link we emailed you.',
137
+ code: 'NOT_ACTIVATED'
138
+ });
108
139
  }
109
140
  if (err.message === 'Invalid email or password' || err.message === 'Account is deactivated') {
110
141
  return res.status(401).json({ error: err.message });
@@ -121,11 +152,11 @@ function createAuthRouter(options = {}) {
121
152
  return res.status(400).json({ error: 'Email is required' });
122
153
  }
123
154
 
124
- const baseUrl = resetBaseUrl || req.protocol + '://' + req.get('host');
125
- await forgotPassword({ email }, baseUrl);
155
+ await forgotPassword({ email }, resetBaseUrl);
126
156
  res.json({ message: 'If that email exists, a reset link has been sent.' });
127
157
  } catch (err) {
128
158
  logError(req, err);
159
+ if (sendNotReady(res, err)) return;
129
160
  res.status(500).json({ error: 'Something went wrong' });
130
161
  }
131
162
  });
@@ -240,6 +271,9 @@ function createAuthRouter(options = {}) {
240
271
  var access = await getUserAccess(req.user.id);
241
272
  return res.json({ user: req.user, access: access, state: 'enabled', api: answer.api });
242
273
  }
274
+ if (answer.state === 'unlicensed') {
275
+ return res.status(403).json({ error: 'This is not part of your licence', code: 'UNLICENSED', api: answer.api });
276
+ }
243
277
  if (answer.state === 'disabled') {
244
278
  return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED', api: answer.api });
245
279
  }
@@ -6,6 +6,7 @@ const User = require('../models/User');
6
6
  const { getUserAccess, clearUserAccess } = require('./accessService');
7
7
  const { createSession, destroyAllUserSessions } = require('./sessionService');
8
8
  const hooks = require('./hooks');
9
+ const { grantRoles, registerRoleIds, refusal } = require('./userRoles');
9
10
 
10
11
  // WHERE THE LINKS IN OUR EMAILS POINT.
11
12
  //
@@ -19,9 +20,39 @@ const hooks = require('./hooks');
19
20
  // path for each link is appended, exactly as before. It served both the
20
21
  // activation and the invite page, which is precisely why one fully-qualified
21
22
  // value could not replace it.
22
- var _links = { activationUrl: null, inviteUrl: null, baseUrl: null };
23
+ var _links = { activationUrl: null, inviteUrl: null, resetUrl: null, baseUrl: null };
23
24
 
24
- var DEFAULT_PATHS = { activation: '/auth/activate', invite: '/auth/accept-invite' };
25
+ var DEFAULT_PATHS = { activation: '/auth/activate', invite: '/auth/accept-invite', reset: '/auth/reset-password' };
26
+
27
+ var LINK_VARS = { activation: 'AUTH_ACTIVATION_URL', invite: 'AUTH_INVITE_URL', reset: 'AUTH_RESET_URL' };
28
+
29
+ // CAN MAIL GO OUT? Set by boot() from its startup check: true, false, or null
30
+ // when nobody checked (an app that calls init()/start() itself). Known-false
31
+ // refuses registration before an account exists; null lets it try, and a
32
+ // failed send rolls the account back — either way no account is left behind
33
+ // that was never sent its link.
34
+ var _emailReady = null;
35
+
36
+ function configureEmailStatus(ready) {
37
+ _emailReady = ready === true || ready === false ? ready : null;
38
+ }
39
+
40
+ function requireEmail(what) {
41
+ if (_emailReady === false) {
42
+ throw refusal('EMAIL_NOT_SET_UP', 'Email is not set up on this server, so ' + what +
43
+ ' cannot be sent. Set EMAIL_PROVIDER and its settings.');
44
+ }
45
+ }
46
+
47
+ async function sendOrRefuse(to, subject, html, what) {
48
+ try {
49
+ await sendEmail(to, subject, html);
50
+ } catch (err) {
51
+ var wrapped = refusal('EMAIL_SEND_FAILED', 'Could not send ' + what + ': ' + err.message);
52
+ wrapped.cause = err;
53
+ throw wrapped;
54
+ }
55
+ }
25
56
 
26
57
  // RESUMING A WORKFLOW ON ACTIVATION.
27
58
  //
@@ -71,13 +102,12 @@ function configureActivation(config) {
71
102
  if (!config) return;
72
103
  if (config.activationUrl !== undefined) _links.activationUrl = config.activationUrl;
73
104
  if (config.inviteUrl !== undefined) _links.inviteUrl = config.inviteUrl;
105
+ if (config.resetUrl !== undefined) _links.resetUrl = config.resetUrl;
74
106
  if (config.baseUrl !== undefined) _links.baseUrl = config.baseUrl;
75
107
  }
76
108
 
77
109
  function linkFor(kind) {
78
- var explicit = kind === 'activation'
79
- ? (_links.activationUrl || process.env.AUTH_ACTIVATION_URL)
80
- : (_links.inviteUrl || process.env.AUTH_INVITE_URL);
110
+ var explicit = _links[kind + 'Url'] || process.env[LINK_VARS[kind]];
81
111
  if (explicit) return explicit;
82
112
 
83
113
  var base = _links.baseUrl || process.env.AUTH_ACTIVATION_BASE_URL;
@@ -92,7 +122,39 @@ function withToken(url, token) {
92
122
  return url + (url.indexOf('?') === -1 ? '?' : '&') + 'token=' + token;
93
123
  }
94
124
 
125
+ function activationEmail(name, link) {
126
+ return '<h2>Activate your account</h2>'
127
+ + '<p>Hi ' + (name || 'there') + ',</p>'
128
+ + '<p>Click below to activate your account:</p>'
129
+ + '<p><a href="' + link + '">' + link + '</a></p>';
130
+ }
131
+
132
+ // The key rides along in the link so it comes back to us when the user
133
+ // clicks — there is nowhere else to keep it: activation happens in a
134
+ // different browser, days later, with no session.
135
+ function activationLinkFor(activationUrl, token, workflowKey) {
136
+ var link = withToken(activationUrl, token);
137
+ if (workflowKey) link += '&workflowKey=' + encodeURIComponent(workflowKey);
138
+ return link;
139
+ }
140
+
141
+ function requireActivationUrl() {
142
+ var activationUrl = linkFor('activation');
143
+ if (!activationUrl) {
144
+ throw refusal('ACTIVATION_URL_NOT_SET', 'AUTH_ACTIVATION_URL is required (the full address of your activation page, ' +
145
+ 'e.g. http://localhost:19100/auth/activate). Cannot register without email activation.');
146
+ }
147
+ return activationUrl;
148
+ }
149
+
95
150
  async function register({ email, phoneNumber, name, password, workflowKey, knex }) {
151
+ // EVERYTHING THAT CAN REFUSE, BEFORE THE ACCOUNT EXISTS. An account created
152
+ // and then refused is stuck: its address is taken (a retry says "already
153
+ // registered") and it can never be activated, because the link never went.
154
+ var activationUrl = requireActivationUrl();
155
+ requireEmail('the activation link');
156
+ await registerRoleIds(knex); // the roles it gets on activation must exist now
157
+
96
158
  const UserM = knex ? User.bindKnex(knex) : User;
97
159
  const normalized = normalizeEmail(email);
98
160
 
@@ -106,44 +168,32 @@ async function register({ email, phoneNumber, name, password, workflowKey, knex
106
168
  const now = formatDbDateTime();
107
169
  const activationToken = crypto.randomBytes(32).toString('hex');
108
170
 
109
- const user = await UserM.query().insert({
110
- id,
111
- email: email.trim().toLowerCase(),
112
- normalizedEmail: normalized,
113
- phoneNumber: phoneNumber || null,
114
- name: name || null,
115
- pwd: hash,
116
- pwdSalt: salt,
117
- isActive: true,
118
- isActivated: false,
119
- activationToken,
120
- activatedOn: null,
121
- activatedBy: null,
122
- recordCreatedDate: now,
123
- recordModifiedDate: now,
124
- recordCreatedBy: id,
125
- recordModifiedBy: id
171
+ // The send is inside the transaction: if the mail cannot go out, the
172
+ // account is rolled back and the person can simply try again.
173
+ var user = await (knex || User.knex()).transaction(async function(trx) {
174
+ var created = await User.bindKnex(trx).query().insert({
175
+ id,
176
+ email: email.trim().toLowerCase(),
177
+ normalizedEmail: normalized,
178
+ phoneNumber: phoneNumber || null,
179
+ name: name || null,
180
+ pwd: hash,
181
+ pwdSalt: salt,
182
+ isActive: true,
183
+ isActivated: false,
184
+ activationToken,
185
+ activatedOn: null,
186
+ activatedBy: null,
187
+ recordCreatedDate: now,
188
+ recordModifiedDate: now,
189
+ recordCreatedBy: id,
190
+ recordModifiedBy: id
191
+ });
192
+ var link = activationLinkFor(activationUrl, activationToken, workflowKey);
193
+ await sendOrRefuse(email, 'Activate your account', activationEmail(name, link), 'the activation link');
194
+ return created;
126
195
  });
127
196
 
128
- // Send activation email
129
- const activationUrl = linkFor('activation');
130
- if (!activationUrl) {
131
- throw new Error('AUTH_ACTIVATION_URL is required (the full address of your activation page, ' +
132
- 'e.g. http://localhost:19100/auth/activate). Cannot register without email activation.');
133
- }
134
-
135
- // The key rides along in the link so it comes back to us when the user
136
- // clicks — there is nowhere else to keep it: activation happens in a
137
- // different browser, days later, with no session.
138
- var activationLink = withToken(activationUrl, activationToken);
139
- if (workflowKey) activationLink += '&workflowKey=' + encodeURIComponent(workflowKey);
140
- const html = '<h2>Activate your account</h2>'
141
- + '<p>Hi ' + (name || 'there') + ',</p>'
142
- + '<p>Click below to activate your account:</p>'
143
- + '<p><a href="' + activationLink + '">' + activationLink + '</a></p>';
144
-
145
- await sendEmail(email, 'Activate your account', html);
146
-
147
197
  await hooks.fire('user', 'create', user.id);
148
198
 
149
199
  return {
@@ -156,6 +206,48 @@ async function register({ email, phoneNumber, name, password, workflowKey, knex
156
206
  };
157
207
  }
158
208
 
209
+ /**
210
+ * Send a fresh activation link to an account that has not been activated.
211
+ * Answers the same way whether or not the address has an account, so it
212
+ * cannot be used to find out who is registered.
213
+ */
214
+ async function resendActivation({ email }) {
215
+ var activationUrl = requireActivationUrl();
216
+ requireEmail('the activation link');
217
+
218
+ var user = await User.query().findOne({ normalizedEmail: normalizeEmail(email) });
219
+ // Invited accounts (no password yet) activate through their invite link.
220
+ if (!user || user.isActivated || !user.pwd) return;
221
+
222
+ var activationToken = crypto.randomBytes(32).toString('hex');
223
+ await User.query().findById(user.id).patch({
224
+ activationToken: activationToken,
225
+ recordModifiedDate: formatDbDateTime()
226
+ });
227
+ await sendOrRefuse(user.email, 'Activate your account',
228
+ activationEmail(user.name, activationLinkFor(activationUrl, activationToken)), 'the activation link');
229
+ }
230
+
231
+ /**
232
+ * Mark the account activated and give it the app's sign-up roles, together.
233
+ * Both activation paths — the emailed link and an admin — come through here,
234
+ * so an activated account always has the roles it needs to use the app.
235
+ */
236
+ async function markActivated(user, activatedBy) {
237
+ var roleIds = await registerRoleIds();
238
+ var now = formatDbDateTime();
239
+ await User.knex().transaction(async function(trx) {
240
+ await User.bindKnex(trx).query().findById(user.id).patch({
241
+ isActivated: true,
242
+ activatedOn: now,
243
+ activatedBy: activatedBy || null,
244
+ activationToken: null,
245
+ recordModifiedDate: now
246
+ });
247
+ await grantRoles(user.id, roleIds, { by: activatedBy || user.id, knex: trx });
248
+ });
249
+ }
250
+
159
251
  async function activate(token, options) {
160
252
  var workflowKey = options && options.workflowKey;
161
253
  var log = require('@xeplr/logs').createLogger('auth');
@@ -168,7 +260,7 @@ async function activate(token, options) {
168
260
 
169
261
  const user = await User.query().findOne({ activationToken: token });
170
262
  if (!user) {
171
- log.warn('activation: no user holds that token — expired, already used, or wrong link');
263
+ log.important('activation: no user holds that token — expired, already used, or wrong link');
172
264
  throw new Error('Invalid activation token');
173
265
  }
174
266
 
@@ -177,15 +269,17 @@ async function activate(token, options) {
177
269
  throw new Error('Account already activated');
178
270
  }
179
271
 
272
+ // An INVITE token opened as an activation link. Activating here would leave
273
+ // an account with no password that nobody can sign in to, and use up the
274
+ // token the invite page needs.
275
+ if (!user.pwd) {
276
+ log.important('activation: ' + user.email + ' was invited and has no password — refused');
277
+ throw new Error('This link is an invitation. Open it from the invite email to set your password.');
278
+ }
279
+
180
280
  log.info('activation: activating ' + user.email);
181
281
 
182
- const now = formatDbDateTime();
183
- await User.query().findById(user.id).patch({
184
- isActivated: true,
185
- activatedOn: now,
186
- activationToken: null,
187
- recordModifiedDate: now
188
- });
282
+ await markActivated(user, null);
189
283
 
190
284
  log.important('activation: ' + user.email + ' activated');
191
285
  await hooks.fire('user', 'update', user.id);
@@ -207,6 +301,23 @@ async function activate(token, options) {
207
301
  return { id: user.id, email: user.email, name: user.name };
208
302
  }
209
303
 
304
+ /**
305
+ * An admin activates an account without its emailed link — for someone whose
306
+ * mail never arrived, or an app that approves sign-ups by hand.
307
+ */
308
+ async function adminActivate(userId, adminId) {
309
+ var user = await User.query().findById(userId);
310
+ if (!user) throw refusal('USER_NOT_FOUND', 'User not found');
311
+ if (user.isActivated) throw refusal('ALREADY_ACTIVATED', 'This account is already activated');
312
+ if (!user.pwd) {
313
+ throw refusal('INVITE_PENDING', 'This person was invited and has not set a password yet. ' +
314
+ 'They activate by accepting the invite.');
315
+ }
316
+ await markActivated(user, adminId);
317
+ await hooks.fire('user', 'update', user.id);
318
+ return { id: user.id, email: user.email, name: user.name, isActivated: true };
319
+ }
320
+
210
321
  async function login({ email, password }) {
211
322
  const normalized = normalizeEmail(email);
212
323
  const user = await User.query()
@@ -220,6 +331,11 @@ async function login({ email, password }) {
220
331
  throw new Error('Account is deactivated');
221
332
  }
222
333
 
334
+ // An invited account has no password until the invite is accepted.
335
+ if (!user.pwd) {
336
+ throw new Error('Invalid email or password');
337
+ }
338
+
223
339
  const isMatch = await comparePassword(password, user.pwd);
224
340
  if (!isMatch) {
225
341
  throw new Error('Invalid email or password');
@@ -377,7 +493,26 @@ async function acceptInvite({ token, name, password, knex }) {
377
493
  return { id: user.id, email: user.email, name: name || user.name };
378
494
  }
379
495
 
496
+ // WHERE THE RESET LINK POINTS — the app's own setting, never the request's
497
+ // Host header: anyone can send a forgot-password request with Host set to
498
+ // their own site and have us mail the real user a link to it, token included.
499
+ // resetBaseUrl (an origin) is the older way for a host app to say the same.
500
+ function resetUrlFor(resetBaseUrl) {
501
+ if (resetBaseUrl) return String(resetBaseUrl).replace(/\/+$/, '') + DEFAULT_PATHS.reset;
502
+ var url = linkFor('reset');
503
+ if (!url) {
504
+ throw refusal('RESET_URL_NOT_SET', 'AUTH_RESET_URL is required (the full address of your reset-password ' +
505
+ 'page, e.g. http://localhost:19100/auth/reset-password). Password reset links cannot be sent without it.');
506
+ }
507
+ return url;
508
+ }
509
+
380
510
  async function forgotPassword({ email }, resetBaseUrl) {
511
+ // Refused for every address alike, before the lookup, so the answer says
512
+ // nothing about whether this one has an account.
513
+ var resetUrl = resetUrlFor(resetBaseUrl);
514
+ requireEmail('the password reset link');
515
+
381
516
  const normalized = normalizeEmail(email);
382
517
  const user = await User.query().findOne({ normalizedEmail: normalized });
383
518
  if (!user) {
@@ -394,7 +529,7 @@ async function forgotPassword({ email }, resetBaseUrl) {
394
529
  recordModifiedDate: formatDbDateTime()
395
530
  });
396
531
 
397
- const resetLink = `${resetBaseUrl}/auth/reset-password?token=${resetToken}`;
532
+ const resetLink = withToken(resetUrl, resetToken);
398
533
 
399
534
  const html = `
400
535
  <h2>Password Reset</h2>
@@ -405,22 +540,26 @@ async function forgotPassword({ email }, resetBaseUrl) {
405
540
  <p>If you didn't request this, ignore this email.</p>
406
541
  `;
407
542
 
408
- await sendEmail(user.email, 'Password Reset', html);
543
+ await sendOrRefuse(user.email, 'Password Reset', html, 'the password reset link');
409
544
 
410
545
  await hooks.fire('user', 'update', user.id);
411
546
  }
412
547
 
413
548
  async function resetPassword({ token, newPassword }) {
414
- const user = await User.query().findOne({ resetToken: token });
549
+ // EXPIRY IS CHECKED IN THE QUERY, against a value written the same way.
550
+ // forgotPassword stores formatDbDateTime() — UTC — in a column with no time
551
+ // zone. Read back, the driver takes that as LOCAL time, so a comparison in
552
+ // JavaScript is off by the server's UTC offset: east of UTC every fresh link
553
+ // looked expired, and the older `Date < string` check let expired ones
554
+ // through. Postgres compares the two UTC values as written.
555
+ const user = await User.query()
556
+ .findOne({ resetToken: token })
557
+ .where('resetTokenExpiry', '>', formatDbDateTime());
415
558
 
416
559
  if (!user) {
417
560
  throw new Error('Invalid or expired reset token');
418
561
  }
419
562
 
420
- if (user.resetTokenExpiry < formatDbDateTime()) {
421
- throw new Error('Invalid or expired reset token');
422
- }
423
-
424
563
  const { hash, salt } = await hashPassword(newPassword);
425
564
 
426
565
  await User.query().findById(user.id).patch({
@@ -609,8 +748,12 @@ module.exports = {
609
748
  configureActivation,
610
749
  configureWorkflowResume,
611
750
  configureEmail,
751
+ configureEmailStatus,
752
+ linkFor,
612
753
  register,
754
+ resendActivation,
613
755
  activate,
756
+ adminActivate,
614
757
  invite,
615
758
  previewInvite,
616
759
  acceptInvite,
package/lib/licence.js ADDED
@@ -0,0 +1,47 @@
1
+ // WHICH SOLD MODULES A USER MAY USE.
2
+ //
3
+ // Every catalog row (apis, menus, uiPages, uiElements) carries a licenseModule
4
+ // (0007): 'core' for sign-in and everything that belongs to no product, or the
5
+ // product it was sold as ('bi', 'warehouse', 'xflow', ...). Roles say what a
6
+ // user's job lets them do; this says what was paid for. Access is both.
7
+ //
8
+ // What was paid for is the host app's to say, not this library's: an
9
+ // on-premises install reads it from its signed licence, a SaaS app from its
10
+ // billing. So the host registers one function, in the auth process (the same
11
+ // file that calls boot(), as for hooks):
12
+ //
13
+ // require('@xeplr/auth').licence.use({
14
+ // modulesFor: async function(userId) { return ['bi', 'warehouse']; }
15
+ // });
16
+ //
17
+ // Nothing registered: no filtering at all, as before this existed. 'core' is
18
+ // always allowed, whatever the function answers: a user who cannot sign in
19
+ // cannot be told they are unlicensed.
20
+ //
21
+ // The answer is folded into the user's cached access (5 minutes), so a seat
22
+ // given or taken reaches the user within that, or at once after
23
+ // clearUserAccess(userId).
24
+
25
+ var CORE = 'core';
26
+ var _modulesFor = null;
27
+
28
+ function use(options) {
29
+ var fn = options && options.modulesFor;
30
+ if (fn !== undefined && fn !== null && typeof fn !== 'function') throw new Error('licence.use: modulesFor must be a function');
31
+ _modulesFor = fn || null;
32
+ }
33
+
34
+ /** The Set of modules this user may use, or null when no host registered one (everything allowed). */
35
+ async function modulesFor(userId) {
36
+ if (!_modulesFor) return null;
37
+ var modules = new Set((await _modulesFor(userId)) || []);
38
+ modules.add(CORE);
39
+ return modules;
40
+ }
41
+
42
+ /** Is a row of this licenseModule allowed under these modules? */
43
+ function allows(modules, licenseModule) {
44
+ return !modules || modules.has(licenseModule || CORE);
45
+ }
46
+
47
+ module.exports = { use: use, modulesFor: modulesFor, allows: allows, CORE: CORE };
@@ -0,0 +1,76 @@
1
+ var { generateId } = require('./authHelper');
2
+ var Role = require('../models/Role');
3
+ var UserRolesMapping = require('../models/UserRolesMapping');
4
+ var { clearUserAccess } = require('./accessService');
5
+
6
+ /**
7
+ * Give a user roles. Skips any they already hold, then drops their cached
8
+ * access so the next request sees the new roles. The one insert behind both
9
+ * the admin's role toggle and the roles a new account gets on activation.
10
+ *
11
+ * @param {string} userId
12
+ * @param {string[]} roleIds
13
+ * @param {object} [options] - { by: userId doing it, knex: transaction }
14
+ */
15
+ async function grantRoles(userId, roleIds, options) {
16
+ var by = options && options.by;
17
+ var knex = options && options.knex;
18
+ var Mapping = knex ? UserRolesMapping.bindKnex(knex) : UserRolesMapping;
19
+ for (var i = 0; i < roleIds.length; i++) {
20
+ var existing = await Mapping.query().findOne({ userId: userId, roleId: roleIds[i] });
21
+ if (existing) continue;
22
+ await Mapping.query().insert({
23
+ id: generateId(),
24
+ userId: userId,
25
+ roleId: roleIds[i],
26
+ recordCreatedBy: by || null
27
+ });
28
+ }
29
+ await clearUserAccess(userId);
30
+ }
31
+
32
+ // THE ROLES A SELF-REGISTERED ACCOUNT GETS — named by each app, never assumed.
33
+ //
34
+ // Without a role every API mapped to roles is hidden from the person, their
35
+ // own profile included, so an account with none can sign in and do nothing.
36
+ // Which role fits is the app's call (BI: Viewer), so there is no default:
37
+ // registration refuses until AUTH_REGISTER_ROLES names one, rather than
38
+ // quietly creating accounts that cannot use the app.
39
+ //
40
+ // Read at call time, like AUTH_ACTIVATION_URL, so the .env the app has
41
+ // loaded is the one used. System roles (Super Admin) are refused: a sign-up
42
+ // form must never be a way to become one.
43
+ var REGISTER_ROLES_VAR = 'AUTH_REGISTER_ROLES';
44
+
45
+ function refusal(code, message) {
46
+ var err = new Error(message);
47
+ err.code = code;
48
+ return err;
49
+ }
50
+
51
+ async function registerRoleIds(knex) {
52
+ var raw = process.env[REGISTER_ROLES_VAR];
53
+ var names = String(raw || '').split(',')
54
+ .map(function(n) { return n.trim(); })
55
+ .filter(Boolean);
56
+ if (!names.length) {
57
+ throw refusal('REGISTER_ROLES_NOT_SET', REGISTER_ROLES_VAR + ' is not set: name the role(s) a new ' +
58
+ 'account gets, comma-separated (for example Viewer). Registration is refused until it is.');
59
+ }
60
+
61
+ var RoleM = knex ? Role.bindKnex(knex) : Role;
62
+ var roles = await RoleM.query().select('id', 'name', 'scope').where('mtId1', '*').whereIn('name', names);
63
+ var missing = names.filter(function(n) { return !roles.some(function(r) { return r.name === n; }); });
64
+ if (missing.length) {
65
+ throw refusal('REGISTER_ROLES_UNKNOWN', REGISTER_ROLES_VAR + ' names ' +
66
+ (missing.length > 1 ? 'roles that do' : 'a role that does') + ' not exist: ' + missing.join(', ') + '.');
67
+ }
68
+ var system = roles.filter(function(r) { return r.scope === 'system'; });
69
+ if (system.length) {
70
+ throw refusal('REGISTER_ROLES_SYSTEM', REGISTER_ROLES_VAR + ' names a system role (' +
71
+ system.map(function(r) { return r.name; }).join(', ') + '); new accounts can never be given one.');
72
+ }
73
+ return roles.map(function(r) { return r.id; });
74
+ }
75
+
76
+ module.exports = { grantRoles, registerRoleIds, refusal, REGISTER_ROLES_VAR };
@@ -0,0 +1,47 @@
1
+ -- 0014_activation_routes.sql
2
+ -- Routes added for the sign-up flow, plus three that shipped without a row.
3
+ --
4
+ -- POST /auth/api/resend-activation public: a new activation link
5
+ -- POST /auth/api/admin/users/:id/activate users:edit: activate by hand
6
+ -- /auth/api/invite-preview, invite-accept public: the accept-invite page
7
+ -- /auth/api/sse-ticket account:view: any signed-in role
8
+ --
9
+ -- invite-preview, invite-accept and sse-ticket existed with no row, and an
10
+ -- unregistered API is open to everyone — sse-ticket is meant for signed-in
11
+ -- users only.
12
+ --
13
+ -- Mapped the same way as 0012: users:* to Super Admin and Admin, account:* to
14
+ -- every base role. An app's own roles (CompanyAdmin, Creator) are mapped in
15
+ -- the app's migrations-auth/.
16
+
17
+ INSERT INTO "apis" (id, name, "apiGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
18
+ SELECT encode(gen_random_bytes(12), 'hex'), v.name, v.grp, v.pub, true, '*', now(), now()
19
+ FROM (VALUES
20
+ ('POST /auth/api/resend-activation', '', true),
21
+ ('POST /auth/api/admin/users/:id/activate', 'users:edit', false),
22
+ ('GET /auth/api/invite-preview', '', true),
23
+ ('POST /auth/api/invite-accept', '', true),
24
+ ('POST /auth/api/sse-ticket', 'account:view', false)
25
+ ) AS v(name, grp, pub)
26
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" a WHERE a.name = v.name AND a."apiGroup" = v.grp);
27
+
28
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
29
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
30
+ FROM "roles" r CROSS JOIN "apis" a
31
+ WHERE r.name IN ('Super Admin', 'Admin')
32
+ AND a.name = 'POST /auth/api/admin/users/:id/activate' AND a."apiGroup" = 'users:edit'
33
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
34
+
35
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
36
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
37
+ FROM "roles" r CROSS JOIN "apis" a
38
+ WHERE r.name IN ('Super Admin', 'Admin', 'Editor', 'Viewer')
39
+ AND a.name = 'POST /auth/api/sse-ticket' AND a."apiGroup" = 'account:view'
40
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
41
+
42
+ -- The two public pages that go with them (the UI's /auth/resend-activation
43
+ -- and /auth/accept-invite), next to Login, Register and the rest from 0006.
44
+ INSERT INTO "uiPages" (id, name, "uiPagesGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
45
+ SELECT encode(gen_random_bytes(12), 'hex'), v.name, '', true, true, '*', now(), now()
46
+ FROM (VALUES ('Resend Activation'), ('Accept Invite')) AS v(name)
47
+ WHERE NOT EXISTS (SELECT 1 FROM "uiPages" p WHERE p.name = v.name AND p."uiPagesGroup" = '');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.1.8",
3
+ "version": "1.3.0",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [