pgkiln 0.63.0 → 0.64.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/SECURITY.md +2 -0
- package/db/migrations/132_app_user_mfa.sql +58 -0
- package/docs/apex-feature-parity.md +4 -1
- package/docs/guide/08-security.md +46 -5
- package/docs/guide/09-reference.md +5 -1
- package/docs/guide/11-from-apex.md +2 -1
- package/docs/guide/12-development.md +6 -0
- package/package.json +1 -1
- package/public/app.css +10 -0
- package/src/account-mfa.ts +93 -0
- package/src/builder/advisor.ts +8 -0
- package/src/builder/i18n/de.ts +6 -0
- package/src/builder/i18n/en.ts +6 -0
- package/src/builder/i18n/es.ts +6 -0
- package/src/builder/i18n/fr.ts +6 -0
- package/src/builder/i18n/nl.ts +6 -0
- package/src/builder/i18n/pt.ts +6 -0
- package/src/builder/login-page.ts +26 -2
- package/src/builder/users.ts +34 -3
- package/src/i18n/ar.ts +34 -0
- package/src/i18n/cs.ts +34 -0
- package/src/i18n/da.ts +34 -0
- package/src/i18n/de.ts +34 -0
- package/src/i18n/el.ts +34 -0
- package/src/i18n/es.ts +34 -0
- package/src/i18n/fi.ts +34 -0
- package/src/i18n/fr.ts +34 -0
- package/src/i18n/he.ts +34 -0
- package/src/i18n/it.ts +34 -0
- package/src/i18n/ja.ts +34 -0
- package/src/i18n/ko.ts +34 -0
- package/src/i18n/nb.ts +34 -0
- package/src/i18n/pl.ts +34 -0
- package/src/i18n/pt.ts +34 -0
- package/src/i18n/ru.ts +34 -0
- package/src/i18n/sv.ts +34 -0
- package/src/i18n/tr.ts +34 -0
- package/src/i18n/uk.ts +34 -0
- package/src/i18n/zh.ts +34 -0
- package/src/i18n.ts +68 -0
- package/src/metadata.ts +4 -1
- package/src/mfa.ts +76 -52
- package/src/remember.ts +1 -1
- package/src/runtime/account.ts +4 -1
- package/src/runtime/routes.ts +10 -6
- package/src/runtime/two-step.ts +395 -0
- package/src/sharedlogin.ts +1 -1
package/SECURITY.md
CHANGED
|
@@ -116,6 +116,7 @@ first version (MVP). Every finding below has a regression test in
|
|
|
116
116
|
| Passkeys and trusted browsers (0.61.0) | Passkeys (WebAuthn) are checked in `src/webauthn.ts` without a library: a 32-byte one-time challenge per purpose (registration or sign-in) kept in the session for five minutes and used up on the first answer, the `clientDataJSON` type, challenge and origin (`PUBLIC_URL`'s, else the browser's own), the SHA-256 of the relying party id in the authenticator data, user presence, an ES256, EdDSA or RS256 signature over the authenticator data and the client data hash, and a signature counter that must go up (updated atomically, so a replayed or cloned key is refused). The CBOR reader takes only definite lengths, at most 16 levels and 1,000 entries. Credentials are public keys (no secret to leak, independent of the instance key); attestation is *none*. `PGKILN_RP_ID` is only honoured when it is the host or a parent domain of it. The sign-in options (the developer's credential ids) are only given after the password step, with the CSRF token. Trusted browsers (off by default) are a random 256-bit cookie token (`HttpOnly`, `SameSite=Lax`, `Secure` with `COOKIE_SECURE`, path `/builder`) of which only the SHA-256 is stored; the cookie is only looked at after a correct password, for that developer, and ends with its days, a new password, removing a factor, a reset, *Forget trusted browsers* or turning trust off (which removes every trusted browser at once). |
|
|
117
117
|
| Passkey sign-in without a password, workspace rule (0.62.0) | *Sign in with a passkey* asks the browser for any passkey of this site (empty allow list) with `userVerification: required`, and the server refuses an answer whose authenticator data lacks the user-verified flag, so the passkey alone stands for possession plus a fingerprint, face or PIN. The credential id is looked up for this relying party only; a user handle, when the browser sends one, must be the developer's (a SHA-256-derived handle, not the user name). The same one-time challenge, origin, RP ID hash, signature and counter checks as at the second step apply; failures are logged as `login_failed` with the developer's name when the key is known and count for the per-user and per-IP lockout. Administrators turn it off in Instance settings. A workspace's rule (administrators and its own administrators only, CSRF-checked) can only add a requirement; `pgkiln admin set-2fa-policy off` clears every workspace's rule. While a second factor is required of a developer, a sign-in with the default password leads only to the password change. |
|
|
118
118
|
| Single sign-on for developers (0.63.0) | A provider or directory signs developers in only with *builder* turned on. The flow is the applications' (state, PKCE, nonce, browser-binding cookie, ID token or SAML assertion checks) with a pending row without an application; developers are found by the provider's stable subject in `meta.developer_identity`, never by a name alone. An existing developer is linked by name only when the administrator allows it, once, never a break-glass administrator, and an e-mail user name only when verified; otherwise the developer links the identity on Security, which needs their session and CSRF token to start and the same browser to finish, and one identity can't be linked to two developers. Automatic accounts need the developers group when one is set and start as developers; the administrators group decides the role at every sign-in but never demotes a break-glass administrator. A workspace's single sign-on rule (administrators and its own administrators, CSRF-checked) refuses the pgkiln password and a passkey alone, after the password check so it reveals nothing; it can only be turned on while a break-glass administrator exists and by someone who could still sign in; the last break-glass administrator and a developer's last identity can't be removed while it applies. Failures are logged as `login_failed` with the reason. |
|
|
119
|
+
| Two-factor sign-in for application users (0.64.0) | Per application (`meta.app.mfa`: off, optional, required, required for roles). The account's TOTP secrets are encrypted with `PGKILN_SECRET_KEY` and stored only after a code confirms them; recovery codes are SHA-256 and used up atomically; each 30-second step once, one step either side. A password or LDAP sign-in that needs the step creates no session: the pending sign-in (5 minutes, 10 while adding an app) lives in the signed-out session, bound to it and to the page's CSRF token, and a forged token ends it. Wrong codes count as failed sign-ins (the per-user and per-IP lockout). A *Keep me signed in* or session-sharing token stands in for the step only when its method ends in `+2fa`; an identity provider's sign-in is left to the provider. Without the instance key the step can't be required and enrolment refuses rather than skips. Removing an app needs a current or recovery code and is refused for the last app while the application requires it; a developer's reset (Users, with a reason) removes the apps and codes and ends the account's sessions, remembered and shared sign-ins. Every enrolment, removal, reset and used recovery code is in the activity log. The factor tables are closed to the runtime roles. |
|
|
119
120
|
|
|
120
121
|
## Findings of the MVP review and their fixes
|
|
121
122
|
|
|
@@ -240,3 +241,4 @@ A second full review, mainly of what end users and API callers can reach. Regres
|
|
|
240
241
|
10. With database-account authentication: list exact roles or use a dedicated membership role, and limit what those roles may connect to in `pg_hba.conf` (they can reach the database with their password outside pgkiln too).
|
|
241
242
|
11. Turn on two-factor sign-in for the builder (Instance settings → Two-factor sign-in, at least for administrators) once two administrators have a passkey or an authenticator app; set `PUBLIC_URL` to the address developers use (passkeys belong to its host name), require it per workspace where the instance policy is too broad, keep *Trust a browser* short or at 0 on shared machines, keep `PGKILN_SECRET_KEY` backed up, and keep the recovery commands (`pgkiln admin reset-2fa`) for people with server access only.
|
|
242
243
|
12. With single sign-on for developers: leave *Link an existing developer with the same user name* off unless you trust the provider's user names, set a developers group for automatic accounts, make at least one administrator break-glass (with a second factor and a password kept safe) before a workspace requires single sign-on, and keep `pgkiln admin builder-sign-in password` for people with server access only.
|
|
244
|
+
13. Require two-factor sign-in of an application's users at least for administrators (Application settings → Sign-in methods → Two-factor sign-in → *Required for some roles*: `admin`); the Advisor warns when it is missing. Keep `PGKILN_SECRET_KEY` backed up: without it the authenticator apps stop working and users need their recovery codes or a reset.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
-- ---------------------------------------------------------------------
|
|
2
|
+
-- 132: two-step sign-in for application users (sprint 130, SEC-3 part 1;
|
|
3
|
+
-- beyond APEX, which has no second factor for application accounts).
|
|
4
|
+
--
|
|
5
|
+
-- meta.account_factor: an account's second factors. This sprint: an
|
|
6
|
+
-- authenticator app (TOTP, RFC 6238), its secret encrypted with the
|
|
7
|
+
-- instance key (PGKILN_SECRET_KEY), like a developer's (128). last_step is
|
|
8
|
+
-- the last 30-second step a code was accepted for, so a code works once.
|
|
9
|
+
-- An account's factors serve every application it may use.
|
|
10
|
+
--
|
|
11
|
+
-- meta.account_recovery_code: ten one-time codes per account, as SHA-256
|
|
12
|
+
-- of the normalised code; confirmed: the user said they saved them.
|
|
13
|
+
--
|
|
14
|
+
-- meta.app.mfa, per application (exported with it):
|
|
15
|
+
-- off : no second step (the default)
|
|
16
|
+
-- optional : users who added an authenticator app give a code
|
|
17
|
+
-- required : every user gives a code; without an app, they add one while
|
|
18
|
+
-- signing in
|
|
19
|
+
-- roles : required for users with one of mfa_roles, optional for others
|
|
20
|
+
-- It covers the user directory's passwords and LDAP directories; an identity
|
|
21
|
+
-- provider (OpenID Connect, SAML) decides on its own second factor.
|
|
22
|
+
--
|
|
23
|
+
-- Owner-only, like meta.persistent_login: the runtime roles never read them.
|
|
24
|
+
-- Installation data: not exported with an application or a workspace.
|
|
25
|
+
-- ---------------------------------------------------------------------
|
|
26
|
+
create table meta.account_factor (
|
|
27
|
+
id int generated always as identity primary key,
|
|
28
|
+
account_id int not null references meta.account on delete cascade,
|
|
29
|
+
kind text not null check (kind in ('totp')),
|
|
30
|
+
name text not null check (length(name) between 1 and 60),
|
|
31
|
+
secret_enc text not null,
|
|
32
|
+
last_step bigint,
|
|
33
|
+
created_at timestamptz not null default now(),
|
|
34
|
+
last_used_at timestamptz
|
|
35
|
+
);
|
|
36
|
+
create index on meta.account_factor (account_id);
|
|
37
|
+
revoke all on meta.account_factor from public;
|
|
38
|
+
comment on table meta.account_factor is
|
|
39
|
+
'An application account''s second factors (132): authenticator apps (TOTP) with the secret encrypted with the instance key.';
|
|
40
|
+
|
|
41
|
+
create table meta.account_recovery_code (
|
|
42
|
+
account_id int not null references meta.account on delete cascade,
|
|
43
|
+
code_hash text not null,
|
|
44
|
+
confirmed boolean not null default false,
|
|
45
|
+
created_at timestamptz not null default now(),
|
|
46
|
+
used_at timestamptz,
|
|
47
|
+
primary key (account_id, code_hash)
|
|
48
|
+
);
|
|
49
|
+
revoke all on meta.account_recovery_code from public;
|
|
50
|
+
comment on table meta.account_recovery_code is
|
|
51
|
+
'One-time recovery codes of application accounts (132), as sha256 hex of the normalised code.';
|
|
52
|
+
|
|
53
|
+
alter table meta.app
|
|
54
|
+
add column mfa text not null default 'off' check (mfa in ('off', 'optional', 'required', 'roles')),
|
|
55
|
+
add column mfa_roles text[] not null default '{}';
|
|
56
|
+
comment on column meta.app.mfa is
|
|
57
|
+
'Two-step sign-in for the application''s users (132): off, optional, required, or roles (required for mfa_roles).';
|
|
58
|
+
comment on column meta.app.mfa_roles is 'Roles (lower case) that must use two-step sign-in when mfa = roles.';
|
|
@@ -138,7 +138,7 @@ the 26.2 comparison.)
|
|
|
138
138
|
| APEX accounts | ✅ | Instance-wide user directory, bcrypt, session rotation, idle and absolute timeouts |
|
|
139
139
|
| Application Access Control (roles per app, any-user switch) | ✅ | Access control per application |
|
|
140
140
|
| Social sign-in / OpenID Connect | ✅ | Any OIDC provider (Entra ID, Google, Okta, Keycloak, …): PKCE, group → role mapping, account linking, automatic accounts |
|
|
141
|
-
| Multi-factor authentication | ✅ | As in APEX: through the identity provider (OpenID Connect, SAML). Beyond APEX (sprints 126–128): the builder itself has two-factor sign-in with passkeys (WebAuthn, also on their own without a password), authenticator apps (TOTP) and recovery codes, trusted browsers, an instance and per-workspace policy with a grace period and lockout recovery ([chapter 3](guide/03-builder.md#two-factor-sign-in))
|
|
141
|
+
| Multi-factor authentication | ✅ | As in APEX: through the identity provider (OpenID Connect, SAML). Beyond APEX (sprints 126–128): the builder itself has two-factor sign-in with passkeys (WebAuthn, also on their own without a password), authenticator apps (TOTP) and recovery codes, trusted browsers, an instance and per-workspace policy with a grace period and lockout recovery ([chapter 3](guide/03-builder.md#two-factor-sign-in)). Sprint 130: application users too, per application (off, optional, required, required for roles) with authenticator apps and recovery codes, added while signing in or on My account, reset from Users ([chapter 8](guide/08-security.md#two-factor-sign-in)) |
|
|
142
142
|
| Change own password | ✅ | A built-in *My account* page (APEX offers the API `CHANGE_CURRENT_USER_PW`) |
|
|
143
143
|
| Password expiry, change on first use, admin reset, complexity | ✅ | Lifetime in days, expire/unexpire, admin reset, length and letters+digits rules, unlock |
|
|
144
144
|
| Lockout after failed sign-ins | ✅ | Per user and per IP, time-based (APEX: until an administrator unlocks) |
|
|
@@ -300,6 +300,9 @@ Small but real differences, for teams comparing the two:
|
|
|
300
300
|
passkey alone), authenticator apps (TOTP), recovery codes, a policy for administrators, all developers or a
|
|
301
301
|
workspace's developers with a grace period, and lockout recovery on the
|
|
302
302
|
command line ([chapter 3](guide/03-builder.md#two-factor-sign-in)). APEX relies on the identity provider.
|
|
303
|
+
- (sprint 130) **Two-factor sign-in for application users**: per application and per role, with authenticator apps
|
|
304
|
+
and recovery codes, added while signing in when required ([chapter 8](guide/08-security.md#two-factor-sign-in)).
|
|
305
|
+
APEX's application authentication schemes have no second factor.
|
|
303
306
|
- One RLS policy set protects both the web UI and the REST API.
|
|
304
307
|
- An import can be checked before it commits (`pgkiln import --check`): SQL that names a missing
|
|
305
308
|
table or column refuses the deployment instead of failing at run time.
|
|
@@ -410,6 +410,46 @@ opening another application of the group signs the user in there without the sig
|
|
|
410
410
|
|
|
411
411
|
Applications of different groups, and applications without a group, sign in on their own.
|
|
412
412
|
|
|
413
|
+
### Two-factor sign-in
|
|
414
|
+
|
|
415
|
+
APEX has no second factor for an application's own accounts: its documented route is an identity provider whose
|
|
416
|
+
sign-on policy asks for one, or a hand-written TOTP check in a custom authentication scheme. pgkiln has it built in.
|
|
417
|
+
**Application settings → Sign-in methods → Two-factor sign-in → Second step**:
|
|
418
|
+
|
|
419
|
+
| Setting | Who gives a code after the password |
|
|
420
|
+
|---|---|
|
|
421
|
+
| **Off** (the default) | Nobody |
|
|
422
|
+
| **Optional** | Users who added an authenticator app on *My account* |
|
|
423
|
+
| **Required** | Everybody. A user without an app adds one while signing in: a QR code, the app's first code, then ten recovery codes shown once |
|
|
424
|
+
| **Required for some roles** | Users with one of the roles in *Required for roles* (for example `admin, manager`); others as with *Optional* |
|
|
425
|
+
|
|
426
|
+
How it works:
|
|
427
|
+
|
|
428
|
+
- The second step follows the user directory's **password** and **LDAP** directories. An identity provider
|
|
429
|
+
([OpenID Connect](#single-sign-on-openid-connect), [SAML](#single-sign-on-saml-20)) asks for its own second factor;
|
|
430
|
+
database accounts, custom authentication and HTTP header authentication are not covered.
|
|
431
|
+
- The code comes from any authenticator app (TOTP, RFC 6238: Google Authenticator, Microsoft Authenticator,
|
|
432
|
+
1Password …), each code once, one 30-second step either side for clock drift. A **recovery code** (ten per account,
|
|
433
|
+
each usable once) works instead, and leads to *My account*, which says how many are left.
|
|
434
|
+
- Until the code is right there is no session: the pending sign-in waits five minutes (ten while adding an app) in
|
|
435
|
+
the signed-out session. Wrong codes count as failed sign-ins, so the usual lockout applies.
|
|
436
|
+
- An account's apps serve every application it uses, and each application decides whether it asks for them.
|
|
437
|
+
- **My account → Two-factor sign-in** adds an app (QR code or key, then its first code), shows new recovery codes,
|
|
438
|
+
and removes an app with a current code or a recovery code. The last app can't be removed while the application
|
|
439
|
+
requires a code of the user.
|
|
440
|
+
- A *Keep me signed in* or session-sharing sign-in skips the second step only when it was made with one (its method
|
|
441
|
+
ends in `+2fa`, shown in the Activity monitor); one made with just a password signs in again with the code.
|
|
442
|
+
- **Users → account → Two-factor sign-in** shows who has an app; **Reset two-factor sign-in** (with a reason, logged
|
|
443
|
+
as `2fa_reset`) removes the apps and recovery codes after a lost phone and signs the account out everywhere. Where
|
|
444
|
+
an application requires the step, the user adds a new app at the next sign-in.
|
|
445
|
+
- The apps' secrets are encrypted with the instance key `PGKILN_SECRET_KEY` (in `meta.account_factor`, readable by
|
|
446
|
+
the owner connection only); without that key *Required* can't be chosen, and the sign-in refuses rather than skips
|
|
447
|
+
the step. Recovery codes are stored as SHA-256 hashes.
|
|
448
|
+
- The **Advisor** warns when users with the role `admin` sign in with only a password.
|
|
449
|
+
|
|
450
|
+
Passkeys, e-mail codes, asking again before a sensitive page (step-up) and tokens for REST and MCP that need a
|
|
451
|
+
two-factor sign-in come in a later release.
|
|
452
|
+
|
|
413
453
|
### What sign-in protects against
|
|
414
454
|
|
|
415
455
|
- **Brute force**: after 5 failed attempts for a username (or 50 from one IP address) within 15
|
|
@@ -418,13 +458,13 @@ Applications of different groups, and applications without a group, sign in on t
|
|
|
418
458
|
time.
|
|
419
459
|
- **Session fixation**: the session token is replaced at sign-in.
|
|
420
460
|
- **Stale sessions**: 60 minutes idle or 8 hours total (configurable).
|
|
461
|
+
- **Stolen passwords**: [two-factor sign-in](#two-factor-sign-in) asks for a code from an authenticator app, for every
|
|
462
|
+
user or for some roles; with an identity provider ([OpenID Connect](#single-sign-on-openid-connect),
|
|
463
|
+
[SAML](#single-sign-on-saml-20)) the provider asks for its own. Developers have
|
|
464
|
+
[two-factor sign-in](03-builder.md#two-factor-sign-in) for the builder too.
|
|
421
465
|
|
|
422
466
|
All sign-ins, failures and lockouts appear in the **Activity** monitor.
|
|
423
467
|
|
|
424
|
-
A second factor for an application's users comes from the identity provider ([OpenID Connect](#single-sign-on-openid-connect),
|
|
425
|
-
[SAML](#single-sign-on-saml-20)). Developers can use an authenticator app for the builder itself:
|
|
426
|
-
[two-factor sign-in](03-builder.md#two-factor-sign-in).
|
|
427
|
-
|
|
428
468
|
## Authorization: what may the user do?
|
|
429
469
|
|
|
430
470
|
### Authorization schemes
|
|
@@ -643,4 +683,5 @@ decision.
|
|
|
643
683
|
4. Checksum protection on pages (the default).
|
|
644
684
|
5. Business rules in constraints, triggers or functions, not only in validations.
|
|
645
685
|
6. Debug mode and debug messages off.
|
|
646
|
-
7.
|
|
686
|
+
7. [Two-factor sign-in](#two-factor-sign-in) required at least for administrators (the Advisor checks it).
|
|
687
|
+
8. Review the app's **Settings → Security checklist** and **Activity** monitor now and then.
|
|
@@ -337,6 +337,7 @@ All in schema `meta`. `id` columns are generated; `seq` orders siblings (default
|
|
|
337
337
|
| `sso_providers` | text[] | Names of identity providers (OpenID Connect or SAML) offered on the login page |
|
|
338
338
|
| `ldap_directories` | text[] | LDAP directories the password form checks, after local accounts |
|
|
339
339
|
| `remember_me_days` | int | Days a "Keep me signed in" sign-in lasts; NULL = not offered |
|
|
340
|
+
| `mfa`, `mfa_roles` | text, text[] | [Two-factor sign-in](08-security.md#two-factor-sign-in): `off`, `optional`, `required` or `roles` (required for `mfa_roles`) |
|
|
340
341
|
| `pwa`, `pwa_short_name`, `pwa_icon`, `pwa_offline_pages`, `pwa_offline_submit` | boolean, text, bytea, boolean, boolean | Progressive Web App ([chapter 17](17-mobile.md)) |
|
|
341
342
|
| `db_role` | text | Database role every request runs as |
|
|
342
343
|
| `api_role` | text | Database role of REST API tokens for this app (PostgREST switches to it) |
|
|
@@ -510,7 +511,8 @@ navigation entries and application processes have the same `build_option` column
|
|
|
510
511
|
| `supporting_script` | Supporting objects per app (see above) | no |
|
|
511
512
|
| `document_template` | Document templates per app: `name`, `description`, `query`, `template`, `layout`, `filename`, `authz` | yes (read) |
|
|
512
513
|
| `ldap_identity` | Links an account to a directory entry (`directory_id`, `subject` = entryUUID or DN) | no |
|
|
513
|
-
| `persistent_login` | "Keep me signed in" tokens: `token_hash`, `account_id`, `app_id`, `groups`, `method
|
|
514
|
+
| `persistent_login` | "Keep me signed in" tokens: `token_hash`, `account_id`, `app_id`, `groups`, `method` (`+2fa` after a second step), `expires_at` | no |
|
|
515
|
+
| `account_factor`, `account_recovery_code` | An account's authenticator apps (secret encrypted with the instance key) and recovery codes (SHA-256) | no |
|
|
514
516
|
| `instance_setting` | Secrets, e.g. the URL checksum key | no |
|
|
515
517
|
| `setting` | Account settings: `password_min_length`, `password_require_mixed`, `password_lifetime_days` | yes (read) |
|
|
516
518
|
| `text_message` | Per app: `name`, `language`, `text` | yes |
|
|
@@ -609,6 +611,8 @@ pgkiln's icons; its filter box also searches the Lucide icons by name and search
|
|
|
609
611
|
| any page `?doc=NAME` | Download a document template filled with the page's values |
|
|
610
612
|
| `POST /a/:alias/account/devices` | Sign out on all devices ("Keep me signed in") |
|
|
611
613
|
| `POST /a/:alias/password` | Change an expired password while signing in |
|
|
614
|
+
| `GET/POST /a/:alias/login/2fa`, `POST /a/:alias/login/2fa/done` | The second step of signing in: a code, or adding the first app and seeing the recovery codes |
|
|
615
|
+
| `POST /a/:alias/account/2fa/start`, `…/cancel`, `…/confirm`, `…/codes`, `…/codes/confirm`, `…/:id/delete` | My account → Two-factor sign-in |
|
|
612
616
|
| `GET/POST /a/:alias/account`, `POST /a/:alias/account/password`, `POST /a/:alias/account/theme`, `POST /a/:alias/account/style` | My account, own password, the light/dark switch, the [style variant](14-globalization.md#style-variants-theme-roller) switch |
|
|
613
617
|
| `POST /a/:alias/tz` | The browser's time zone for the session (automatic time zone; sent by `app.js`, CSRF token required) |
|
|
614
618
|
| any page `?lang=xx` | Switch the language for the session |
|
|
@@ -98,7 +98,8 @@ APEX's "Social Sign-In" scheme, with identity-provider groups mapped to applicat
|
|
|
98
98
|
in to a second app is then silent via the identity provider's session. See
|
|
99
99
|
[chapter 8](08-security.md#single-sign-on-openid-connect). **SAML 2.0** providers and **LDAP /
|
|
100
100
|
Active Directory** passwords work the same way (groups → roles), and *Keep me signed in* matches
|
|
101
|
-
APEX's persistent authentication.
|
|
101
|
+
APEX's persistent authentication. Unlike APEX, the user directory's accounts can have
|
|
102
|
+
[two-factor sign-in](08-security.md#two-factor-sign-in) (an authenticator app), per application and per role. **Database accounts** sign in with PostgreSQL login roles, and
|
|
102
103
|
**custom authentication** calls your own PL/pgSQL function (APEX: a custom PL/SQL scheme), see
|
|
103
104
|
[chapter 8](08-security.md#custom-authentication-a-plpgsql-function). The **login page** (APEX: page 9999 with
|
|
104
105
|
the Login region template) is a page you design in the Page Designer around a **Login** region, and
|
|
@@ -62,6 +62,10 @@ src/
|
|
|
62
62
|
dbauth.ts database-account authentication: role lists, a short connection as the role (DATABASE_URL target), membership/superuser checks
|
|
63
63
|
customauth.ts custom authentication: the app's function or PL/pgSQL body (a pg_temp function) and post-authentication code, as the app's role
|
|
64
64
|
remember.ts "Keep me signed in": rotating persistent sign-in tokens
|
|
65
|
+
mfa.ts second factors: TOTP, recovery codes, a FactorStore per kind of user (developers, accounts);
|
|
66
|
+
the developers' policy, passkeys, trusted browsers (webauthn.ts: WebAuthn checks)
|
|
67
|
+
account-mfa.ts (sprint 130) two-factor sign-in for application accounts: the application's rule (off, optional,
|
|
68
|
+
required, roles), secondStep, carriesSecondStep (remembered/shared sign-ins), resets
|
|
65
69
|
workflow.ts workflows: step checks, the runner with parallel branches (NOTIFY + polling), invoke_api steps
|
|
66
70
|
(the call between two transactions, with a lease), Advisor references, the diagram;
|
|
67
71
|
(sprint 114) send_mail and draft steps, switch cases on task outcomes, the diagram as a standalone SVG
|
|
@@ -171,6 +175,8 @@ src/
|
|
|
171
175
|
routes.ts HTTP handlers: show, submit, dynamic actions, cascading lists, login
|
|
172
176
|
signin.ts the sign-in form (built-in page and the login region of an application's own login page), safeNext, passwordResetAvailable
|
|
173
177
|
password-reset.ts Forgot password: request (same answer either way), the link (token into the session), the new password
|
|
178
|
+
two-step.ts (sprint 130) the second step of signing in (/login/2fa: a code, or the first app and its recovery
|
|
179
|
+
codes), passwordSignIn, and My account → Two-factor sign-in
|
|
174
180
|
context.ts PageContext, dbg()/timed() debug helpers, bind values, substitutions, public error messages, writeOut (streamed responses with back pressure)
|
|
175
181
|
authz.ts authorization schemes, conditions, visibility (menu requests count as buttons)
|
|
176
182
|
engine.ts form fetch, validations, processes (conditions, execution chains, queueing background chains; web requests queued by an sql process are made right after it), application processes
|
package/package.json
CHANGED
package/public/app.css
CHANGED
|
@@ -2164,3 +2164,13 @@ body.nav-pillar-dark .t-nav details:has(> summary.in-trail) > ul { border-inline
|
|
|
2164
2164
|
.region[aria-busy="true"]::after { animation: busy-slide 1.2s cubic-bezier(0.45, 0.05, 0.55, 0.95) infinite; }
|
|
2165
2165
|
}
|
|
2166
2166
|
@keyframes busy-slide { from { background-position: -60% 0, 0 0; } to { background-position: 160% 0, 0 0; } }
|
|
2167
|
+
|
|
2168
|
+
/* (sprint 130) two-step sign-in: the QR code for an authenticator app, its key and the recovery codes */
|
|
2169
|
+
.mfa-qr { margin: .5rem 0 1rem; }
|
|
2170
|
+
.mfa-qr svg { width: 200px; max-width: 100%; height: auto; background: #fff; padding: 8px; border-radius: 6px; }
|
|
2171
|
+
.mfa-secret { word-break: break-all; letter-spacing: .05em; }
|
|
2172
|
+
.mfa-steps { padding-left: 1.25rem; margin: 0; }
|
|
2173
|
+
.mfa-codes { columns: 2; column-gap: 2rem; padding-left: 1.5rem; }
|
|
2174
|
+
.mfa-factors { list-style: none; padding: 0; margin: 0 0 .75rem; }
|
|
2175
|
+
.mfa-factors li { padding: .4rem 0; border-bottom: 1px solid var(--border); }
|
|
2176
|
+
@media (max-width: 480px) { .mfa-codes { columns: 1; } }
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { owner } from './db.ts';
|
|
2
|
+
import { ACCOUNTS, storeAddTotp, storeCheck, storeCodesLeft, storeConfirmCodes, storeHasFactor, storeNewCodes } from './mfa.ts';
|
|
3
|
+
|
|
4
|
+
// (sprint 130, SEC-3) Two-step sign-in for application users, beyond APEX (whose application authentication has no
|
|
5
|
+
// second factor). An account's authenticator apps and recovery codes (meta.account_factor, account_recovery_code,
|
|
6
|
+
// migration 132) serve every application it may use; each application decides whether it asks for them (meta.app.mfa):
|
|
7
|
+
// off, optional (users who added an app give a code), required, or required for some roles. The second step follows
|
|
8
|
+
// the user directory's passwords and LDAP directories; an identity provider decides on its own second factor (SEC-4).
|
|
9
|
+
// A remembered or shared sign-in carries its method: only one that ends in "+2fa" stands in for the second step.
|
|
10
|
+
|
|
11
|
+
export type AppMfa = 'off' | 'optional' | 'required' | 'roles';
|
|
12
|
+
export const APP_MFA: AppMfa[] = ['off', 'optional', 'required', 'roles'];
|
|
13
|
+
|
|
14
|
+
export interface MfaApp { authentication: string; mfa?: AppMfa | null; mfa_roles?: string[] | null }
|
|
15
|
+
|
|
16
|
+
/** Whether the application has a second step at all (its own accounts, and not "off"). */
|
|
17
|
+
export const mfaOn = (a: MfaApp) => a.authentication === 'app_users' && !!a.mfa && a.mfa !== 'off';
|
|
18
|
+
|
|
19
|
+
/** Whether the application requires a second step of a user with these roles. */
|
|
20
|
+
export function mfaRequired(a: MfaApp, roles: string[]): boolean {
|
|
21
|
+
if (!mfaOn(a)) return false;
|
|
22
|
+
if (a.mfa === 'required') return true;
|
|
23
|
+
const need = new Set((a.mfa_roles ?? []).map((r) => r.toLowerCase()));
|
|
24
|
+
return a.mfa === 'roles' && roles.some((r) => need.has(r.toLowerCase()));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The sign-in methods a second step follows (the directory's password, an LDAP directory). */
|
|
28
|
+
export const knowsPassword = (method: string | undefined) => !method || method.startsWith('password') || method.startsWith('ldap:');
|
|
29
|
+
export const MFA_SUFFIX = '+2fa';
|
|
30
|
+
export const withSecondStep = (method: string | undefined) => `${method ?? 'password'}${MFA_SUFFIX}`;
|
|
31
|
+
|
|
32
|
+
/** An active account's id by user name (accounts are matched without regard to case). */
|
|
33
|
+
export async function accountId(username: string): Promise<number | null> {
|
|
34
|
+
return (await owner.one<{ id: number }>('select id from meta.account where lower(username) = lower($1) and active', [username]))?.id ?? null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What a password (or LDAP) sign-in to this application still needs: 'code' (the user has an authenticator app),
|
|
39
|
+
* 'enrol' (required, and the user has none yet) or null (no second step).
|
|
40
|
+
*/
|
|
41
|
+
export async function secondStep(a: MfaApp, username: string, roles: string[]): Promise<'code' | 'enrol' | null> {
|
|
42
|
+
if (!mfaOn(a)) return null;
|
|
43
|
+
const id = await accountId(username);
|
|
44
|
+
if (id === null) return null;
|
|
45
|
+
if (await storeHasFactor(ACCOUNTS, id)) return 'code';
|
|
46
|
+
return mfaRequired(a, roles) ? 'enrol' : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Whether a remembered or shared sign-in may sign the user in here without a second step: one made with an identity
|
|
51
|
+
* provider, one that had a second step, or a user this application asks nothing of.
|
|
52
|
+
*/
|
|
53
|
+
export async function carriesSecondStep(a: MfaApp, username: string, roles: string[], method: string | undefined): Promise<boolean> {
|
|
54
|
+
if (!knowsPassword(method) || method?.endsWith(MFA_SUFFIX)) return true;
|
|
55
|
+
return (await secondStep(a, username, roles)) === null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface AccountFactor { id: number; name: string; created_at: string; last_used_at: string | null }
|
|
59
|
+
|
|
60
|
+
export async function accountFactors(id: number): Promise<AccountFactor[]> {
|
|
61
|
+
return (await owner.query<AccountFactor>('select id, name, created_at, last_used_at from meta.account_factor where account_id = $1 order by id', [id])).rows;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const accountHasFactor = (id: number) => storeHasFactor(ACCOUNTS, id);
|
|
65
|
+
export const accountCodesLeft = (id: number) => storeCodesLeft(ACCOUNTS, id);
|
|
66
|
+
export const addAccountTotp = (id: number, name: string, secret: string, step: number) => storeAddTotp(ACCOUNTS, id, name, secret, step);
|
|
67
|
+
export const newAccountCodes = (id: number) => storeNewCodes(ACCOUNTS, id);
|
|
68
|
+
export const confirmAccountCodes = (id: number) => storeConfirmCodes(ACCOUNTS, id);
|
|
69
|
+
export const checkAccountCode = (id: number, code: string) => storeCheck(ACCOUNTS, id, code);
|
|
70
|
+
|
|
71
|
+
/** Remove one of the account's authenticator apps (and the recovery codes with the last one). */
|
|
72
|
+
export async function removeAccountFactor(id: number, factorId: number): Promise<boolean> {
|
|
73
|
+
return owner.tx(async (c) => {
|
|
74
|
+
const gone = (await c.query('delete from meta.account_factor where id = $1 and account_id = $2', [factorId, id])).rowCount;
|
|
75
|
+
if (gone && !(await c.query('select 1 from meta.account_factor where account_id = $1', [id])).rowCount)
|
|
76
|
+
await c.query('delete from meta.account_recovery_code where account_id = $1', [id]);
|
|
77
|
+
return !!gone;
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** (Manage users) Remove every second factor of an account and end its sessions and remembered sign-ins. */
|
|
82
|
+
export async function resetAccountFactors(id: number): Promise<boolean> {
|
|
83
|
+
return owner.tx(async (c) => {
|
|
84
|
+
const acc = (await c.query<{ username: string }>('select username from meta.account where id = $1', [id])).rows[0];
|
|
85
|
+
if (!acc) return false;
|
|
86
|
+
await c.query('delete from meta.account_factor where account_id = $1', [id]);
|
|
87
|
+
await c.query('delete from meta.account_recovery_code where account_id = $1', [id]);
|
|
88
|
+
await c.query('delete from meta.persistent_login where account_id = $1', [id]);
|
|
89
|
+
await c.query('delete from meta.shared_login where account_id = $1', [id]);
|
|
90
|
+
await c.query('delete from meta.session where app_id is not null and lower(username) = lower($1)', [acc.username]);
|
|
91
|
+
return true;
|
|
92
|
+
});
|
|
93
|
+
}
|
package/src/builder/advisor.ts
CHANGED
|
@@ -187,6 +187,14 @@ export async function advise(appId: number, tx?: pg.ClientBase, opts: { db?: Db
|
|
|
187
187
|
else if (!all.some((x) => x.kind === 'region' && x.row.type === 'login' && Number(x.row.page_no) === Number(app.login_page)))
|
|
188
188
|
findings.push({ severity: 'error', entry: null, field, message: `Page ${app.login_page} has no Login region: nobody can sign in.` });
|
|
189
189
|
}
|
|
190
|
+
// (sprint 130, SEC-3) administrators of the application who sign in with only a password
|
|
191
|
+
if (app.authentication === 'app_users' && (app.local_login || (app.ldap_directories ?? []).length)) {
|
|
192
|
+
const covered = app.mfa === 'required' || (app.mfa === 'roles' && (app.mfa_roles ?? []).includes('admin'));
|
|
193
|
+
const admins = covered ? 0 : (await one(`select count(*)::int as n from meta.app_access where app_id = $1 and 'admin' = any(roles)`, [appId])).n;
|
|
194
|
+
if (admins)
|
|
195
|
+
findings.push({ severity: 'warning', entry: null, field: 'Application settings → Two-factor sign-in',
|
|
196
|
+
message: `${admins === 1 ? 'A user' : `${admins} users`} with the admin role sign${admins === 1 ? 's' : ''} in with only a password: require two-factor sign-in (Required, or Required for roles: admin).` });
|
|
197
|
+
}
|
|
190
198
|
// (089) a page's group exists
|
|
191
199
|
for (const p of (await query(`select p.page_no, p.page_group from meta.page p where p.app_id = $1 and p.page_group is not null
|
|
192
200
|
and not exists (select 1 from meta.page_group g where g.app_id = p.app_id and g.name = p.page_group) order by 1`, [appId])).rows)
|
package/src/builder/i18n/de.ts
CHANGED
|
@@ -1870,4 +1870,10 @@ export const de: BuilderMessages = {
|
|
|
1870
1870
|
'wsp.sso_off': 'Die Entwickler des Workspace dürfen wieder das pgkiln-Kennwort verwenden.',
|
|
1871
1871
|
'wsp.sso_no_break_glass': 'Geben Sie zuerst einem Administrator Notfallzugang (Entwickler), damit sich jemand anmelden kann, wenn der Identitätsanbieter ausfällt.',
|
|
1872
1872
|
'wsp.sso_link_first': 'Verknüpfen Sie zuerst auf Ihrer Sicherheitsseite eine Identität, sonst könnten Sie sich selbst nicht anmelden.',
|
|
1873
|
+
'us.mfa_title': 'Zwei-Faktor-Anmeldung',
|
|
1874
|
+
'us.mfa_status': 'Authenticator-Apps: {n}. Verbleibende Wiederherstellungscodes: {codes}.',
|
|
1875
|
+
'us.mfa_none': 'Noch keine Authenticator-App.',
|
|
1876
|
+
'us.mfa_reset_help': 'Entfernt die Authenticator-Apps und Wiederherstellungscodes von {user} und meldet das Konto überall ab. Wo eine Anwendung die Zwei-Faktor-Anmeldung verlangt, wird bei der nächsten Anmeldung eine neue App hinzugefügt. Wird protokolliert.',
|
|
1877
|
+
'us.mfa_reset_done': 'Die Zwei-Faktor-Anmeldung von {user} wurde zurückgesetzt.',
|
|
1878
|
+
'us.mfa_reason_needed': 'Geben Sie einen Grund für das Zurücksetzen an.',
|
|
1873
1879
|
};
|
package/src/builder/i18n/en.ts
CHANGED
|
@@ -1873,4 +1873,10 @@ export const en = {
|
|
|
1873
1873
|
'wsp.sso_off': 'The workspace’s developers may use the pgkiln password again.',
|
|
1874
1874
|
'wsp.sso_no_break_glass': 'Make an administrator break-glass first (Developers), so someone can still sign in when the identity provider fails.',
|
|
1875
1875
|
'wsp.sso_link_first': 'Link an identity on your Security page first, or you could not sign in yourself.',
|
|
1876
|
+
'us.mfa_title': 'Two-factor sign-in',
|
|
1877
|
+
'us.mfa_status': 'Authenticator apps: {n}. Recovery codes left: {codes}.',
|
|
1878
|
+
'us.mfa_none': 'No authenticator app yet.',
|
|
1879
|
+
'us.mfa_reset_help': 'Removes the authenticator apps and recovery codes of {user} and signs them out everywhere. Where an application requires two-factor sign-in, they add a new app at their next sign-in. Logged.',
|
|
1880
|
+
'us.mfa_reset_done': 'Two-factor sign-in of {user} was reset.',
|
|
1881
|
+
'us.mfa_reason_needed': 'Give a reason for the reset.',
|
|
1876
1882
|
} as const;
|
package/src/builder/i18n/es.ts
CHANGED
|
@@ -1870,4 +1870,10 @@ export const es: BuilderMessages = {
|
|
|
1870
1870
|
'wsp.sso_off': 'Los desarrolladores del espacio de trabajo pueden volver a usar la contraseña de pgkiln.',
|
|
1871
1871
|
'wsp.sso_no_break_glass': 'Primero dé acceso de emergencia a un administrador (Desarrolladores), para que alguien pueda entrar si falla el proveedor de identidad.',
|
|
1872
1872
|
'wsp.sso_link_first': 'Vincule primero una identidad en su página de seguridad, o usted mismo no podría iniciar sesión.',
|
|
1873
|
+
'us.mfa_title': 'Inicio de sesión en dos pasos',
|
|
1874
|
+
'us.mfa_status': 'Aplicaciones de autenticación: {n}. Códigos de recuperación restantes: {codes}.',
|
|
1875
|
+
'us.mfa_none': 'Aún no hay ninguna aplicación de autenticación.',
|
|
1876
|
+
'us.mfa_reset_help': 'Quita las aplicaciones de autenticación y los códigos de recuperación de {user} y cierra todas sus sesiones. Donde una aplicación exija el inicio de sesión en dos pasos, añadirá una aplicación nueva en su próximo inicio de sesión. Queda registrado.',
|
|
1877
|
+
'us.mfa_reset_done': 'Se restableció el inicio de sesión en dos pasos de {user}.',
|
|
1878
|
+
'us.mfa_reason_needed': 'Indique un motivo para el restablecimiento.',
|
|
1873
1879
|
};
|
package/src/builder/i18n/fr.ts
CHANGED
|
@@ -1870,4 +1870,10 @@ export const fr: BuilderMessages = {
|
|
|
1870
1870
|
'wsp.sso_off': 'Les développeurs de l’espace de travail peuvent de nouveau utiliser le mot de passe pgkiln.',
|
|
1871
1871
|
'wsp.sso_no_break_glass': 'Donnez d’abord l’accès de secours à un administrateur (Développeurs), pour que quelqu’un puisse se connecter si le fournisseur d’identité tombe en panne.',
|
|
1872
1872
|
'wsp.sso_link_first': 'Liez d’abord une identité sur votre page Sécurité, sinon vous ne pourriez plus vous connecter.',
|
|
1873
|
+
'us.mfa_title': 'Connexion à deux facteurs',
|
|
1874
|
+
'us.mfa_status': 'Applications d’authentification : {n}. Codes de récupération restants : {codes}.',
|
|
1875
|
+
'us.mfa_none': 'Aucune application d’authentification pour l’instant.',
|
|
1876
|
+
'us.mfa_reset_help': 'Supprime les applications d’authentification et les codes de récupération de {user} et le déconnecte partout. Là où une application exige la connexion à deux facteurs, une nouvelle application est ajoutée à la prochaine connexion. Journalisé.',
|
|
1877
|
+
'us.mfa_reset_done': 'La connexion à deux facteurs de {user} a été réinitialisée.',
|
|
1878
|
+
'us.mfa_reason_needed': 'Indiquez la raison de la réinitialisation.',
|
|
1873
1879
|
};
|
package/src/builder/i18n/nl.ts
CHANGED
|
@@ -1870,4 +1870,10 @@ export const nl: BuilderMessages = {
|
|
|
1870
1870
|
'wsp.sso_off': 'De ontwikkelaars van de werkruimte mogen weer het pgkiln-wachtwoord gebruiken.',
|
|
1871
1871
|
'wsp.sso_no_break_glass': 'Geef eerst een beheerder noodtoegang (Ontwikkelaars), zodat iemand kan aanmelden als de identiteitsprovider uitvalt.',
|
|
1872
1872
|
'wsp.sso_link_first': 'Koppel eerst een identiteit op uw beveiligingspagina, anders kunt u zelf niet aanmelden.',
|
|
1873
|
+
'us.mfa_title': 'Aanmelden in twee stappen',
|
|
1874
|
+
'us.mfa_status': 'Authenticator-apps: {n}. Resterende herstelcodes: {codes}.',
|
|
1875
|
+
'us.mfa_none': 'Nog geen authenticator-app.',
|
|
1876
|
+
'us.mfa_reset_help': 'Verwijdert de authenticator-apps en herstelcodes van {user} en meldt het account overal af. Waar een applicatie aanmelden in twee stappen vereist, voegt de gebruiker bij de volgende aanmelding een nieuwe app toe. Wordt gelogd.',
|
|
1877
|
+
'us.mfa_reset_done': 'Aanmelden in twee stappen van {user} is gereset.',
|
|
1878
|
+
'us.mfa_reason_needed': 'Geef een reden voor de reset.',
|
|
1873
1879
|
};
|
package/src/builder/i18n/pt.ts
CHANGED
|
@@ -1870,4 +1870,10 @@ export const pt: BuilderMessages = {
|
|
|
1870
1870
|
'wsp.sso_off': 'Os desenvolvedores do espaço de trabalho podem voltar a usar a senha do pgkiln.',
|
|
1871
1871
|
'wsp.sso_no_break_glass': 'Primeiro dê acesso de emergência a um administrador (Desenvolvedores), para que alguém possa entrar se o provedor de identidade falhar.',
|
|
1872
1872
|
'wsp.sso_link_first': 'Vincule primeiro uma identidade na sua página de segurança, ou você mesmo não conseguiria entrar.',
|
|
1873
|
+
'us.mfa_title': 'Login em duas etapas',
|
|
1874
|
+
'us.mfa_status': 'Aplicativos autenticadores: {n}. Códigos de recuperação restantes: {codes}.',
|
|
1875
|
+
'us.mfa_none': 'Nenhum aplicativo autenticador ainda.',
|
|
1876
|
+
'us.mfa_reset_help': 'Remove os aplicativos autenticadores e os códigos de recuperação de {user} e encerra todas as sessões. Onde um aplicativo exigir login em duas etapas, um novo aplicativo será adicionado no próximo login. Registrado.',
|
|
1877
|
+
'us.mfa_reset_done': 'O login em duas etapas de {user} foi redefinido.',
|
|
1878
|
+
'us.mfa_reason_needed': 'Informe um motivo para a redefinição.',
|
|
1873
1879
|
};
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import type { FastifyInstance } from 'fastify';
|
|
2
2
|
import { owner } from '../db.ts';
|
|
3
|
+
import { APP_MFA, type AppMfa } from '../account-mfa.ts';
|
|
3
4
|
import { html, raw } from '../html.ts';
|
|
5
|
+
import { secretKeyConfigured } from '../secrets.ts';
|
|
4
6
|
import { back, BASE, developer, flash, type Req } from './ui.ts';
|
|
5
7
|
|
|
6
8
|
// Application settings → Sign-in methods (migration 087): the application's
|
|
7
9
|
// own login page (APEX: the login page, usually 9999) and "Forgot password?".
|
|
8
10
|
// "Create login page" adds a minimal public page with a login region and
|
|
9
|
-
// makes it the login page.
|
|
11
|
+
// makes it the login page. (sprint 130, SEC-3) Two-factor sign-in for the
|
|
12
|
+
// application's users: off, optional, required, or required for some roles.
|
|
10
13
|
|
|
11
14
|
interface AppRow {
|
|
12
15
|
id: number;
|
|
@@ -15,6 +18,8 @@ interface AppRow {
|
|
|
15
18
|
local_login: boolean;
|
|
16
19
|
login_page: number | null;
|
|
17
20
|
password_reset: boolean;
|
|
21
|
+
mfa: AppMfa;
|
|
22
|
+
mfa_roles: string[];
|
|
18
23
|
}
|
|
19
24
|
|
|
20
25
|
/** The fields in the settings form. */
|
|
@@ -41,14 +46,33 @@ export async function loginSettingsFields(a: AppRow) {
|
|
|
41
46
|
? html`Sent through mail service ${mail!.service} as ${mail!.from_address}.`
|
|
42
47
|
: html`<strong>Not offered yet:</strong> the application needs an enabled mail service with a From address (Workspace utilities → Mail services).`}
|
|
43
48
|
Only for the user directory's own passwords: not for LDAP, single sign-on, database accounts or custom authentication.</small></div>
|
|
49
|
+
</div>
|
|
50
|
+
<h3 id="two-factor">Two-factor sign-in</h3>
|
|
51
|
+
<div class="form-grid">
|
|
52
|
+
<div class="field"><label class="label" for="f_mfa">Second step</label>
|
|
53
|
+
<select id="f_mfa" name="mfa" aria-describedby="f_mfa_help">${(APP_MFA as string[]).map((m) => opt(m, MFA_LABELS[m as AppMfa], a.mfa))}</select>
|
|
54
|
+
<small class="help" id="f_mfa_help">After the password (or an LDAP directory), users give a code from an authenticator app or a recovery code. They add the app on <em>My account</em>, or while signing in when it is required. An identity provider asks for its own second factor. Accounts share their apps across applications.
|
|
55
|
+
${secretKeyConfigured() ? '' : html`<strong>Not available yet:</strong> the server needs <code>PGKILN_SECRET_KEY</code> to keep the apps' secrets.`}</small></div>
|
|
56
|
+
<div class="field"><label class="label" for="f_mfa_roles">Required for roles</label>
|
|
57
|
+
<input id="f_mfa_roles" name="mfa_roles" value="${(a.mfa_roles ?? []).join(', ')}" placeholder="admin, manager" aria-describedby="f_mfa_roles_help">
|
|
58
|
+
<small class="help" id="f_mfa_roles_help">With <em>Required for some roles</em>: users with one of these roles must use it, others may.</small></div>
|
|
44
59
|
</div>`;
|
|
45
60
|
}
|
|
46
61
|
|
|
62
|
+
const MFA_LABELS: Record<AppMfa, string> = { off: 'Off', optional: 'Optional (users may add an app)', required: 'Required', roles: 'Required for some roles' };
|
|
63
|
+
|
|
47
64
|
/** Save them (with the rest of the settings form). */
|
|
48
65
|
export async function saveLoginSettings(appId: string, b: Record<string, string | undefined>) {
|
|
49
66
|
const page = b.login_page?.trim() ? Number(b.login_page) : null;
|
|
50
67
|
if (page !== null && !(await owner.one('select 1 from meta.page where app_id = $1 and page_no = $2', [appId, page]))) throw new Error(`Login page: there is no page ${b.login_page}.`);
|
|
51
|
-
|
|
68
|
+
const mfa = (APP_MFA as string[]).includes(b.mfa ?? '') ? (b.mfa as AppMfa) : 'off';
|
|
69
|
+
const roles = [...new Set((b.mfa_roles ?? '').split(',').map((r) => r.trim().toLowerCase()).filter(Boolean))];
|
|
70
|
+
if (roles.some((r) => r.length > 100)) throw new Error('Two-factor sign-in: a role name is too long.');
|
|
71
|
+
if (mfa === 'roles' && !roles.length) throw new Error('Two-factor sign-in: name the roles that must use it.');
|
|
72
|
+
// without the instance key, users could not add an app: requiring one would lock them out
|
|
73
|
+
if ((mfa === 'required' || mfa === 'roles') && !secretKeyConfigured()) throw new Error('Two-factor sign-in: the server needs PGKILN_SECRET_KEY before it can be required.');
|
|
74
|
+
await owner.query('update meta.app set login_page = $2, password_reset = $3, mfa = $4, mfa_roles = $5 where id = $1',
|
|
75
|
+
[appId, page, b.password_reset === 'true', mfa, roles]);
|
|
52
76
|
}
|
|
53
77
|
|
|
54
78
|
export async function loginPageRoutes(app: FastifyInstance) {
|
package/src/builder/users.ts
CHANGED
|
@@ -4,6 +4,9 @@ import { owner } from '../db.ts';
|
|
|
4
4
|
import { appAllowed } from './workspaces.ts';
|
|
5
5
|
import { html, raw } from '../html.ts';
|
|
6
6
|
import { accountSettings, clearAccountSettings, passwordProblem } from '../accounts.ts';
|
|
7
|
+
import { accountCodesLeft, accountFactors, resetAccountFactors } from '../account-mfa.ts';
|
|
8
|
+
import { icon } from '../icons.ts';
|
|
9
|
+
import { clientIp, logActivity } from '../session.ts';
|
|
7
10
|
import { loginMaxFailuresPerUser, loginWindowMinutes } from '../security.ts';
|
|
8
11
|
import { acsUrl, metadataUrl, spEntityId } from '../saml.ts';
|
|
9
12
|
import { discover, publicUrl, redirectUri } from '../sso.ts';
|
|
@@ -107,7 +110,8 @@ export async function usersRoutes(app: FastifyInstance) {
|
|
|
107
110
|
const users = (
|
|
108
111
|
await owner.query(
|
|
109
112
|
`select a.*, coalesce((select jsonb_agg(jsonb_build_object('alias', p.alias, 'roles', aa.roles) order by p.alias)
|
|
110
|
-
from meta.app_access aa join meta.app p on p.id = aa.app_id where aa.account_id = a.id), '[]') as apps
|
|
113
|
+
from meta.app_access aa join meta.app p on p.id = aa.app_id where aa.account_id = a.id), '[]') as apps,
|
|
114
|
+
exists (select 1 from meta.account_factor f where f.account_id = a.id) as mfa
|
|
111
115
|
from meta.account a
|
|
112
116
|
where $1 = '' or a.username ilike '%' || $1 || '%' or a.display_name ilike '%' || $1 || '%' or a.email ilike '%' || $1 || '%'
|
|
113
117
|
order by lower(a.username)
|
|
@@ -125,16 +129,17 @@ export async function usersRoutes(app: FastifyInstance) {
|
|
|
125
129
|
<input type="search" name="q" value="${q}" placeholder="${tx('us.search_ph')}" aria-label="${tx('us.search_label')}"><button class="btn">${tx('us.search')}</button>
|
|
126
130
|
</form>
|
|
127
131
|
<div class="table-wrap"><table class="report report-reflow">
|
|
128
|
-
<thead><tr><th>${tx('us.username')}</th><th>${tx('us.name')}</th><th>${tx('us.apps_roles')}</th><th>${tx('us.signin')}</th><th>${tx('us.status')}</th></tr></thead>
|
|
132
|
+
<thead><tr><th>${tx('us.username')}</th><th>${tx('us.name')}</th><th>${tx('us.apps_roles')}</th><th>${tx('us.signin')}</th><th>${tx('mfa.column')}</th><th>${tx('us.status')}</th></tr></thead>
|
|
129
133
|
<tbody>${users.length
|
|
130
134
|
? users.map((u) => html`<tr>
|
|
131
135
|
<td data-label="${tx('us.username')}"><a href="${BASE}/users/${u.id}">${u.username}</a></td>
|
|
132
136
|
<td data-label="${tx('us.name')}">${u.display_name ?? ''}${u.email ? html`<div class="muted">${u.email}</div>` : ''}</td>
|
|
133
137
|
<td data-label="${tx('us.applications')}">${u.apps.length ? u.apps.map((x: any) => html`<span class="chip">${x.alias}${x.roles.length ? `: ${x.roles.join(', ')}` : ''}</span> `) : html`<span class="muted">${tx('us.none')}</span>`}</td>
|
|
134
138
|
<td data-label="${tx('us.signin')}">${u.password_hash ? tx('us.password') : html`<span class="muted">${tx('us.no_password')}</span>`}</td>
|
|
139
|
+
<td data-label="${tx('mfa.column')}">${u.mfa ? html`${icon('lock')} ${tx('mfa.on')}` : html`<span class="muted">${tx('mfa.off')}</span>`}</td>
|
|
135
140
|
<td data-label="${tx('us.status')}">${u.active ? tx('us.active') : html`<b>${tx('us.inactive')}</b>`}${u.last_login_at ? html`<div class="muted">${tx('us.last', { at: String(u.last_login_at).slice(0, 16) })}</div>` : ''}</td>
|
|
136
141
|
</tr>`)
|
|
137
|
-
: html`<tr><td colspan="
|
|
142
|
+
: html`<tr><td colspan="6" class="empty">${tx('us.no_accounts')}</td></tr>`}</tbody>
|
|
138
143
|
</table></div>`)}
|
|
139
144
|
${region(tx('us.create'), html`
|
|
140
145
|
<form method="post" action="${BASE}/users">${csrf(s)}
|
|
@@ -215,6 +220,7 @@ export async function usersRoutes(app: FastifyInstance) {
|
|
|
215
220
|
owner.query(`select id, name, alias from meta.app where id not in (select app_id from meta.app_access where account_id = $1) order by name`, [u.id]),
|
|
216
221
|
]);
|
|
217
222
|
const hints = await roleHints([...access.rows.map((a) => a.app_id), ...apps.rows.map((a) => a.id)]);
|
|
223
|
+
const [factors, codes] = await Promise.all([accountFactors(u.id), accountCodesLeft(u.id)]);
|
|
218
224
|
const main = html`
|
|
219
225
|
<div class="title-row"><h1>${u.username}</h1></div>
|
|
220
226
|
<div class="columns">
|
|
@@ -244,6 +250,13 @@ export async function usersRoutes(app: FastifyInstance) {
|
|
|
244
250
|
<div class="buttons"><button class="btn">${tx('us.set_password')}</button>
|
|
245
251
|
${u.password_hash ? html`<button class="btn" name="remove" value="1" data-confirm="${tx('us.remove_confirm')}">${tx('us.remove_password')}</button>` : ''}</div>
|
|
246
252
|
</form>
|
|
253
|
+
<h3 id="two-factor">${tx('us.mfa_title')}</h3>
|
|
254
|
+
<p>${factors.length ? tx('us.mfa_status', { n: factors.length, codes }) : tx('us.mfa_none')}</p>
|
|
255
|
+
${factors.length
|
|
256
|
+
? html`<form method="post" action="${BASE}/users/${u.id}/reset-2fa" class="danger-zone">${csrf(s)}
|
|
257
|
+
<div class="form-grid">${input('reason', tx('mfa.reason'), '', { required: true, help: tx('us.mfa_reset_help', { user: u.username }) })}</div>
|
|
258
|
+
<div class="buttons"><button class="btn btn-danger">${tx('mfa.reset_btn')}</button></div></form>`
|
|
259
|
+
: ''}
|
|
247
260
|
<form method="post" action="${BASE}/users/${u.id}/delete" class="danger-zone">${csrf(s)}
|
|
248
261
|
<button class="btn btn-danger" data-confirm="${tx('us.delete_confirm', { user: u.username })}">${tx('us.delete')}</button>
|
|
249
262
|
</form>`)}
|
|
@@ -326,6 +339,24 @@ export async function usersRoutes(app: FastifyInstance) {
|
|
|
326
339
|
return back(reply, s, `${BASE}/users/${req.params.id}`);
|
|
327
340
|
});
|
|
328
341
|
|
|
342
|
+
// (sprint 130, SEC-3) remove an account's authenticator apps and recovery codes (a lost phone), with a reason
|
|
343
|
+
app.post(`${BASE}/users/:id(^\\d+$)/reset-2fa`, async (req: Req, reply) => {
|
|
344
|
+
const s = await developer(req, reply);
|
|
345
|
+
if (!s) return;
|
|
346
|
+
const tx = tr(s);
|
|
347
|
+
const reason = String(req.body?.reason ?? '').trim().slice(0, 200);
|
|
348
|
+
const acc = await owner.one<{ id: number; username: string }>('select id, username from meta.account where id = $1', [req.params.id]);
|
|
349
|
+
if (!acc) return reply.code(404).send('Not found');
|
|
350
|
+
if (!reason) {
|
|
351
|
+
flash(s, tx('us.mfa_reason_needed'), 'error');
|
|
352
|
+
return back(reply, s, `${BASE}/users/${acc.id}#two-factor`);
|
|
353
|
+
}
|
|
354
|
+
await resetAccountFactors(acc.id);
|
|
355
|
+
await logActivity({ username: acc.username, event: '2fa_reset', ip: clientIp(req), detail: `by ${s.username}: ${reason}` });
|
|
356
|
+
flash(s, tx('us.mfa_reset_done', { user: acc.username }));
|
|
357
|
+
return back(reply, s, `${BASE}/users/${acc.id}`);
|
|
358
|
+
});
|
|
359
|
+
|
|
329
360
|
app.post(`${BASE}/users/:id(^\\d+$)/delete`, async (req: Req, reply) => {
|
|
330
361
|
const s = await developer(req, reply);
|
|
331
362
|
if (!s) return;
|