@xeplr/auth 1.5.2 → 1.6.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
@@ -78,14 +78,16 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName }) //
78
78
  | `boot()` | the standalone service, env-driven, as above; resolves to the `http.Server` |
79
79
  | `start(config)` | `init(config)` + Express on `config.port` with both routers; no Redis check, no migrations, no banner |
80
80
  | `init(config)` | connect and bind the models, configure JWT and email; checks `REDIS_PREFIX` |
81
- | `attach()` | secondary connection to the auth database from another process: `{ ready, conn, model(name), service }` |
81
+ | `attach()` | secondary connection to the auth database from another process: `{ ready, conn, model(name), service, internalTokenFor(userId, { ttl }) }` |
82
+ | `createInternalToken(user, { ttl })` | an [internal token](#internal-tokens): the server calling its own API as `user` (`{ id, email, name, roles }`) |
82
83
  | `router(options)` | the `/auth/api` router; `options.resetBaseUrl` sets where reset links point |
83
84
  | `adminRouter()` | the `/auth/api/admin` router |
84
- | `authMiddleware` | Bearer token check against the Redis session; sets `req.user`; slides within tolerance |
85
+ | `authMiddleware` | Bearer token check against the Redis session; sets `req.user`; slides within tolerance. An [internal token](#internal-tokens) is served as the user it acts as |
85
86
  | `accessMiddleware(options)` | per-API RBAC from the `apis` catalog — see [Access checks](#access-checks) |
86
87
  | `requireRole(...names)` | 403 unless `req.user.roles` holds one of the names; use after `authMiddleware` |
87
88
  | `mtMembershipMiddleware(options)` | 403 when a tenant header names a value the caller has no membership for |
88
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` |
89
91
  | `accessService` | `getUserAccess`, `userApiState`, `userHasApiAccess`, `apiStateFor`, `ACCESS_STATES`, `getApiRule`, `getPublicItems`, `clearUserAccess`, `clearAccessRules`, `clearAllAccess` |
90
92
  | `sessionService` | `createSession`, `getSession`, `validateAccessToken`, `slideAccessToken`, `rotateSession`, `destroySession`, `destroyAllUserSessions` |
91
93
  | `ticketService` | `issueTicket`, `consumeTicket` — single-use 30-second tickets for SSE / WebSocket |
@@ -135,6 +137,10 @@ Everything in `requiredEnv`, plus a connection. `requiredEnv` includes the sign-
135
137
  | `REDIS_HOST` / `REDIS_PORT` | `127.0.0.1` / `6379` | the session store |
136
138
  | `REDIS_PASSWORD` / `REDIS_DB` | none / `0` | read by `@xeplr/utils`' cache |
137
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 |
138
144
  | `EMAIL_PROVIDER` | not configured | `smtp`, `brevo`, `aws` or `azure` |
139
145
  | `SMTP_HOST`, `SMTP_PORT` (587), `SMTP_USER`, `SMTP_PASS`, `SMTP_FROM`, `SMTP_SECURE`, … | | SMTP settings, read by `@xeplr/utils` |
140
146
  | `BREVO_API_KEY`, `BREVO_FROM_EMAIL`, `BREVO_FROM_NAME` | | Brevo |
@@ -262,6 +268,44 @@ It is created **once**, when migrations first run on that database:
262
268
 
263
269
  To add or change an account afterwards, use the app (or `seedSuperAdmin(knex, { email, password })` from your own migration code).
264
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
+
265
309
  ## Sessions and tokens
266
310
 
267
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.
@@ -284,6 +328,26 @@ Access-Control-Expose-Headers: X-New-Token
284
328
 
285
329
  Client code must read the header and replace its stored token, or the session ends when the grace runs out. Concurrent requests carrying the same expiring token all get the **same** new token. A slid token copies its roles from the old one; roles are re-read on `/refresh` or the next login. A revoked session is never graced.
286
330
 
331
+ ## Internal tokens
332
+
333
+ A token the **server makes for itself**, to call its own API — or another xeplr service — as a user: a scheduled export, a dashboard print, a job step. **A library call, never a route**, so nothing outside the server can make one:
334
+
335
+ ```js
336
+ const auth = require('@xeplr/auth').attach();
337
+ const token = await auth.internalTokenFor(userId); // reads the user and their roles
338
+ // or, with the claims already at hand:
339
+ const token = await require('@xeplr/auth').createInternalToken({ id, email, name, roles });
340
+
341
+ await fetch(api + '/reports/r1/export', { method: 'POST', headers: {
342
+ authorization: 'Bearer ' + token, 'x-company-id': company, 'x-workspace-id': workspace, … } });
343
+ ```
344
+
345
+ - **A long random string** (`xit_` + 32 random bytes), kept in Redis under `REDIS_PREFIX` with the user it acts as, **for 30 seconds** (`ttl`: 1 to 300). Not a short code: it works on the API, so it must not be guessable within its life.
346
+ - **`authMiddleware` knows it by its prefix** and serves the request as that user. So `/verify`, every app's gate, the company membership and the API access rules apply exactly as to a sign-in token: it opens nothing that user could not open. **No code in the app** — the app's gate already asks auth.
347
+ - **Usable for its whole life, not once**: an export is started, waited on and fetched with one token.
348
+ - `internalTokenFor(userId)` refuses a user who is inactive or never activated: a deactivated person's scheduled work does not go on running as them.
349
+ - The server making it and the auth service reading it must share the Redis and `REDIS_PREFIX` — as they already do for sessions.
350
+
287
351
  ## Routes
288
352
 
289
353
  ### Sign-up and activation
@@ -303,7 +367,12 @@ Client code must read the header and replace its stored token, or the session en
303
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) |
304
368
  | `GET /invite-preview` | — | `?token=…` → `{ email, name }` for an account not yet activated (a password set by a reset meanwhile does not matter) |
305
369
  | `POST /invite-accept` | — | `{ token, password, name? }` → sets the password and activates |
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 |
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 |
307
376
  | `POST /refresh` | — | `{ refreshToken }` → a new `{ accessToken, refreshToken, user, access }` |
308
377
  | `POST /logout` | — | `{ refreshToken }` → ends that session |
309
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 |
@@ -313,8 +382,12 @@ Client code must read the header and replace its stored token, or the session en
313
382
  | `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
314
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 |
315
384
  | `POST /change-password` | ✓ | `{ oldPassword, newPassword }`; ends every session |
316
- | `POST /request-phone-otp` | ✓ | `{ phoneNumber? }` — needs an SMS provider registered with `@xeplr/utils` |
317
- | `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 |
318
391
  | `POST /sse-ticket` | ✓ | `{ scopes? }` (default `['user:me:*']`) → `{ ticket, expiresIn: 30 }` |
319
392
 
320
393
  ### `/auth/api/admin`
@@ -323,7 +396,8 @@ Client code must read the header and replace its stored token, or the session en
323
396
 
324
397
  | route | |
325
398
  |---|---|
326
- | `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 |
327
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 |
328
402
  | `GET /roles` | `[{ id, name, scope, mtId1 }]`: the current company's roles and the generic ones; system roles only for Super Admin |
329
403
  | `GET /access-items` | `{ apis, pages, elements, menus }`, each with its roles |
@@ -644,12 +718,24 @@ Hooks run in the process that did the work — register them in the same script
644
718
  npm test # node --test test/*.test.js
645
719
  ```
646
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
+
647
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.
648
732
 
649
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.
650
734
 
651
735
  `test/verifyTenant.test.js` checks the membership answer on real memberships (local PostgreSQL and Redis; skipped without either): a member of company and workspace passes and is told `tenant: 'checked'`; another company, another workspace and a switched-off membership are `403 NOT_A_MEMBER`; Super Admin passes; a request naming none is not checked and does not claim to be; an unreadable `x-verify-tenant` is `400 BAD_TENANT`.
652
736
 
737
+ `test/internalToken.test.js` (local Redis): a token the server made is served as its user, for its whole life; one nobody made is refused; it ends when its time is up; 30 seconds unless asked, never more than 5 minutes; a sign-in token is checked as before.
738
+
653
739
  `test/menuItems.test.js` needs a local PostgreSQL (the usual `PG*` variables): it creates and drops a throwaway database, and is skipped when none is reachable. The token-decision and `REDIS_PREFIX` tests need nothing.
654
740
 
655
741
  ## License
package/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ const internalToken = require('./lib/internalToken');
1
2
  const path = require('path');
2
3
  const { getConnection, bindModels, resolveConfig, sqlMigrator, resolveDbConnection, describeDbConnection, migrationsFor, migrationsVar } = require('@xeplr/db');
3
4
 
@@ -23,6 +24,7 @@ const mtMembershipMiddleware = require('./lib/mtMembershipMiddleware');
23
24
  const createAuthRouter = require('./lib/authRouter');
24
25
  const createAdminRouter = require('./lib/adminRouter');
25
26
  const systemScope = require('./lib/systemScope');
27
+ const signInSteps = require('./lib/signInSteps');
26
28
  const models = require('./models');
27
29
 
28
30
  let _initialized = false;
@@ -217,6 +219,24 @@ async function boot() {
217
219
  // reset) cannot be sent, and the banner says so rather than the first
218
220
  // person to register finding out.
219
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
+ }
220
240
  // Registration and reset refuse up front when mail is known not to work,
221
241
  // instead of creating an account whose link never goes out.
222
242
  authService.configureEmailStatus(email.unknown ? null : email.ok);
@@ -240,7 +260,7 @@ async function boot() {
240
260
  }
241
261
  });
242
262
 
243
- banner(email);
263
+ banner(email, signIn);
244
264
  if (!email.ok) warnNoEmail(email);
245
265
  return server;
246
266
  }
@@ -270,7 +290,7 @@ function describeEmail(email) {
270
290
 
271
291
  // Startup summary — the EFFECTIVE config (defaults resolved) so you can see what
272
292
  // the service is actually running with. Secrets are masked, never printed.
273
- function banner(email) {
293
+ function banner(email, signIn) {
274
294
  var set = function (v) { return v ? '✓ set' : '✗ MISSING'; };
275
295
  var rows = [
276
296
  ['port', process.env.AUTH_PORT || '19001'],
@@ -287,6 +307,9 @@ function banner(email) {
287
307
  ['redis', (process.env.REDIS_HOST || 'localhost') + ':' + (process.env.REDIS_PORT || '6379')],
288
308
  ['redis prefix', redisPrefix()],
289
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') : '?'],
290
313
  // Names the VARIABLE it resolved through, not just "set" — with a shared
291
314
  // default and a per-service override, "which server am I on" is otherwise
292
315
  // a guess.
@@ -347,7 +370,17 @@ function attach() {
347
370
  if (!M) throw new Error('auth.attach(): unknown auth model "' + name + '"');
348
371
  return M.bindKnex(conn());
349
372
  }
350
- return { ready: function () { return _ready; }, conn: conn, model: model, service: authService };
373
+ // A token the server makes for itself, acting as this user (by id): read
374
+ // with their roles, refused if they are inactive or never activated — a
375
+ // deactivated person's scheduled export must not go on running as them.
376
+ async function internalTokenFor(userId, opts) {
377
+ await _ready;
378
+ var user = await model('User').query().findById(userId).withGraphFetched('roles');
379
+ if (!user || !user.isActive || !user.isActivated) throw new Error('internalTokenFor: no active user "' + userId + '"');
380
+ return internalToken.createInternalToken({ id: user.id, email: user.email, name: user.name, roles: user.roles || [] }, opts);
381
+ }
382
+
383
+ return { ready: function () { return _ready; }, conn: conn, model: model, service: authService, internalTokenFor: internalTokenFor };
351
384
  }
352
385
 
353
386
  // Env vars this library needs — apps spread this into their env.required.js so
@@ -428,6 +461,9 @@ Object.defineProperty(requiredEnv, 'activationLinkVar', {
428
461
  // different question from the SERVER, and services do not share one.
429
462
 
430
463
  module.exports = {
464
+ // A token the server makes for itself (lib/internalToken.js): a library
465
+ // call, never a route. attach().internalTokenFor(userId) reads the user.
466
+ createInternalToken: internalToken.createInternalToken,
431
467
  // Hand in @xeplr-workflow/api's resumeByKey to release a step that is
432
468
  // waiting for someone to activate. Omitted, activation just activates.
433
469
  configureWorkflowResume: authService.configureWorkflowResume,
@@ -447,6 +483,9 @@ module.exports = {
447
483
  authHelper,
448
484
  seedSuperAdmin,
449
485
  authService,
486
+ // Code sign-in and the second step (lib/signInSteps.js): settings(),
487
+ // signInOptions(), resetTwoFactor(userId, adminId), cleanPhone() …
488
+ signInSteps,
450
489
  accessService,
451
490
  sessionService,
452
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 {
@@ -1,6 +1,7 @@
1
1
  const { decodeVerified, getToleranceSeconds } = require('./authHelper');
2
2
  const { validateAccessToken, slideAccessToken } = require('./sessionService');
3
3
  const { decide } = require('./tokenDecision');
4
+ const { isInternalToken, readInternalToken } = require('./internalToken');
4
5
 
5
6
  // The ONE place token logic lives. Order (from tokenDecision): signature →
6
7
  // revocation → expiry. Tolerance (ACCESS_TOKEN_TOLERANCE_SECONDS, default 0)
@@ -15,6 +16,16 @@ async function authMiddleware(req, res, next) {
15
16
  }
16
17
  const token = authHeader.split(' ')[1];
17
18
 
19
+ // AN INTERNAL TOKEN — made by the server for itself (lib/internalToken.js):
20
+ // served as the user it acts as while it lives in Redis. Everything after
21
+ // this (membership, the API's access) checks that user as usual.
22
+ if (isInternalToken(token)) {
23
+ const claims = await readInternalToken(token).catch(function() { return null; });
24
+ if (!claims) return res.status(401).json({ error: 'Invalid or expired token' });
25
+ req.user = claims;
26
+ return next();
27
+ }
28
+
18
29
  // Verify signature, ignore expiry (we decide on expiry ourselves).
19
30
  const { decoded, signatureValid } = decodeVerified(token);
20
31
 
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