@xeplr/auth 1.5.3 → 1.6.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
@@ -87,6 +87,7 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName }) //
87
87
  | `requireRole(...names)` | 403 unless `req.user.roles` holds one of the names; use after `authMiddleware` |
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
+ | `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` |
90
91
  | `accessService` | `getUserAccess`, `userApiState`, `userHasApiAccess`, `apiStateFor`, `ACCESS_STATES`, `getApiRule`, `getPublicItems`, `clearUserAccess`, `clearAccessRules`, `clearAllAccess` |
91
92
  | `sessionService` | `createSession`, `getSession`, `validateAccessToken`, `slideAccessToken`, `rotateSession`, `destroySession`, `destroyAllUserSessions` |
92
93
  | `ticketService` | `issueTicket`, `consumeTicket` — single-use 30-second tickets for SSE / WebSocket |
@@ -136,6 +137,10 @@ Everything in `requiredEnv`, plus a connection. `requiredEnv` includes the sign-
136
137
  | `REDIS_HOST` / `REDIS_PORT` | `127.0.0.1` / `6379` | the session store |
137
138
  | `REDIS_PASSWORD` / `REDIS_DB` | none / `0` | read by `@xeplr/utils`' cache |
138
139
  | `UPLOAD_DIR` | `./uploads` | where avatar uploads are written |
140
+ | `AUTH_LOGIN_METHODS` | `password` | the ways in, comma-separated: `password`, `email_otp` (a code by email instead of a password), `phone_otp` (a code by text to a **verified** mobile number) — [details](#other-ways-in-a-code-and-the-second-step) |
141
+ | `AUTH_2FA` | `off` | the second step: `off`, `optional` (each person turns it on in their profile) or `required` (everyone; with nothing set up, an emailed code). `required` refuses to start when mail is known not to work |
142
+ | `AUTH_2FA_METHODS` | `authenticator,email` | what a second step may use: `authenticator`, `email`, `sms`. **`email` is always offered**, listed or not — the way back in for someone who cannot open their app |
143
+ | `AUTH_2FA_TRUST_DAYS` | `0` | "Trust this device" for this many days; `0` never offers it |
139
144
  | `EMAIL_PROVIDER` | not configured | `smtp`, `brevo`, `aws` or `azure` |
140
145
  | `SMTP_HOST`, `SMTP_PORT` (587), `SMTP_USER`, `SMTP_PASS`, `SMTP_FROM`, `SMTP_SECURE`, … | | SMTP settings, read by `@xeplr/utils` |
141
146
  | `BREVO_API_KEY`, `BREVO_FROM_EMAIL`, `BREVO_FROM_NAME` | | Brevo |
@@ -263,6 +268,44 @@ It is created **once**, when migrations first run on that database:
263
268
 
264
269
  To add or change an account afterwards, use the app (or `seedSuperAdmin(knex, { email, password })` from your own migration code).
265
270
 
271
+ ## Other ways in: a code, and the second step
272
+
273
+ Off unless turned on: with none of the settings below, signing in is email and password, as before. `lib/signInSteps.js`; codes are `@xeplr/utils` `otp` (Redis, 5 minutes, 5 wrong tries) and authenticator codes `@xeplr/utils` `totp`.
274
+
275
+ **A code instead of a password** — `AUTH_LOGIN_METHODS=password,email_otp,phone_otp`.
276
+
277
+ - The email or number finds an **existing** account. A code never creates one: someone who signed up with email, adds their mobile number and later signs in with it is signed in to that same account.
278
+ - **Only a verified number signs in.** A number is verified from the profile (`/request-phone-otp`, `/verify-phone-otp`), signed in. Otherwise anyone could type another person's number onto their own account and sign in as them.
279
+ - **One account per verified number** — refused with `409 PHONE_TAKEN`, and held in the database by a unique index (`users_verified_phone_unique`, migration `0015`). An install that already has duplicates starts anyway, with a notice, and the check in code still applies.
280
+ - A number typed **without its country code** (`9876543210`) finds the verified number ending in those digits — only when exactly one account has such a number.
281
+ - `/login/code` answers the same whether or not anything matched, so it cannot be used to learn who has an account.
282
+ - **Five codes per person per 15 minutes**, every kind counted together.
283
+
284
+ **The second step** — `AUTH_2FA=optional|required`, `AUTH_2FA_METHODS=authenticator,email,sms`.
285
+
286
+ - The first step answers `{ secondStep: { ticket, method, methods, sentTo, trustDays } }` instead of tokens. When the method is email or text, the code has already gone out. The ticket lives 10 minutes.
287
+ - `/login/second-step/verify` turns the ticket into the usual tokens.
288
+ - **Email is always offered.** Someone who cannot open their authenticator app asks for a code by email instead (`/login/second-step/send`).
289
+ - **The second step never asks again for what the first step proved.** Signing in with an emailed code is not followed by another email. If nothing else is set up, the sign-in code counts. If an authenticator app is set up, it is asked.
290
+ - `required` with nothing set up uses an emailed code.
291
+ - An authenticator code works **once**: the same six digits are refused a second time.
292
+ - **10 wrong authenticator codes per person per 15 minutes**, counted across every sign-in, lock the app out for the rest of that window. Each sign-in also allows only 5 wrong codes. An emailed code still works during the lockout. Without this limit, someone holding the password could keep starting new sign-ins to get more guesses.
293
+ - The authenticator secret is stored **encrypted with `ENCRYPTION_KEY`**.
294
+ - **No backup codes.** A person who lost their phone gets a code by email. If that fails too, an admin resets their second step (`POST /admin/users/:id/two-factor/reset`).
295
+ - **Trust this device** (`AUTH_2FA_TRUST_DAYS`): the device keeps a random `trustToken` and sends it with the first step.
296
+ - Redis keeps only its hash, the user, and when their second step last changed.
297
+ - Changing method, setting up the app again, or an admin reset makes every trusted device ask again.
298
+
299
+ **Text messages need an SMS provider**, registered by the host with `@xeplr/utils` `sms.register()` before `boot()`. With `phone_otp`, or `sms` as a second step, and no provider, the service **refuses to start**, naming the setting. An unknown value in any of these settings is refused the same way (`AUTH_SETTING_INVALID`), so a typo cannot quietly turn the second step off.
300
+
301
+ **Who reaches the routes** (migration `0015`):
302
+ - The public ones carry no group.
303
+ - The `account:*` ones go to every role that can already open its own profile.
304
+ - The reset goes to every role that can already activate a user by hand.
305
+ - This covers each app's own roles (BI's CompanyAdmin, Creator, Viewer) without a migration in the app.
306
+
307
+ `@xeplr/ui-account` 1.6 draws all of this on its sign-in and profile pages. **Turn `AUTH_2FA` on only with that version or newer**, because an older sign-in page does not know what to do with `{ secondStep }`.
308
+
266
309
  ## Sessions and tokens
267
310
 
268
311
  A session is one login on one device: a JWT **access token** (claims `id`, `email`, `name`, `roles`) and a random **refresh token**, both recorded in Redis.
@@ -324,7 +367,12 @@ await fetch(api + '/reports/r1/export', { method: 'POST', headers: {
324
367
  | `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) |
325
368
  | `GET /invite-preview` | — | `?token=…` → `{ email, name }` for an account not yet activated (a password set by a reset meanwhile does not matter) |
326
369
  | `POST /invite-accept` | — | `{ token, password, name? }` → sets the password and activates |
327
- | `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 |
370
+ | `POST /login` | — | `{ email, password, trustToken? }` → `{ accessToken, refreshToken, user, access }`, or `{ secondStep }` when a [second step](#other-ways-in-a-code-and-the-second-step) is asked; `403 METHOD_OFF` when `AUTH_LOGIN_METHODS` leaves out `password`; `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 |
371
+ | `GET /sign-in-options` | — | `{ methods, twoFactor, twoFactorMethods, trustDays }` — what the sign-in page offers |
372
+ | `POST /login/code` | — | `{ email }` or `{ phoneNumber }` → `{ sent: true, message }`, **the same answer whether or not an account matches**; a code is sent only to a real, active, activated account (a phone only when verified). `403 METHOD_OFF` when that way is off; `429 TOO_MANY_CODES` |
373
+ | `POST /login/code/verify` | — | `{ email \| phoneNumber, code, trustToken? }` → tokens, or `{ secondStep }`; `401 BAD_CODE` / `CODE_EXPIRED`, `429 TOO_MANY_TRIES` |
374
+ | `POST /login/second-step/send` | — | `{ ticket, method: 'email' \| 'sms' }` → `{ sent, method, sentTo }` — "send me a code by email instead" |
375
+ | `POST /login/second-step/verify` | — | `{ ticket, method, code, trustDevice? }` → tokens, plus `trustToken` when `trustDevice` and `AUTH_2FA_TRUST_DAYS` > 0; `401 SIGN_IN_EXPIRED` once the ticket is used, 10 minutes old, or after 5 wrong authenticator codes |
328
376
  | `POST /refresh` | — | `{ refreshToken }` → a new `{ accessToken, refreshToken, user, access }` |
329
377
  | `POST /logout` | — | `{ refreshToken }` → ends that session |
330
378
  | `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 |
@@ -334,8 +382,12 @@ await fetch(api + '/reports/r1/export', { method: 'POST', headers: {
334
382
  | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
335
383
  | `POST /profile/avatar` | ✓ | multipart `avatar`, an image up to 2 MB; stores the file name only — serving `UPLOAD_DIR` is the app's job |
336
384
  | `POST /change-password` | ✓ | `{ oldPassword, newPassword }`; ends every session |
337
- | `POST /request-phone-otp` | ✓ | `{ phoneNumber? }` — needs an SMS provider registered with `@xeplr/utils` |
338
- | `POST /verify-phone-otp` | ✓ | `{ code }` → `{ phoneVerified: true }` |
385
+ | `POST /request-phone-otp` | ✓ | `{ phoneNumber? }` — needs an SMS provider registered with `@xeplr/utils`. The number is stored cleaned (`+91 98765-43210` → `+919876543210`); `409 PHONE_TAKEN` when another account has it verified |
386
+ | `POST /verify-phone-otp` | ✓ | `{ code }` → `{ phoneVerified: true }`; `409 PHONE_TAKEN` if someone else verified it meanwhile |
387
+ | `GET /two-factor` | ✓ | `{ mode, methods, method, authenticator, phoneNumber, phoneVerified, trustDays, signIn }` — my second step |
388
+ | `POST /two-factor/authenticator` | ✓ | `{ issuer? }` → `{ secret, otpauthUrl }` for the app (QR or typed); held 15 minutes, not used until confirmed |
389
+ | `POST /two-factor/authenticator/confirm` | ✓ | `{ code }` from the app → stores the secret (encrypted) and makes the app my second step |
390
+ | `POST /two-factor/method` | ✓ | `{ method: 'authenticator' \| 'email' \| 'sms' \| null }`; `null` turns it off (`409 REQUIRED` when `AUTH_2FA=required`); `409 NOT_SET_UP` for an app not set up or a number not verified |
339
391
  | `POST /sse-ticket` | ✓ | `{ scopes? }` (default `['user:me:*']`) → `{ ticket, expiresIn: 30 }` |
340
392
 
341
393
  ### `/auth/api/admin`
@@ -344,7 +396,8 @@ await fetch(api + '/reports/r1/export', { method: 'POST', headers: {
344
396
 
345
397
  | route | |
346
398
  |---|---|
347
- | `GET /users` | users with their roles, `isActivated`, and `invitePending` (invited, no password set yet — they activate by accepting the invite) |
399
+ | `GET /users` | users with their roles, `isActivated`, `twoFactorMethod`, `hasAuthenticator`, and `invitePending` (invited, no password set yet — they activate by accepting the invite) |
400
+ | `POST /users/:id/two-factor/reset` | `users:edit` — clears someone's second step (method and authenticator); every device they trusted asks again. For a person who lost their phone |
348
401
  | `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 |
349
402
  | `GET /roles` | `[{ id, name, scope, mtId1 }]`: the current company's roles and the generic ones; system roles only for Super Admin |
350
403
  | `GET /access-items` | `{ apis, pages, elements, menus }`, each with its roles |
@@ -665,6 +718,16 @@ Hooks run in the process that did the work — register them in the same script
665
718
  npm test # node --test test/*.test.js
666
719
  ```
667
720
 
721
+ `test/signInSteps.test.js` covers signing in with a code and the second step, against local PostgreSQL and Redis, real mail and a real SMS provider call:
722
+ - an emailed code: the same answer for anyone, used once, five per 15 minutes;
723
+ - a mobile number: verified only, one account per number, typed without `+91`;
724
+ - the authenticator: set up, stored encrypted, a code good once;
725
+ - an emailed code instead of the app;
726
+ - `required` with nothing set up;
727
+ - never asked twice for the same proof;
728
+ - a trusted device, and an admin reset;
729
+ - the settings refused by name, and text messages with no provider.
730
+
668
731
  `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.
669
732
 
670
733
  `test/scopedRoles.test.js` checks roles held in a company or workspace (local PostgreSQL and Redis; skipped without either): the company a Viewer created lets them import there and only there (`HIDDEN` naming none, or another company where they are a plain member; `NOT_A_MEMBER` naming a stranger's); a workspace role counts in that workspace and the company role in all of its workspaces; `/me` answers as the user is in the company named; a role taken away is gone after `clearUserAccess`; an app running auth in-process (`accessMiddleware`) reads the company from the request.
package/index.js CHANGED
@@ -24,6 +24,7 @@ const mtMembershipMiddleware = require('./lib/mtMembershipMiddleware');
24
24
  const createAuthRouter = require('./lib/authRouter');
25
25
  const createAdminRouter = require('./lib/adminRouter');
26
26
  const systemScope = require('./lib/systemScope');
27
+ const signInSteps = require('./lib/signInSteps');
27
28
  const models = require('./models');
28
29
 
29
30
  let _initialized = false;
@@ -218,6 +219,24 @@ async function boot() {
218
219
  // reset) cannot be sent, and the banner says so rather than the first
219
220
  // person to register finding out.
220
221
  var email = await emailStatus();
222
+
223
+ // The ways in (AUTH_LOGIN_METHODS, AUTH_2FA…): a typo or a text-message
224
+ // setting with no SMS provider stops the start, named — never a sign-in
225
+ // that quietly skips its second step.
226
+ var signIn;
227
+ try {
228
+ signIn = signInSteps.checkSettings();
229
+ } catch (err) {
230
+ console.error('\n[xeplr-auth] ' + err.message + '\n');
231
+ process.exit(1);
232
+ }
233
+ // A second step falls back to an emailed code; with mail known NOT to work,
234
+ // anyone without an authenticator app would be shut out.
235
+ if (signIn.mode === 'required' && email.ok === false && !email.unknown) {
236
+ console.error('\n[xeplr-auth] AUTH_2FA=required needs working email: the emailed code is everyone\'s');
237
+ console.error(' way in until they set up an authenticator app. ' + email.detail + '\n');
238
+ process.exit(1);
239
+ }
221
240
  // Registration and reset refuse up front when mail is known not to work,
222
241
  // instead of creating an account whose link never goes out.
223
242
  authService.configureEmailStatus(email.unknown ? null : email.ok);
@@ -241,7 +260,7 @@ async function boot() {
241
260
  }
242
261
  });
243
262
 
244
- banner(email);
263
+ banner(email, signIn);
245
264
  if (!email.ok) warnNoEmail(email);
246
265
  return server;
247
266
  }
@@ -271,7 +290,7 @@ function describeEmail(email) {
271
290
 
272
291
  // Startup summary — the EFFECTIVE config (defaults resolved) so you can see what
273
292
  // the service is actually running with. Secrets are masked, never printed.
274
- function banner(email) {
293
+ function banner(email, signIn) {
275
294
  var set = function (v) { return v ? '✓ set' : '✗ MISSING'; };
276
295
  var rows = [
277
296
  ['port', process.env.AUTH_PORT || '19001'],
@@ -288,6 +307,9 @@ function banner(email) {
288
307
  ['redis', (process.env.REDIS_HOST || 'localhost') + ':' + (process.env.REDIS_PORT || '6379')],
289
308
  ['redis prefix', redisPrefix()],
290
309
  ['email', describeEmail(email)],
310
+ ['sign in with', signIn ? signIn.login.join(', ') : '?'],
311
+ ['second step', signIn ? (signIn.mode === 'off' ? 'off' : signIn.mode + ' — ' + signIn.methods.join(', ')) : '?'],
312
+ ['trust a device', signIn ? (signIn.trustDays ? signIn.trustDays + ' days' : 'never') : '?'],
291
313
  // Names the VARIABLE it resolved through, not just "set" — with a shared
292
314
  // default and a per-service override, "which server am I on" is otherwise
293
315
  // a guess.
@@ -461,6 +483,9 @@ module.exports = {
461
483
  authHelper,
462
484
  seedSuperAdmin,
463
485
  authService,
486
+ // Code sign-in and the second step (lib/signInSteps.js): settings(),
487
+ // signInOptions(), resetTwoFactor(userId, adminId), cleanPhone() …
488
+ signInSteps,
464
489
  accessService,
465
490
  sessionService,
466
491
  ticketService,
@@ -7,6 +7,7 @@ var authMiddleware = require('./authMiddleware');
7
7
  var hooks = require('./hooks');
8
8
  var { grantRoles } = require('./userRoles');
9
9
  var { adminActivate } = require('./authService');
10
+ var { resetTwoFactor } = require('./signInSteps');
10
11
  var { isSuperAdmin, systemScopeGuard, SUPER_ADMIN_ROLE } = require('./systemScope');
11
12
  var { tenantOf, visibleTenants, GENERIC } = require('./tenant');
12
13
  var User = require('../models/User');
@@ -104,7 +105,8 @@ function createAdminRouter() {
104
105
  // invitePending: invited and has not set a password yet — activated by
105
106
  // accepting the invite, never by an admin. Only the fact leaves here.
106
107
  var users = await User.query()
107
- .select('id', 'email', 'name', 'isActive', 'isActivated', User.raw('("pwd" IS NULL) as "invitePending"'))
108
+ .select('id', 'email', 'name', 'isActive', 'isActivated', 'twoFactorMethod',
109
+ User.raw('("pwd" IS NULL) as "invitePending"'), User.raw('("totpSecret" IS NOT NULL) as "hasAuthenticator"'))
108
110
  .withGraphFetched('roles');
109
111
  res.json(users);
110
112
  } catch (err) {
@@ -132,6 +134,21 @@ function createAdminRouter() {
132
134
  }
133
135
  });
134
136
 
137
+ // ─── Reset someone's second step ───
138
+ // For a person who lost the phone with their authenticator app and cannot
139
+ // get a code by email either. Clears their method and authenticator; every
140
+ // device they trusted asks again. If the server requires a second step,
141
+ // their next sign-in uses an emailed code until they set one up again.
142
+ router.post('/users/:id/two-factor/reset', async function(req, res) {
143
+ try {
144
+ var result = await resetTwoFactor(req.params.id, req.user ? req.user.id : null);
145
+ res.json({ message: 'Two-step sign-in reset', result: result });
146
+ } catch (err) {
147
+ if (err.code === 'USER_NOT_FOUND') return res.status(404).json({ error: err.message, code: err.code });
148
+ res.status(500).json({ error: 'Something went wrong' });
149
+ }
150
+ });
151
+
135
152
  // ─── Roles ───
136
153
  router.get('/roles', async function(req, res) {
137
154
  try {
package/lib/authRouter.js CHANGED
@@ -4,6 +4,7 @@ const { register, resendActivation, activate, previewInvite, acceptInvite, login
4
4
  const { getUserAccess, requestApiState } = require('./accessService');
5
5
  const { getSession, rotateSession, destroySession } = require('./sessionService');
6
6
  const { issueTicket } = require('./ticketService');
7
+ const signInSteps = require('./signInSteps');
7
8
  const authMiddleware = require('./authMiddleware');
8
9
  const { refusedTenant, readTenants } = require('./mtMembershipMiddleware');
9
10
  const { accessGate } = require('./accessMiddleware');
@@ -14,12 +15,18 @@ const { accessGate } = require('./accessMiddleware');
14
15
  const signedInAndAllowed = [authMiddleware, accessGate()];
15
16
  const User = require('../models/User');
16
17
 
17
- // Avatar uploads — local disk by default (FileUploader's own default:
18
- // process.env.UPLOAD_DIR or ./uploads). Auth only persists the resulting
18
+ // Avatar uploads — local disk: process.env.UPLOAD_DIR or ./uploads. Auth only persists the resulting
19
19
  // path on the user; serving it back over HTTP is the consuming app's concern
20
20
  // (same as any other uploaded asset), so wire a static route to the same
21
21
  // directory wherever it makes sense for your deployment.
22
- const avatarUploader = new FileUploader({ allowedTypes: ['image/*'], maxSize: 2 * 1024 * 1024 });
22
+ // Named here because @xeplr/utils 2 defaults an uploader to the requesting
23
+ // company's folder, and a profile picture belongs to a person, not a company:
24
+ // the same place as before — UPLOAD_DIR, or ./uploads.
25
+ const avatarUploader = new FileUploader({
26
+ allowedTypes: ['image/*'],
27
+ maxSize: 2 * 1024 * 1024,
28
+ destination: process.env.UPLOAD_DIR || './uploads'
29
+ });
23
30
 
24
31
  function logError(req, err) {
25
32
  if (req.log) req.log.error(err.message, { stack: err.stack });
@@ -29,7 +36,34 @@ function logError(req, err) {
29
36
  // setting or cannot send mail. 503 with the reason, so whoever runs the app
30
37
  // sees which setting to fix instead of a bare "Something went wrong".
31
38
  var SERVER_NOT_READY = ['EMAIL_NOT_SET_UP', 'EMAIL_SEND_FAILED', 'ACTIVATION_URL_NOT_SET', 'RESET_URL_NOT_SET',
32
- 'REGISTER_ROLES_NOT_SET', 'REGISTER_ROLES_UNKNOWN', 'REGISTER_ROLES_SYSTEM'];
39
+ 'REGISTER_ROLES_NOT_SET', 'REGISTER_ROLES_UNKNOWN', 'REGISTER_ROLES_SYSTEM', 'AUTH_SETTING_INVALID', 'SMS_NOT_SET_UP'];
40
+
41
+ // What a refusal from signing in with a code, or the second step, answers.
42
+ var STEP_STATUS = {
43
+ BAD_REQUEST: 400, BAD_METHOD: 400, BAD_CODE: 401, CODE_EXPIRED: 401, TOO_MANY_TRIES: 429,
44
+ TOO_MANY_CODES: 429, SIGN_IN_EXPIRED: 401, METHOD_OFF: 403, REQUIRED: 409, NOT_SET_UP: 409,
45
+ SETUP_EXPIRED: 410, USER_NOT_FOUND: 404, PHONE_TAKEN: 409
46
+ };
47
+
48
+ function sendStepError(req, res, err) {
49
+ if (sendNotReady(res, err)) { logError(req, err); return; }
50
+ var status = STEP_STATUS[err.code];
51
+ if (status) return res.status(status).json({ error: err.message, code: err.code });
52
+ logError(req, err);
53
+ res.status(500).json({ error: 'Something went wrong' });
54
+ }
55
+
56
+ // An SMS provider's failure ("Failed to send OTP: …") is the server's problem
57
+ // to fix, not the person's; it is not one of ours, so it arrives without a code.
58
+ function sendFailure(err) {
59
+ if (!err.code && /^Failed to send OTP/.test(err.message || '')) {
60
+ var e = new Error('Could not send the code by text message: ' + err.message.replace(/^Failed to send OTP: /, ''));
61
+ e.code = 'SMS_SEND_FAILED';
62
+ return e;
63
+ }
64
+ return err;
65
+ }
66
+ SERVER_NOT_READY.push('SMS_SEND_FAILED');
33
67
 
34
68
  function sendNotReady(res, err) {
35
69
  if (SERVER_NOT_READY.indexOf(err.code) === -1) return false;
@@ -122,13 +156,14 @@ function createAuthRouter(options = {}) {
122
156
 
123
157
  router.post('/login', async function(req, res) {
124
158
  try {
125
- const { email, password } = req.body;
159
+ const { email, password, trustToken } = req.body;
126
160
 
127
161
  if (!email || !password) {
128
162
  return res.status(400).json({ error: 'Email and password are required' });
129
163
  }
130
164
 
131
- const result = await login({ email, password });
165
+ // Tokens — or { secondStep: { ticket, … } } when a second step is asked.
166
+ const result = await login({ email, password, trustToken });
132
167
  res.json(result);
133
168
  } catch (err) {
134
169
  logError(req, err);
@@ -141,7 +176,67 @@ function createAuthRouter(options = {}) {
141
176
  if (err.message === 'Invalid email or password' || err.message === 'Account is deactivated') {
142
177
  return res.status(401).json({ error: err.message });
143
178
  }
144
- res.status(500).json({ error: 'Something went wrong' });
179
+ sendStepError(req, res, sendFailure(err));
180
+ }
181
+ });
182
+
183
+ // ── Other ways in: a code instead of a password, and the second step ──
184
+ // See lib/signInSteps.js. All public: they are how a caller gets a token.
185
+
186
+ // Which ways in this server offers — the sign-in page draws itself from it.
187
+ router.get('/sign-in-options', function(req, res) {
188
+ try {
189
+ res.json(signInSteps.signInOptions());
190
+ } catch (err) {
191
+ sendStepError(req, res, err);
192
+ }
193
+ });
194
+
195
+ // { email } or { phoneNumber } → a code, if an account matches. The same
196
+ // answer either way, so it cannot be used to find out who has an account.
197
+ router.post('/login/code', async function(req, res) {
198
+ try {
199
+ var body = req.body || {};
200
+ await signInSteps.requestSignInCode({ email: body.email, phoneNumber: body.phoneNumber });
201
+ res.json({ sent: true, message: 'If an account matches, a code has been sent.' });
202
+ } catch (err) {
203
+ sendStepError(req, res, sendFailure(err));
204
+ }
205
+ });
206
+
207
+ // { email | phoneNumber, code, trustToken? } → tokens, or { secondStep }.
208
+ router.post('/login/code/verify', async function(req, res) {
209
+ try {
210
+ var body = req.body || {};
211
+ if (!body.code) return res.status(400).json({ error: 'code is required', code: 'BAD_REQUEST' });
212
+ res.json(await signInSteps.verifySignInCode({
213
+ email: body.email, phoneNumber: body.phoneNumber, code: body.code, trustToken: body.trustToken
214
+ }));
215
+ } catch (err) {
216
+ sendStepError(req, res, sendFailure(err));
217
+ }
218
+ });
219
+
220
+ // { ticket, method: 'email' | 'sms' } → a (new) second-step code that way.
221
+ router.post('/login/second-step/send', async function(req, res) {
222
+ try {
223
+ var body = req.body || {};
224
+ res.json(await signInSteps.sendSecondStepCode({ ticket: body.ticket, method: body.method }));
225
+ } catch (err) {
226
+ sendStepError(req, res, sendFailure(err));
227
+ }
228
+ });
229
+
230
+ // { ticket, method, code, trustDevice? } → tokens (+ trustToken when asked).
231
+ router.post('/login/second-step/verify', async function(req, res) {
232
+ try {
233
+ var body = req.body || {};
234
+ if (!body.code || !body.method) return res.status(400).json({ error: 'method and code are required', code: 'BAD_REQUEST' });
235
+ res.json(await signInSteps.verifySecondStep({
236
+ ticket: body.ticket, method: body.method, code: body.code, trustDevice: Boolean(body.trustDevice)
237
+ }));
238
+ } catch (err) {
239
+ sendStepError(req, res, err);
145
240
  }
146
241
  });
147
242
 
@@ -378,6 +473,7 @@ function createAuthRouter(options = {}) {
378
473
  res.json(result);
379
474
  } catch (err) {
380
475
  logError(req, err);
476
+ if (err.code === 'PHONE_TAKEN') return res.status(409).json({ error: err.message, code: err.code });
381
477
  res.status(400).json({ error: err.message });
382
478
  }
383
479
  });
@@ -389,10 +485,49 @@ function createAuthRouter(options = {}) {
389
485
  res.json(result);
390
486
  } catch (err) {
391
487
  logError(req, err);
488
+ if (err.code === 'PHONE_TAKEN') return res.status(409).json({ error: err.message, code: err.code });
392
489
  res.status(400).json({ error: err.message });
393
490
  }
394
491
  });
395
492
 
493
+ // ── My own second step ──
494
+ router.get('/two-factor', signedInAndAllowed, async function(req, res) {
495
+ try {
496
+ res.json(await signInSteps.twoFactorStatus(req.user.id));
497
+ } catch (err) {
498
+ sendStepError(req, res, err);
499
+ }
500
+ });
501
+
502
+ // { issuer? } → { secret, otpauthUrl } for the app (a QR code, or typed in).
503
+ // Not in use until a code from the app confirms it.
504
+ router.post('/two-factor/authenticator', signedInAndAllowed, async function(req, res) {
505
+ try {
506
+ res.json(await signInSteps.startAuthenticator(req.user.id, req.body && req.body.issuer));
507
+ } catch (err) {
508
+ sendStepError(req, res, err);
509
+ }
510
+ });
511
+
512
+ router.post('/two-factor/authenticator/confirm', signedInAndAllowed, async function(req, res) {
513
+ try {
514
+ if (!req.body || !req.body.code) return res.status(400).json({ error: 'code is required', code: 'BAD_REQUEST' });
515
+ res.json(await signInSteps.confirmAuthenticator(req.user.id, req.body.code));
516
+ } catch (err) {
517
+ sendStepError(req, res, err);
518
+ }
519
+ });
520
+
521
+ // { method: 'authenticator' | 'email' | 'sms' | null } — null turns it off
522
+ // (refused when AUTH_2FA=required).
523
+ router.post('/two-factor/method', signedInAndAllowed, async function(req, res) {
524
+ try {
525
+ res.json(await signInSteps.chooseMethod(req.user.id, req.body ? req.body.method : null));
526
+ } catch (err) {
527
+ sendStepError(req, res, err);
528
+ }
529
+ });
530
+
396
531
  // ── SSE ticket ────────────────────────────────────────────────────────
397
532
  //
398
533
  // Mints a short-lived, single-use ticket so a browser can open an
@@ -3,10 +3,11 @@ const { sendEmail, configureEmail, formatDbDateTime, otp } = require('@xeplr/uti
3
3
  const { normalizeEmail } = require('@xeplr/utils/isomorphic');
4
4
  const { generateId, hashPassword, comparePassword } = require('./authHelper');
5
5
  const User = require('../models/User');
6
- const { getUserAccess, clearUserAccess } = require('./accessService');
7
- const { createSession, destroyAllUserSessions } = require('./sessionService');
6
+ const { clearUserAccess } = require('./accessService');
7
+ const { destroyAllUserSessions } = require('./sessionService');
8
8
  const hooks = require('./hooks');
9
9
  const { grantRoles, registerRoleIds, refusal } = require('./userRoles');
10
+ const signInSteps = require('./signInSteps');
10
11
 
11
12
  // WHERE THE LINKS IN OUR EMAILS POINT.
12
13
  //
@@ -318,7 +319,14 @@ async function adminActivate(userId, adminId) {
318
319
  return { id: user.id, email: user.email, name: user.name, isActivated: true };
319
320
  }
320
321
 
321
- async function login({ email, password }) {
322
+ /**
323
+ * Email and password. When a second step is asked (AUTH_2FA) and this device
324
+ * is not trusted, the answer is { secondStep: { ticket, method, methods,
325
+ * sentTo, trustDays } } instead of tokens — see lib/signInSteps.js.
326
+ */
327
+ async function login({ email, password, trustToken }) {
328
+ signInSteps.requireLoginMethod(signInSteps.settings(), 'password', 'Signing in with a password');
329
+
322
330
  const normalized = normalizeEmail(email);
323
331
  const user = await User.query()
324
332
  .findOne({ normalizedEmail: normalized })
@@ -345,33 +353,9 @@ async function login({ email, password }) {
345
353
  throw new Error('NOT_ACTIVATED');
346
354
  }
347
355
 
348
- // Pack role names into the JWT so middleware (e.g. requireSuperAdmin)
349
- // can gate without a per-request DB lookup.
350
- const tokenUser = {
351
- id: user.id,
352
- email: user.email,
353
- name: user.name,
354
- roles: (user.roles || []).map(function(r) { return r.name; })
355
- };
356
-
357
- const { accessToken, refreshToken } = await createSession(tokenUser);
358
-
359
- await clearUserAccess(user.id);
360
- const access = await getUserAccess(user.id);
361
-
362
- await hooks.fire('user', 'login', user.id);
363
-
364
- return {
365
- accessToken,
366
- refreshToken,
367
- user: {
368
- id: user.id,
369
- email: user.email,
370
- name: user.name,
371
- isActivated: user.isActivated
372
- },
373
- access
374
- };
356
+ // Role names ride in the JWT so middleware (e.g. requireSuperAdmin) can gate
357
+ // without a per-request DB lookup — signInSteps.issueSession packs them.
358
+ return signInSteps.afterFirstStep(user, 'password', trustToken);
375
359
  }
376
360
 
377
361
  /**
@@ -631,10 +615,13 @@ async function requestPhoneOtp(userId, phoneNumber) {
631
615
  const user = await User.query().findById(userId);
632
616
  if (!user) throw new Error('User not found');
633
617
 
634
- const targetPhone = phoneNumber || user.phoneNumber;
618
+ const targetPhone = signInSteps.cleanPhone(phoneNumber || user.phoneNumber);
635
619
  if (!targetPhone) throw new Error('phoneNumber is required');
620
+ if (await signInSteps.phoneTakenByOther(userId, targetPhone)) {
621
+ throw refusal('PHONE_TAKEN', 'This number is already verified on another account');
622
+ }
636
623
 
637
- if (phoneNumber && phoneNumber !== user.phoneNumber) {
624
+ if (targetPhone !== signInSteps.cleanPhone(user.phoneNumber)) {
638
625
  // Changing the number on file invalidates any prior verification.
639
626
  await User.query().findById(userId).patch({
640
627
  phoneNumber: targetPhone,
@@ -656,6 +643,12 @@ async function verifyPhoneOtp(userId, code) {
656
643
  if (!user) throw new Error('User not found');
657
644
  if (!user.phoneNumber) throw new Error('No phone number on file — request a code first');
658
645
 
646
+ // One person per verified number — signing in by mobile finds the account
647
+ // by it. Checked again here: someone else may have verified it meanwhile.
648
+ if (await signInSteps.phoneTakenByOther(userId, user.phoneNumber)) {
649
+ throw refusal('PHONE_TAKEN', 'This number is already verified on another account');
650
+ }
651
+
659
652
  const result = await otp.verifyOtp(user.phoneNumber, code);
660
653
  if (!result.success) {
661
654
  const messages = {
@@ -712,9 +705,12 @@ async function updateProfile(userId, fields) {
712
705
  data.name = fields.name;
713
706
  }
714
707
 
715
- if (fields.phoneNumber !== undefined && fields.phoneNumber !== user.phoneNumber) {
716
- data.phoneNumber = fields.phoneNumber;
717
- data.phoneVerified = false;
708
+ if (fields.phoneNumber !== undefined) {
709
+ const cleaned = signInSteps.cleanPhone(fields.phoneNumber) || null;
710
+ if (cleaned !== (signInSteps.cleanPhone(user.phoneNumber) || null)) {
711
+ data.phoneNumber = cleaned;
712
+ data.phoneVerified = false;
713
+ }
718
714
  }
719
715
 
720
716
  if (fields.email !== undefined) {
@@ -0,0 +1,546 @@
1
+ /**
2
+ * SIGNING IN WITH A CODE, AND THE SECOND STEP.
3
+ *
4
+ * Two things, sharing one code store (@xeplr/utils otp, in Redis) and one
5
+ * idea: a code proves you hold an inbox, a phone, or an authenticator app.
6
+ *
7
+ * 1. A code INSTEAD of a password — AUTH_LOGIN_METHODS email_otp / phone_otp.
8
+ * The address or number finds an EXISTING account; a code never creates
9
+ * one. A mobile number counts only once it is verified on the account
10
+ * (from the profile), so nobody can type someone else's number onto their
11
+ * own account and sign in as them — and a verified number belongs to one
12
+ * account only.
13
+ *
14
+ * 2. A code AFTER the first step (two-factor) — AUTH_2FA off | optional |
15
+ * required, AUTH_2FA_METHODS authenticator,email,sms. The first step
16
+ * gives a short-lived ticket instead of tokens; the second step turns the
17
+ * ticket into tokens. EMAIL IS ALWAYS OFFERED: someone who cannot open
18
+ * their authenticator app can have a code mailed instead. An admin can
19
+ * reset a person's second step (POST /admin/users/:id/two-factor/reset).
20
+ *
21
+ * The second step never asks again for what the first step already proved:
22
+ * signing in with an emailed code does not then mail another one. When
23
+ * nothing else is set up, the sign-in code counts.
24
+ *
25
+ * "Trust this device" (AUTH_2FA_TRUST_DAYS, 0 = never offered): the device
26
+ * keeps a random token; Redis keeps its hash, the user and when their second
27
+ * step last changed. An admin reset, or any change of method, makes every
28
+ * trusted device ask again.
29
+ */
30
+ var crypto = require('crypto');
31
+ var utils = require('@xeplr/utils');
32
+ var { encrypt, decrypt } = require('@xeplr/utils/isomorphic/crypto');
33
+ var { normalizeEmail } = require('@xeplr/utils/isomorphic');
34
+ var User = require('../models/User');
35
+ var { createSession } = require('./sessionService');
36
+ var { getUserAccess, clearUserAccess } = require('./accessService');
37
+ var hooks = require('./hooks');
38
+ var { refusal } = require('./userRoles');
39
+
40
+ var otp = utils.otp;
41
+ var totp = utils.totp;
42
+ var cache = utils.cache;
43
+
44
+ var LOGIN_METHODS = ['password', 'email_otp', 'phone_otp'];
45
+ var MODES = ['off', 'optional', 'required'];
46
+ var SECOND_METHODS = ['authenticator', 'email', 'sms'];
47
+
48
+ var TICKET_SECONDS = 600; // first step → second step
49
+ var SETUP_SECONDS = 900; // authenticator scanned → first code typed
50
+ var MAX_TICKET_TRIES = 5; // wrong authenticator codes on one ticket
51
+ var CODES_PER_WINDOW = 5; // codes sent to one person …
52
+ var CODE_WINDOW_SECONDS = 900; // … per 15 minutes
53
+ var APP_FAILS_PER_WINDOW = 10; // wrong authenticator codes for one person, across sign-ins, per 15 minutes
54
+
55
+ // ── settings ─────────────────────────────────────────────────────────────
56
+
57
+ function list(raw, fallback) {
58
+ if (raw === undefined || raw === null || String(raw).trim() === '') return fallback.slice();
59
+ return String(raw).split(',').map(function(s) { return s.trim().toLowerCase(); }).filter(Boolean);
60
+ }
61
+
62
+ function invalid(name, value, allowed) {
63
+ return refusal('AUTH_SETTING_INVALID', name + ' has "' + value + '"; allowed: ' + allowed.join(', '));
64
+ }
65
+
66
+ /**
67
+ * The sign-in settings, read at call time. Throws on a value it does not know,
68
+ * naming the variable — a typo must not quietly turn the second step off.
69
+ */
70
+ function settings() {
71
+ var login = list(process.env.AUTH_LOGIN_METHODS, ['password']);
72
+ login.forEach(function(m) { if (LOGIN_METHODS.indexOf(m) === -1) throw invalid('AUTH_LOGIN_METHODS', m, LOGIN_METHODS); });
73
+ if (!login.length) throw refusal('AUTH_SETTING_INVALID', 'AUTH_LOGIN_METHODS names no way to sign in');
74
+
75
+ var mode = String(process.env.AUTH_2FA || 'off').trim().toLowerCase();
76
+ if (MODES.indexOf(mode) === -1) throw invalid('AUTH_2FA', mode, MODES);
77
+
78
+ var methods = list(process.env.AUTH_2FA_METHODS, ['authenticator', 'email']);
79
+ methods.forEach(function(m) { if (SECOND_METHODS.indexOf(m) === -1) throw invalid('AUTH_2FA_METHODS', m, SECOND_METHODS); });
80
+ if (methods.indexOf('email') === -1) methods.push('email'); // always the way back in
81
+
82
+ var rawDays = process.env.AUTH_2FA_TRUST_DAYS;
83
+ var trustDays = rawDays === undefined || String(rawDays).trim() === '' ? 0 : Number(rawDays);
84
+ if (!(trustDays >= 0) || Math.floor(trustDays) !== trustDays) {
85
+ throw refusal('AUTH_SETTING_INVALID', 'AUTH_2FA_TRUST_DAYS must be a whole number of days (0 = never trust a device), not "' + rawDays + '"');
86
+ }
87
+
88
+ return { login: login, mode: mode, methods: methods, trustDays: trustDays };
89
+ }
90
+
91
+ /** Whether these settings send text messages — and so need an SMS provider. */
92
+ function needsSms(s) {
93
+ return s.login.indexOf('phone_otp') !== -1 || (s.mode !== 'off' && s.methods.indexOf('sms') !== -1);
94
+ }
95
+
96
+ /**
97
+ * At start: the settings parse, and what they need exists. An SMS provider is
98
+ * registered by the host (@xeplr/utils sms.register) before boot(); without
99
+ * one, a code by text cannot go out, so the server refuses to start rather
100
+ * than have the first person to try it find out.
101
+ */
102
+ function checkSettings() {
103
+ var s = settings();
104
+ if (needsSms(s) && !utils.sms.getProviders().length) {
105
+ throw refusal('SMS_NOT_SET_UP', 'Signing in by text message is turned on (' +
106
+ (s.login.indexOf('phone_otp') !== -1 ? 'AUTH_LOGIN_METHODS has phone_otp' : 'AUTH_2FA_METHODS has sms') +
107
+ ') but no SMS provider is registered. Register one with @xeplr/utils sms.register() before boot(), or remove it.');
108
+ }
109
+ return s;
110
+ }
111
+
112
+ /** What the sign-in page needs to know — public, nothing about any account. */
113
+ function signInOptions() {
114
+ var s = settings();
115
+ return { methods: s.login, twoFactor: s.mode, twoFactorMethods: s.methods, trustDays: s.trustDays };
116
+ }
117
+
118
+ function requireLoginMethod(s, method, words) {
119
+ if (s.login.indexOf(method) === -1) throw refusal('METHOD_OFF', words + ' is turned off on this server');
120
+ }
121
+
122
+ // ── phone numbers ────────────────────────────────────────────────────────
123
+
124
+ /** "+91 98765-43210" → "+919876543210": a leading + and the digits. */
125
+ function cleanPhone(typed) {
126
+ var t = String(typed || '').trim();
127
+ var digits = t.replace(/\D/g, '');
128
+ if (!digits) return '';
129
+ return (t.charAt(0) === '+' ? '+' : '') + digits;
130
+ }
131
+
132
+ var PHONE_SQL = 'regexp_replace("phoneNumber", \'[^0-9+]\', \'\', \'g\')';
133
+ var DIGITS_SQL = 'regexp_replace("phoneNumber", \'[^0-9]\', \'\', \'g\')';
134
+
135
+ function verifiedPhones() {
136
+ return User.query().where('phoneVerified', true).whereNotNull('phoneNumber');
137
+ }
138
+
139
+ /**
140
+ * The one account whose VERIFIED number this is. Typed with its country code,
141
+ * it must match exactly; typed without (9876543210), it matches a number that
142
+ * ends with those digits — and only when exactly one account does.
143
+ */
144
+ async function findByVerifiedPhone(typed) {
145
+ var p = cleanPhone(typed);
146
+ if (!p) return null;
147
+ var exact = await verifiedPhones().whereRaw(PHONE_SQL + ' = ?', [p]).withGraphFetched('roles');
148
+ if (exact.length === 1) return exact[0];
149
+ if (exact.length > 1 || p.charAt(0) === '+' || p.length < 10) return null;
150
+ var ending = await verifiedPhones().whereRaw(DIGITS_SQL + ' LIKE ?', ['%' + p]).withGraphFetched('roles');
151
+ return ending.length === 1 ? ending[0] : null;
152
+ }
153
+
154
+ /** Another account already holds this number, verified. */
155
+ async function phoneTakenByOther(userId, number) {
156
+ var p = cleanPhone(number);
157
+ if (!p) return false;
158
+ var others = await verifiedPhones().whereRaw(PHONE_SQL + ' = ?', [p]).whereNot('id', userId).select('id');
159
+ return others.length > 0;
160
+ }
161
+
162
+ // ── showing where a code went, without saying all of it ─────────────────
163
+
164
+ function maskEmail(email) {
165
+ var parts = String(email || '').split('@');
166
+ if (parts.length !== 2) return '';
167
+ return parts[0].charAt(0) + '•••@' + parts[1];
168
+ }
169
+
170
+ function maskPhone(phone) {
171
+ var d = String(phone || '').replace(/\D/g, '');
172
+ return d ? '•••' + d.slice(-4) : '';
173
+ }
174
+
175
+ function sentTo(user, method) {
176
+ if (method === 'email') return maskEmail(user.email);
177
+ if (method === 'sms') return maskPhone(user.phoneNumber);
178
+ return '';
179
+ }
180
+
181
+ // ── sending a code ───────────────────────────────────────────────────────
182
+
183
+ var _sendLimiter = null;
184
+ function sendLimiter() {
185
+ if (!_sendLimiter) _sendLimiter = new utils.RateLimiter({ windowInSeconds: CODE_WINDOW_SECONDS, max: CODES_PER_WINDOW, store: 'redis' });
186
+ return _sendLimiter;
187
+ }
188
+
189
+ /** Five codes per person per 15 minutes, whichever way they go. */
190
+ async function countSend(userId) {
191
+ var key = 'auth-codes:' + userId;
192
+ var wait = await sendLimiter().lockedFor(key);
193
+ if (wait > 0) {
194
+ throw refusal('TOO_MANY_CODES', 'Too many codes asked for. Try again in ' + Math.ceil(wait / 60) + ' minute' + (wait > 60 ? 's' : '') + '.');
195
+ }
196
+ await sendLimiter().fail(key);
197
+ }
198
+
199
+ // Wrong authenticator codes for one PERSON, across every sign-in: someone who
200
+ // has the password can start as many sign-ins as they like, each with its own
201
+ // five tries — this is what bounds the guessing.
202
+ var _appFails = null;
203
+ function appFails() {
204
+ if (!_appFails) _appFails = new utils.RateLimiter({ windowInSeconds: CODE_WINDOW_SECONDS, max: APP_FAILS_PER_WINDOW, store: 'redis' });
205
+ return _appFails;
206
+ }
207
+
208
+ function lockedOut(wait) {
209
+ return refusal('TOO_MANY_TRIES', 'Too many wrong codes. Try again in ' + Math.ceil(wait / 60) + ' minute' + (wait > 60 ? 's' : '') + ', or ask for a code by email.');
210
+ }
211
+
212
+ function codeEmail(code, why) {
213
+ return '<h2>' + why + '</h2>'
214
+ + '<p>Your code is:</p>'
215
+ + '<p style="font-size:28px;letter-spacing:6px;font-weight:bold">' + code + '</p>'
216
+ + '<p>It works once, for 5 minutes. If you did not try to sign in, ignore this email — and consider changing your password.</p>';
217
+ }
218
+
219
+ /** One code under `key`, to the person's email or verified phone. */
220
+ async function sendCode(key, method, user) {
221
+ if (method === 'email') {
222
+ return otp.requestOtp(key, {
223
+ send: async function(code) {
224
+ try {
225
+ await utils.sendEmail(user.email, 'Your sign-in code: ' + code, codeEmail(code, 'Your sign-in code'));
226
+ } catch (err) {
227
+ var e = refusal('EMAIL_SEND_FAILED', 'Could not send the code by email: ' + err.message);
228
+ e.cause = err;
229
+ throw e;
230
+ }
231
+ }
232
+ });
233
+ }
234
+ if (method === 'sms') return otp.requestOtp(key, { to: cleanPhone(user.phoneNumber) });
235
+ throw refusal('BAD_METHOD', 'Codes are sent by email or text message, not "' + method + '"');
236
+ }
237
+
238
+ function codeRefusal(reason) {
239
+ if (reason === 'too_many_attempts') return refusal('TOO_MANY_TRIES', 'Too many wrong codes. Ask for a new one.');
240
+ if (reason === 'expired') return refusal('CODE_EXPIRED', 'That code has expired or was already used. Ask for a new one.');
241
+ return refusal('BAD_CODE', 'That code is not right.');
242
+ }
243
+
244
+ // ── the session at the end of every way in ───────────────────────────────
245
+
246
+ async function issueSession(user) {
247
+ var full = user.roles ? user : await User.query().findById(user.id).withGraphFetched('roles');
248
+ var tokenUser = {
249
+ id: full.id,
250
+ email: full.email,
251
+ name: full.name,
252
+ roles: (full.roles || []).map(function(r) { return r.name; })
253
+ };
254
+ var pair = await createSession(tokenUser);
255
+ await clearUserAccess(full.id);
256
+ var access = await getUserAccess(full.id);
257
+ await hooks.fire('user', 'login', full.id);
258
+ return {
259
+ accessToken: pair.accessToken,
260
+ refreshToken: pair.refreshToken,
261
+ user: { id: full.id, email: full.email, name: full.name, isActivated: full.isActivated },
262
+ access: access
263
+ };
264
+ }
265
+
266
+ function canSignIn(user) {
267
+ return Boolean(user && user.isActive && user.isActivated);
268
+ }
269
+
270
+ // ── the second step ──────────────────────────────────────────────────────
271
+
272
+ /**
273
+ * Which second steps this person may use, after a first step that used
274
+ * `used` ('password', 'email', 'sms'); null when none is asked.
275
+ */
276
+ function secondStepFor(user, used, s) {
277
+ if (s.mode === 'off') return null;
278
+ if (s.mode === 'optional' && !user.twoFactorMethod) return null;
279
+ var have = [];
280
+ if (s.methods.indexOf('authenticator') !== -1 && user.totpSecret) have.push('authenticator');
281
+ if (s.methods.indexOf('sms') !== -1 && user.phoneVerified && user.phoneNumber) have.push('sms');
282
+ have.push('email');
283
+ have = have.filter(function(m) { return m !== used; });
284
+ if (!have.length) return null;
285
+ var method = have.indexOf(user.twoFactorMethod) !== -1 ? user.twoFactorMethod : have[0];
286
+ return { methods: have, method: method };
287
+ }
288
+
289
+ function stampOf(user) {
290
+ return user.twoFactorChangedOn ? new Date(user.twoFactorChangedOn).getTime() : 0;
291
+ }
292
+
293
+ function trustKey(token) {
294
+ return '2fa-trust:' + crypto.createHash('sha256').update(String(token)).digest('hex');
295
+ }
296
+
297
+ async function trusted(user, token, s) {
298
+ if (!token || !s.trustDays) return false;
299
+ var rec = await cache.get(trustKey(token));
300
+ return Boolean(rec && rec.userId === user.id && rec.stamp === stampOf(user));
301
+ }
302
+
303
+ async function trustThisDevice(user, s) {
304
+ var token = crypto.randomBytes(32).toString('hex');
305
+ await cache.set(trustKey(token), { userId: user.id, stamp: stampOf(user) }, s.trustDays * 86400);
306
+ return token;
307
+ }
308
+
309
+ function ticketKey(ticket) { return '2fa-ticket:' + ticket; }
310
+ function codeKeyFor(ticket) { return '2fa:' + ticket; }
311
+
312
+ /**
313
+ * After a first step that proved `used`: tokens, or — when a second step is
314
+ * asked and this device is not trusted — a ticket for it. Sends the code
315
+ * straight away when the second step is a code by email or text.
316
+ */
317
+ async function afterFirstStep(user, used, trustToken) {
318
+ var s = settings();
319
+ var step = secondStepFor(user, used, s);
320
+ if (!step || await trusted(user, trustToken, s)) return issueSession(user);
321
+
322
+ var ticket = crypto.randomBytes(24).toString('hex');
323
+ await cache.set(ticketKey(ticket), { userId: user.id, methods: step.methods, tries: 0 }, TICKET_SECONDS);
324
+ if (step.method !== 'authenticator') {
325
+ await countSend(user.id);
326
+ await sendCode(codeKeyFor(ticket), step.method, user);
327
+ }
328
+ return {
329
+ secondStep: {
330
+ ticket: ticket,
331
+ method: step.method,
332
+ methods: step.methods,
333
+ sentTo: sentTo(user, step.method),
334
+ trustDays: s.trustDays
335
+ }
336
+ };
337
+ }
338
+
339
+ async function readTicket(ticket) {
340
+ var t = ticket ? await cache.get(ticketKey(ticket)) : null;
341
+ if (!t) throw refusal('SIGN_IN_EXPIRED', 'This sign-in has expired. Start again.');
342
+ return t;
343
+ }
344
+
345
+ async function ticketUser(t) {
346
+ var user = await User.query().findById(t.userId).withGraphFetched('roles');
347
+ if (!canSignIn(user)) throw refusal('SIGN_IN_EXPIRED', 'This sign-in has expired. Start again.');
348
+ return user;
349
+ }
350
+
351
+ /** Send (or send again) the second-step code, by email or text. */
352
+ async function sendSecondStepCode({ ticket, method }) {
353
+ var t = await readTicket(ticket);
354
+ if (t.methods.indexOf(method) === -1 || method === 'authenticator') {
355
+ throw refusal('BAD_METHOD', 'A code cannot be sent that way for this sign-in');
356
+ }
357
+ var user = await ticketUser(t);
358
+ await countSend(user.id);
359
+ await sendCode(codeKeyFor(ticket), method, user);
360
+ return { sent: true, method: method, sentTo: sentTo(user, method) };
361
+ }
362
+
363
+ async function readSecret(user) {
364
+ return decrypt(user.totpSecret, process.env.ENCRYPTION_KEY);
365
+ }
366
+
367
+ /** An authenticator code is good once: the same six digits a second time are refused. */
368
+ async function usedBefore(userId, code) {
369
+ var key = 'totp-used:' + userId + ':' + String(code).replace(/\s/g, '');
370
+ if (await cache.get(key)) return true;
371
+ await cache.set(key, { at: Date.now() }, 120);
372
+ return false;
373
+ }
374
+
375
+ /** The second step's code → tokens (and, when asked for, a trusted-device token). */
376
+ async function verifySecondStep({ ticket, method, code, trustDevice }) {
377
+ var s = settings();
378
+ var t = await readTicket(ticket);
379
+ if (t.methods.indexOf(method) === -1) throw refusal('BAD_METHOD', 'That way is not offered for this sign-in');
380
+ var user = await ticketUser(t);
381
+
382
+ if (method === 'authenticator') {
383
+ var failKey = 'auth-app-fails:' + user.id;
384
+ var wait = await appFails().lockedFor(failKey);
385
+ if (wait > 0) throw lockedOut(wait);
386
+ var ok = totp.verify(await readSecret(user), code);
387
+ if (!ok || await usedBefore(user.id, code)) {
388
+ var counted = await appFails().fail(failKey);
389
+ if (counted.lockedFor > 0) {
390
+ await cache.del(ticketKey(ticket));
391
+ throw lockedOut(counted.lockedFor);
392
+ }
393
+ t.tries = (t.tries || 0) + 1;
394
+ if (t.tries >= MAX_TICKET_TRIES) {
395
+ await cache.del(ticketKey(ticket));
396
+ throw refusal('TOO_MANY_TRIES', 'Too many wrong codes. Sign in again.');
397
+ }
398
+ await cache.set(ticketKey(ticket), t, TICKET_SECONDS);
399
+ throw refusal('BAD_CODE', 'That code is not right. Use the one your authenticator app shows now.');
400
+ }
401
+ await appFails().reset(failKey);
402
+ } else {
403
+ var r = await otp.verifyOtp(codeKeyFor(ticket), code);
404
+ if (!r.success) throw codeRefusal(r.reason);
405
+ }
406
+
407
+ await cache.del(ticketKey(ticket));
408
+ await otp.cancelOtp(codeKeyFor(ticket));
409
+ var session = await issueSession(user);
410
+ if (trustDevice && s.trustDays) session.trustToken = await trustThisDevice(user, s);
411
+ return session;
412
+ }
413
+
414
+ // ── signing in with a code instead of a password ─────────────────────────
415
+
416
+ async function accountFor({ email, phoneNumber }, s) {
417
+ if (email) {
418
+ requireLoginMethod(s, 'email_otp', 'Signing in with an emailed code');
419
+ return User.query().findOne({ normalizedEmail: normalizeEmail(email) }).withGraphFetched('roles');
420
+ }
421
+ if (phoneNumber) {
422
+ requireLoginMethod(s, 'phone_otp', 'Signing in with your mobile number');
423
+ return findByVerifiedPhone(phoneNumber);
424
+ }
425
+ throw refusal('BAD_REQUEST', 'Email or mobile number is required');
426
+ }
427
+
428
+ /**
429
+ * Send a sign-in code. The SAME answer whether or not an account matched —
430
+ * it must not tell anyone which addresses or numbers have accounts.
431
+ */
432
+ async function requestSignInCode({ email, phoneNumber }) {
433
+ var s = settings();
434
+ var user = await accountFor({ email: email, phoneNumber: phoneNumber }, s);
435
+ if (!canSignIn(user)) return { sent: true };
436
+ await countSend(user.id);
437
+ await sendCode('signin:' + user.id, email ? 'email' : 'sms', user);
438
+ return { sent: true };
439
+ }
440
+
441
+ async function verifySignInCode({ email, phoneNumber, code, trustToken }) {
442
+ var s = settings();
443
+ var user = await accountFor({ email: email, phoneNumber: phoneNumber }, s);
444
+ if (!canSignIn(user)) throw codeRefusal('invalid');
445
+ var r = await otp.verifyOtp('signin:' + user.id, code);
446
+ if (!r.success) throw codeRefusal(r.reason);
447
+ return afterFirstStep(user, email ? 'email' : 'sms', trustToken);
448
+ }
449
+
450
+ // ── my own second step (signed in) ───────────────────────────────────────
451
+
452
+ async function mine(userId) {
453
+ var user = await User.query().findById(userId);
454
+ if (!user) throw refusal('USER_NOT_FOUND', 'User not found');
455
+ return user;
456
+ }
457
+
458
+ function statusOf(user, s) {
459
+ return {
460
+ mode: s.mode,
461
+ methods: s.methods,
462
+ method: user.twoFactorMethod || null,
463
+ authenticator: Boolean(user.totpSecret),
464
+ phoneNumber: user.phoneNumber || null,
465
+ phoneVerified: Boolean(user.phoneVerified),
466
+ trustDays: s.trustDays,
467
+ signIn: s.login
468
+ };
469
+ }
470
+
471
+ async function twoFactorStatus(userId) {
472
+ return statusOf(await mine(userId), settings());
473
+ }
474
+
475
+ /** A new authenticator secret, held for 15 minutes until a code from the app confirms it. */
476
+ async function startAuthenticator(userId, issuer) {
477
+ var s = settings();
478
+ if (s.methods.indexOf('authenticator') === -1) throw refusal('METHOD_OFF', 'Authenticator apps are turned off on this server');
479
+ var user = await mine(userId);
480
+ var secret = totp.newSecret();
481
+ await cache.set('totp-setup:' + userId, { secret: secret }, SETUP_SECONDS);
482
+ var name = String(issuer || '').trim().slice(0, 60) || 'Xeplr';
483
+ return { secret: secret, otpauthUrl: totp.otpauthUrl(secret, user.email, name) };
484
+ }
485
+
486
+ async function changed(userId, patch) {
487
+ var now = utils.formatDbDateTime();
488
+ await User.query().findById(userId).patch(Object.assign({ twoFactorChangedOn: now, recordModifiedDate: now }, patch));
489
+ await hooks.fire('user', 'update', userId);
490
+ }
491
+
492
+ async function confirmAuthenticator(userId, code) {
493
+ var held = await cache.get('totp-setup:' + userId);
494
+ if (!held) throw refusal('SETUP_EXPIRED', 'Setting up took too long. Start again.');
495
+ if (!totp.verify(held.secret, code)) {
496
+ throw refusal('BAD_CODE', 'That code is not right. Check the app shows this account, and that the phone sets its time automatically.');
497
+ }
498
+ var stored = await encrypt(held.secret, process.env.ENCRYPTION_KEY);
499
+ await changed(userId, { totpSecret: stored, twoFactorMethod: 'authenticator' });
500
+ await cache.del('totp-setup:' + userId);
501
+ return twoFactorStatus(userId);
502
+ }
503
+
504
+ /** Choose the second step ('authenticator', 'email', 'sms'), or turn it off (null). */
505
+ async function chooseMethod(userId, method) {
506
+ var s = settings();
507
+ var user = await mine(userId);
508
+ if (!method || method === 'off') {
509
+ if (s.mode === 'required') throw refusal('REQUIRED', 'The second step is required on this server; choose how, it cannot be turned off');
510
+ await changed(userId, { twoFactorMethod: null });
511
+ return twoFactorStatus(userId);
512
+ }
513
+ if (s.methods.indexOf(method) === -1) throw refusal('METHOD_OFF', '"' + method + '" is not offered on this server');
514
+ if (method === 'authenticator' && !user.totpSecret) throw refusal('NOT_SET_UP', 'Set up the authenticator app first');
515
+ if (method === 'sms' && !(user.phoneVerified && user.phoneNumber)) throw refusal('NOT_SET_UP', 'Verify your mobile number first');
516
+ await changed(userId, { twoFactorMethod: method });
517
+ return twoFactorStatus(userId);
518
+ }
519
+
520
+ /** An admin clears someone's second step: no method, no authenticator; trusted devices ask again. */
521
+ async function resetTwoFactor(userId, adminId) {
522
+ await mine(userId);
523
+ await changed(userId, { twoFactorMethod: null, totpSecret: null, recordModifiedBy: adminId || null });
524
+ return { reset: true };
525
+ }
526
+
527
+ module.exports = {
528
+ settings: settings,
529
+ checkSettings: checkSettings,
530
+ signInOptions: signInOptions,
531
+ requireLoginMethod: requireLoginMethod,
532
+ cleanPhone: cleanPhone,
533
+ findByVerifiedPhone: findByVerifiedPhone,
534
+ phoneTakenByOther: phoneTakenByOther,
535
+ issueSession: issueSession,
536
+ afterFirstStep: afterFirstStep,
537
+ sendSecondStepCode: sendSecondStepCode,
538
+ verifySecondStep: verifySecondStep,
539
+ requestSignInCode: requestSignInCode,
540
+ verifySignInCode: verifySignInCode,
541
+ twoFactorStatus: twoFactorStatus,
542
+ startAuthenticator: startAuthenticator,
543
+ confirmAuthenticator: confirmAuthenticator,
544
+ chooseMethod: chooseMethod,
545
+ resetTwoFactor: resetTwoFactor
546
+ };
@@ -0,0 +1,115 @@
1
+ -- 0015_otp_two_factor.sql
2
+ -- Signing in with a code (email or mobile) and the second step (2FA).
3
+ --
4
+ -- users:
5
+ -- twoFactorMethod what this person's second step uses: 'authenticator',
6
+ -- 'email' or 'sms'; NULL = not turned on (AUTH_2FA=optional)
7
+ -- totpSecret the authenticator app's secret, encrypted with
8
+ -- ENCRYPTION_KEY (never stored in clear)
9
+ -- twoFactorChangedOn when the above last changed. A trusted device
10
+ -- remembers this value; a change (or an admin reset)
11
+ -- makes every earlier "trust this device" ask again.
12
+
13
+ ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "twoFactorMethod" varchar(20);
14
+ ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "totpSecret" varchar(500);
15
+ ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "twoFactorChangedOn" timestamp;
16
+
17
+ -- ONE PERSON PER VERIFIED NUMBER: signing in by mobile finds the account by
18
+ -- its number, so two accounts holding the same verified number would make it
19
+ -- a guess. The code refuses a second one at verification; this index holds it
20
+ -- in the database too. An install that already has duplicates is not stopped
21
+ -- from starting — it is told, and the code's check still applies.
22
+ DO $$
23
+ BEGIN
24
+ IF EXISTS (
25
+ SELECT 1 FROM "users"
26
+ WHERE "phoneVerified" = true AND "phoneNumber" IS NOT NULL
27
+ GROUP BY regexp_replace("phoneNumber", '[^0-9+]', '', 'g')
28
+ HAVING count(*) > 1
29
+ ) THEN
30
+ RAISE NOTICE 'users: some verified phone numbers belong to more than one account; unique index not created. Unverify the duplicates, then create users_verified_phone_unique.';
31
+ ELSE
32
+ CREATE UNIQUE INDEX IF NOT EXISTS "users_verified_phone_unique"
33
+ ON "users" (regexp_replace("phoneNumber", '[^0-9+]', '', 'g'))
34
+ WHERE "phoneVerified" = true AND "phoneNumber" IS NOT NULL;
35
+ END IF;
36
+ END $$;
37
+
38
+ -- ROUTES.
39
+ --
40
+ -- public (how a caller gets a token, so no group):
41
+ -- GET /auth/api/sign-in-options which ways in this server offers
42
+ -- POST /auth/api/login/code send a sign-in code (email or mobile)
43
+ -- POST /auth/api/login/code/verify sign in with it
44
+ -- POST /auth/api/login/second-step/send send the second-step code (email/SMS)
45
+ -- POST /auth/api/login/second-step/verify finish signing in
46
+ -- account:* (my own second step):
47
+ -- GET /auth/api/two-factor account:view
48
+ -- POST /auth/api/two-factor/authenticator account:edit start setting up the app
49
+ -- POST /auth/api/two-factor/authenticator/confirm account:edit
50
+ -- POST /auth/api/two-factor/method account:edit choose / turn off
51
+ -- users:edit:
52
+ -- POST /auth/api/admin/users/:id/two-factor/reset
53
+
54
+ INSERT INTO "apis" (id, name, "apiGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
55
+ SELECT encode(gen_random_bytes(12), 'hex'), v.name, v.grp, v.pub, true, '*', now(), now()
56
+ FROM (VALUES
57
+ ('GET /auth/api/sign-in-options', '', true),
58
+ ('POST /auth/api/login/code', '', true),
59
+ ('POST /auth/api/login/code/verify', '', true),
60
+ ('POST /auth/api/login/second-step/send', '', true),
61
+ ('POST /auth/api/login/second-step/verify', '', true),
62
+ ('GET /auth/api/two-factor', 'account:view', false),
63
+ ('POST /auth/api/two-factor/authenticator', 'account:edit', false),
64
+ ('POST /auth/api/two-factor/authenticator/confirm', 'account:edit', false),
65
+ ('POST /auth/api/two-factor/method', 'account:edit', false),
66
+ ('POST /auth/api/admin/users/:id/two-factor/reset', 'users:edit', false)
67
+ ) AS v(name, grp, pub)
68
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" a WHERE a.name = v.name AND a."apiGroup" = v.grp);
69
+
70
+ -- WHO GETS THEM: every role that can already reach the route beside it — any
71
+ -- role that opens its own profile gets its own second step; any role that can
72
+ -- activate a user by hand can reset one's second step. That covers auth's
73
+ -- default roles AND each app's own (BI's CompanyAdmin, Creator, Viewer;
74
+ -- Taskie's), whose account:* mappings their own migrations made long before
75
+ -- these routes existed and will not run again.
76
+
77
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
78
+ SELECT DISTINCT ON (m."roleId", a.id) encode(gen_random_bytes(12), 'hex'), m."roleId", a.id, true, '*', now(), now()
79
+ FROM "apisRolesMapping" m
80
+ JOIN "apis" have ON have.id = m."apiId" AND have.name = '/auth/api/profile' AND have."apiGroup" = 'account:view'
81
+ CROSS JOIN "apis" a
82
+ WHERE m."isActive" = true
83
+ AND a.name IN ('GET /auth/api/two-factor', 'POST /auth/api/two-factor/authenticator',
84
+ 'POST /auth/api/two-factor/authenticator/confirm', 'POST /auth/api/two-factor/method')
85
+ AND a."apiGroup" IN ('account:view', 'account:edit')
86
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" x WHERE x."roleId" = m."roleId" AND x."apiId" = a.id);
87
+
88
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
89
+ SELECT DISTINCT ON (m."roleId", a.id) encode(gen_random_bytes(12), 'hex'), m."roleId", a.id, true, '*', now(), now()
90
+ FROM "apisRolesMapping" m
91
+ JOIN "apis" have ON have.id = m."apiId" AND have.name = 'POST /auth/api/admin/users/:id/activate' AND have."apiGroup" = 'users:edit'
92
+ CROSS JOIN "apis" a
93
+ WHERE m."isActive" = true
94
+ AND a.name = 'POST /auth/api/admin/users/:id/two-factor/reset' AND a."apiGroup" = 'users:edit'
95
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" x WHERE x."roleId" = m."roleId" AND x."apiId" = a.id);
96
+
97
+ -- Super Admin and Admin by name as well, in case a fresh install's mapping of
98
+ -- the neighbour route is still to come.
99
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
100
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
101
+ FROM "roles" r CROSS JOIN "apis" a
102
+ WHERE r.name IN ('Super Admin', 'Admin')
103
+ AND a.name IN ('GET /auth/api/two-factor', 'POST /auth/api/two-factor/authenticator',
104
+ 'POST /auth/api/two-factor/authenticator/confirm', 'POST /auth/api/two-factor/method',
105
+ 'POST /auth/api/admin/users/:id/two-factor/reset')
106
+ AND a."apiGroup" <> ''
107
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
108
+
109
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
110
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
111
+ FROM "roles" r CROSS JOIN "apis" a
112
+ WHERE r.name IN ('Editor', 'Viewer')
113
+ AND a.name IN ('GET /auth/api/two-factor', 'POST /auth/api/two-factor/authenticator',
114
+ 'POST /auth/api/two-factor/authenticator/confirm', 'POST /auth/api/two-factor/method')
115
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
package/models/User.js CHANGED
@@ -39,7 +39,10 @@ class User extends BaseModel {
39
39
  resetToken: { type: ['string', 'null'], maxLength: 255 },
40
40
  resetTokenExpiry: { type: ['string', 'null'] },
41
41
  activationToken: { type: ['string', 'null'], maxLength: 255 },
42
- normalizedEmail: { type: ['string', 'null'], maxLength: 255 }
42
+ normalizedEmail: { type: ['string', 'null'], maxLength: 255 },
43
+ twoFactorMethod: { type: ['string', 'null'], maxLength: 20 },
44
+ totpSecret: { type: ['string', 'null'], maxLength: 500 },
45
+ twoFactorChangedOn: { type: ['string', 'null'] }
43
46
  }
44
47
  };
45
48
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/auth",
3
- "version": "1.5.3",
3
+ "version": "1.6.1",
4
4
  "description": "Pluggable authentication service: register, login, forgot/reset password, RBAC, multi-tenancy",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -38,13 +38,13 @@
38
38
  "access": "public"
39
39
  },
40
40
  "dependencies": {
41
+ "@xeplr/base-apis": "^2.0.0",
42
+ "@xeplr/db": "^1.0.0",
43
+ "@xeplr/utils": "^2.1.0",
41
44
  "bcrypt": "^6.0.0",
42
45
  "ioredis": "^5.6.1",
43
46
  "jsonwebtoken": "^9.0.3",
44
- "multer": "^2.3.0",
45
- "@xeplr/base-apis": "^2.0.0",
46
- "@xeplr/db": "^1.0.0",
47
- "@xeplr/utils": "^1.0.8"
47
+ "multer": "^2.3.0"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "express": "^4.0.0 || ^5.0.0"