@xeplr/auth 1.5.0 → 1.5.1

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
@@ -68,7 +68,7 @@ To act on auth tables from another service (invite a user, assign roles) while a
68
68
  var auth = require('@xeplr/auth').attach() // AUTH_DB_NAME + the connection env
69
69
  await auth.ready()
70
70
  await auth.model('UserRolesMapping').query().insert({ /* … */ })
71
- await auth.service.invite({ email, name, invitedBy, inviterName, appName })
71
+ await auth.service.invite({ email, name, invitedBy, inviterName, appName }) // → { id, isNew, isActivated, resent? } — not yet activated: the invite goes again
72
72
  ```
73
73
 
74
74
  ## Exports
@@ -292,6 +292,7 @@ Client code must read the header and replace its stored token, or the session en
292
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
293
  3. **Lost the mail?** `POST /resend-activation` sends a new link.
294
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
+ 5. **Nobody is left stuck.** Inviting an address whose account is **not activated** sends the invite **again** — a fresh link, the old one stops working (`invite()` answers `resent: true`); an activated account is left alone. And a completed **password reset activates** an account that never was: the reset link proves the address just as an activation or invite link does. Invited (no password until the reset): activated as accepting the invite would. Signed up: activated as the emailed link would, with the sign-up roles. A password set meanwhile does not block accepting an invite.
295
296
 
296
297
  ### `/auth/api`
297
298
 
@@ -300,13 +301,13 @@ Client code must read the header and replace its stored token, or the session en
300
301
  | `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
302
  | `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
303
  | `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) |
303
- | `GET /invite-preview` | — | `?token=…` → `{ email, name }` |
304
+ | `GET /invite-preview` | — | `?token=…` → `{ email, name }` for an account not yet activated (a password set by a reset meanwhile does not matter) |
304
305
  | `POST /invite-accept` | — | `{ token, password, name? }` → sets the password and activates |
305
306
  | `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 |
306
307
  | `POST /refresh` | — | `{ refreshToken }` → a new `{ accessToken, refreshToken, user, access }` |
307
308
  | `POST /logout` | — | `{ refreshToken }` → ends that session |
308
309
  | `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` |
310
+ | `POST /reset-password` | — | `{ token, newPassword }`; `400` once the link is older than `AUTH_RESET_TOKEN_EXPIRY_MINUTES`. Activates an account that was never activated (the link proves the address) |
310
311
  | `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims. With `x-verify-tenant` (`{ "l1": "<company>", "l2": "<workspace>" }`), `access` is as the user is there: their own roles plus the ones their membership gives them ([roles held in a company](#roles-held-in-a-company-or-workspace)). Not a member: `403 NOT_A_MEMBER`; unreadable: `400 BAD_TENANT` |
311
312
  | `GET /verify` | ✓ | the check every app's gate makes on every request — see [Every request is checked](#every-request-is-checked) |
312
313
  | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
@@ -379,22 +379,43 @@ async function login({ email, password }) {
379
379
  * activation token. Sends an "accept invite" email pointing the user to a page
380
380
  * where they set their own password and activate.
381
381
  *
382
- * Idempotent on email: if the user already exists, returns the existing user
383
- * (no email sent, no password reset). The caller can then layer additional
384
- * roles/mappings on top.
382
+ * On an email that already has an account:
383
+ * - activated: returned as it is — nothing sent, nothing changed;
384
+ * - NOT activated (never accepted, the link lost or broken): INVITED AGAIN —
385
+ * a fresh link replaces the old one and the email goes out again
386
+ * (`resent: true`). Nobody is left with an account they cannot get into.
387
+ * The caller can then layer additional roles/mappings on top (isNew only).
385
388
  */
386
389
  async function invite({ email, name, phoneNumber, invitedBy, inviterName, appName, knex }) {
387
390
  const UserM = knex ? User.bindKnex(knex) : User;
388
391
  const normalized = normalizeEmail(email);
389
392
 
390
393
  const existing = await UserM.query().findOne({ normalizedEmail: normalized });
394
+ if (existing && existing.isActivated) {
395
+ return {
396
+ id: existing.id,
397
+ email: existing.email,
398
+ name: existing.name,
399
+ isNew: false,
400
+ isActivated: true
401
+ };
402
+ }
391
403
  if (existing) {
404
+ const freshToken = crypto.randomBytes(32).toString('hex');
405
+ await UserM.query().findById(existing.id).patch({
406
+ activationToken: freshToken,
407
+ recordModifiedDate: formatDbDateTime(),
408
+ recordModifiedBy: invitedBy || existing.id
409
+ });
410
+ await sendInviteEmail(email, name || existing.name, inviterName, appName, freshToken);
411
+ await hooks.fire('user', 'update', existing.id);
392
412
  return {
393
413
  id: existing.id,
394
414
  email: existing.email,
395
415
  name: existing.name,
396
416
  isNew: false,
397
- isActivated: existing.isActivated
417
+ isActivated: false,
418
+ resent: true
398
419
  };
399
420
  }
400
421
 
@@ -422,12 +443,26 @@ async function invite({ email, name, phoneNumber, invitedBy, inviterName, appNam
422
443
  recordModifiedBy: inviter
423
444
  });
424
445
 
446
+ await sendInviteEmail(email, name, inviterName, appName, activationToken);
447
+
448
+ await hooks.fire('user', 'create', user.id);
449
+
450
+ return {
451
+ id: user.id,
452
+ email: user.email,
453
+ name: user.name,
454
+ isNew: true,
455
+ isActivated: false
456
+ };
457
+ }
458
+
459
+ /** The invite email: the link where they set their password and accept. */
460
+ async function sendInviteEmail(email, name, inviterName, appName, activationToken) {
425
461
  const inviteUrl = linkFor('invite');
426
462
  if (!inviteUrl) {
427
463
  throw new Error('AUTH_INVITE_URL is required to send invite emails (the full address of your ' +
428
464
  'accept-invite page, e.g. http://localhost:19100/auth/accept-invite).');
429
465
  }
430
-
431
466
  const acceptLink = withToken(inviteUrl, activationToken);
432
467
  const app = appName || 'the app';
433
468
  const subject = 'You have been invited to ' + app;
@@ -436,30 +471,19 @@ async function invite({ email, name, phoneNumber, invitedBy, inviterName, appNam
436
471
  + (inviterName ? '<p>' + inviterName + ' has invited you to join ' + app + '.</p>' : '<p>You have been invited to join ' + app + '.</p>')
437
472
  + '<p>Click below to set your password and accept the invite:</p>'
438
473
  + '<p><a href="' + acceptLink + '">' + acceptLink + '</a></p>';
439
-
440
474
  await sendEmail(email, subject, html);
441
-
442
- await hooks.fire('user', 'create', user.id);
443
-
444
- return {
445
- id: user.id,
446
- email: user.email,
447
- name: user.name,
448
- isNew: true,
449
- isActivated: false
450
- };
451
475
  }
452
476
 
453
477
  /**
454
478
  * Preview an invite — returns invitee info if the token matches a pending
455
- * invite (user exists, is not activated, and has no password set yet).
479
+ * invite (user exists and is not activated). A password set meanwhile — by a
480
+ * reset, say — does not stop it: accepting sets the password again.
456
481
  */
457
482
  async function previewInvite(token, options = {}) {
458
483
  const UserM = options.knex ? User.bindKnex(options.knex) : User;
459
484
  const user = await UserM.query().findOne({ activationToken: token });
460
485
  if (!user) throw new Error('Invalid or expired invite');
461
486
  if (user.isActivated) throw new Error('Invite already accepted');
462
- if (user.pwd) throw new Error('This account already has a password — use the activation link instead');
463
487
 
464
488
  return { email: user.email, name: user.name };
465
489
  }
@@ -561,6 +585,7 @@ async function resetPassword({ token, newPassword }) {
561
585
  }
562
586
 
563
587
  const { hash, salt } = await hashPassword(newPassword);
588
+ const invited = !user.pwd;
564
589
 
565
590
  await User.query().findById(user.id).patch({
566
591
  pwd: hash,
@@ -570,6 +595,21 @@ async function resetPassword({ token, newPassword }) {
570
595
  recordModifiedDate: formatDbDateTime()
571
596
  });
572
597
 
598
+ // A RESET PROVES THE ADDRESS, as an activation or invite link does — the
599
+ // link was opened from that inbox. So an account never activated is
600
+ // activated now, instead of being left with a password it cannot sign in
601
+ // with. Invited (no password until now): as accepting the invite does — its
602
+ // roles came with the invite. Signed up: as the activation link does — with
603
+ // the sign-up roles.
604
+ if (!user.isActivated) {
605
+ if (invited) {
606
+ const now = formatDbDateTime();
607
+ await User.query().findById(user.id).patch({ isActivated: true, activatedOn: now, activatedBy: user.id, activationToken: null, recordModifiedDate: now });
608
+ } else {
609
+ await markActivated(user, user.id);
610
+ }
611
+ }
612
+
573
613
  await destroyAllUserSessions(user.id);
574
614
  await clearUserAccess(user.id);
575
615
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.5.0",
3
+ "version": "1.5.1",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [