feat: add native totp two-factor authentication for password login (#12620)

* feat: add native totp two-factor authentication for password login

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep login field spacing when the code field shows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep two-factor across a user overwrite and key the prompt to the submitted email

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: snapshot totp in the overwrite delete and audit wrong two-factor codes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: move two-factor to ee, add recovery codes, encrypt secrets, db-backed limit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: refuse a two-factor reset for an account without one

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: serialize two-factor races with key rotation and ce enrollment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: argon2 recovery codes, otpauth link, totp field name, settings styling

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: serialize totp setup with admins key rotation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: two-factor setup wizard that asks for the password

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: ask for the two-factor code on its own login screen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: say two-factor is on with the recovery codes, red turn-off confirm

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: update ee-repo-ref to 5456ade3c09011206acc20ab026dda49f15f9517

This commit updates the EE repository reference after PR #1005 was merged in windmill-ee-private.

Previous ee-repo-ref: 84c64720d625ed5a41b6ff0851f9d9b568b31c0b

New ee-repo-ref: 5456ade3c09011206acc20ab026dda49f15f9517

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
hugocasa
2026-11-27 15:25:14 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot] Ruben Fiszel
parent 55aec82102
commit f52c117e76
39 changed files with 1252 additions and 139 deletions
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_recovery_codes = $2 WHERE email = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"TextArray"
]
},
"nullable": []
},
"hash": "05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a"
}
@@ -0,0 +1,47 @@
{
"db_name": "PostgreSQL",
"query": "SELECT totp_secret, totp_pending_secret, totp_last_step, totp_recovery_codes,\n (totp_failed_attempts >= $2 AND totp_failed_since > now() - interval '1 minute')\n AS \"locked!\"\n FROM password WHERE email = $1 FOR UPDATE",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "totp_secret",
"type_info": "Text"
},
{
"ordinal": 1,
"name": "totp_pending_secret",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "totp_last_step",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "totp_recovery_codes",
"type_info": "TextArray"
},
{
"ordinal": 4,
"name": "locked!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text",
"Int4"
]
},
"nullable": [
true,
true,
true,
true,
null
]
},
"hash": "08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_secret = totp_pending_secret, totp_pending_secret = NULL,\n totp_recovery_codes = $2\n WHERE email = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"TextArray"
]
},
"nullable": []
},
"hash": "0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_pending_secret = $2\n WHERE email = $1 AND login_type = 'password' AND totp_secret IS NULL",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": []
},
"hash": "134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268"
}
@@ -0,0 +1,20 @@
{
"db_name": "PostgreSQL",
"query": "SELECT 1 AS \"one!\" FROM workspace_key\n WHERE workspace_id = 'admins' AND kind = 'cloud' FOR UPDATE",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "one!",
"type_info": "Int4"
}
],
"parameters": {
"Left": []
},
"nullable": [
null
]
},
"hash": "4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86"
}
@@ -0,0 +1,38 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM password RETURNING email, totp_secret, totp_last_step, totp_recovery_codes",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "email",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "totp_secret",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "totp_last_step",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "totp_recovery_codes",
"type_info": "TextArray"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
true,
true
]
},
"hash": "4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de"
}
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT password_hash FROM password WHERE email = $1 AND login_type = 'password'",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "password_hash",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
true
]
},
"hash": "4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET\n totp_failed_attempts = CASE WHEN totp_failed_since > now() - interval '1 minute'\n THEN totp_failed_attempts + 1 ELSE 1 END,\n totp_failed_since = CASE WHEN totp_failed_since > now() - interval '1 minute'\n THEN totp_failed_since ELSE now() END\n WHERE email = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f"
}
@@ -0,0 +1,32 @@
{
"db_name": "PostgreSQL",
"query": "SELECT email, totp_secret, totp_pending_secret FROM password\n WHERE totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL FOR UPDATE",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "email",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "totp_secret",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "totp_pending_secret",
"type_info": "Text"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
true
]
},
"hash": "536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_secret = NULL, totp_pending_secret = NULL, totp_last_step = NULL,\n totp_recovery_codes = NULL, totp_failed_attempts = 0, totp_failed_since = NULL\n WHERE email = $1 AND (totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_failed_attempts = 0, totp_failed_since = NULL WHERE email = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032"
}
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT totp_secret IS NOT NULL AS \"enrolled!\" FROM password\n WHERE email = $1 AND login_type = 'password'",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "enrolled!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
null
]
},
"hash": "8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce"
}
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT key FROM workspace_key WHERE workspace_id = $1 AND kind = 'cloud' FOR SHARE",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "key",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false
]
},
"hash": "8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036"
}
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT EXISTS(SELECT 1 FROM password WHERE totp_secret IS NOT NULL AND email <> $1)\n AS \"exists!\"",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "exists!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
null
]
},
"hash": "be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_recovery_codes = array_remove(totp_recovery_codes, $2)\n WHERE email = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": []
},
"hash": "c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f"
}
@@ -0,0 +1,17 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_secret = $2, totp_last_step = $3, totp_recovery_codes = $4\n WHERE email = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text",
"Int8",
"TextArray"
]
},
"nullable": []
},
"hash": "d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d"
}
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT totp_secret IS NOT NULL AS \"enabled!\" FROM password WHERE email = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "enabled!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
null
]
},
"hash": "eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_last_step = $2 WHERE email = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Int8"
]
},
"nullable": []
},
"hash": "ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59"
}
@@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE password SET totp_secret = $2, totp_pending_secret = $3 WHERE email = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text",
"Text"
]
},
"nullable": []
},
"hash": "fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a"
}
+4
View File
@@ -16368,12 +16368,16 @@ version = "1.886.0"
dependencies = [
"argon2",
"axum",
"base32",
"chrono",
"hmac 0.12.1",
"http 1.5.0",
"hyper 1.13.0",
"lazy_static",
"rand 0.9.5",
"serde",
"serde_json",
"sha1",
"sqlx",
"time",
"tokio",
+1 -1
View File
@@ -1 +1 @@
c05fadda9d6bd772e56cec00d5b9c721afab4aed
5456ade3c09011206acc20ab026dda49f15f9517
@@ -0,0 +1,7 @@
ALTER TABLE password
DROP COLUMN IF EXISTS totp_secret,
DROP COLUMN IF EXISTS totp_pending_secret,
DROP COLUMN IF EXISTS totp_last_step,
DROP COLUMN IF EXISTS totp_recovery_codes,
DROP COLUMN IF EXISTS totp_failed_attempts,
DROP COLUMN IF EXISTS totp_failed_since;
@@ -0,0 +1,7 @@
ALTER TABLE password
ADD COLUMN IF NOT EXISTS totp_secret TEXT,
ADD COLUMN IF NOT EXISTS totp_pending_secret TEXT,
ADD COLUMN IF NOT EXISTS totp_last_step BIGINT,
ADD COLUMN IF NOT EXISTS totp_recovery_codes TEXT[],
ADD COLUMN IF NOT EXISTS totp_failed_attempts INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS totp_failed_since TIMESTAMPTZ;
+4
View File
@@ -24,6 +24,10 @@ windmill-audit.workspace = true
windmill-git-sync.workspace = true
argon2.workspace = true
base32.workspace = true
hmac.workspace = true
rand.workspace = true
sha1.workspace = true
axum.workspace = true
chrono.workspace = true
http.workspace = true
+4
View File
@@ -1,3 +1,7 @@
pub mod totp;
#[cfg(feature = "private")]
pub mod totp_ee;
mod totp_oss;
pub mod users;
#[cfg(feature = "private")]
pub mod users_ee;
+9
View File
@@ -0,0 +1,9 @@
//! Native TOTP second factor for password logins. The implementation is in `totp_ee`.
#[cfg(feature = "private")]
pub use crate::totp_ee::{check_login_code, service};
#[cfg(not(feature = "private"))]
pub use crate::totp_oss::{check_login_code, service};
pub const TOTP_REQUIRED: &str = "Two-factor code required";
pub const TOTP_INVALID: &str = "Invalid two-factor code";
@@ -0,0 +1,16 @@
#[cfg(not(feature = "private"))]
pub fn service() -> axum::Router {
axum::Router::new()
}
#[cfg(not(feature = "private"))]
pub async fn check_login_code(
_tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
_db: &windmill_common::DB,
_email: &str,
_code: &str,
) -> windmill_common::error::Result<bool> {
Err(windmill_common::error::Error::BadRequest(
"Two-factor authentication requires a build with the private feature".to_string(),
))
}
+60 -8
View File
@@ -125,6 +125,7 @@ pub fn global_service() -> Router {
.route("/exists/{email}", get(exists_email))
.route("/email", get(get_email))
.route("/whoami", get(global_whoami))
.nest("/totp", crate::totp::service())
.route("/list_invites", get(list_invites))
.route("/decline_invite", post(decline_invite))
.route("/accept_invite", post(accept_invite))
@@ -345,6 +346,8 @@ pub struct TruncatedToken {
pub struct Login {
pub email: String,
pub password: String,
#[serde(default)]
pub totp_code: Option<String>,
}
lazy_static::lazy_static! {
@@ -2905,7 +2908,7 @@ async fn login(
cookies: Cookies,
Extension(db): Extension<DB>,
Extension(argon2): Extension<Arc<Argon2<'_>>>,
Json(Login { email, password }): Json<Login>,
Json(Login { email, password, totp_code }): Json<Login>,
) -> Result<String> {
// In `--no-auth` mode there is no real login; the frontend never needs a
// session cookie because every request already resolves as the admin
@@ -2933,15 +2936,15 @@ async fn login(
username_override: None,
token_prefix: None,
};
let email_w_h: Option<(String, String, bool)> = sqlx::query_as(
"SELECT email, password_hash, super_admin FROM password WHERE email = $1 AND login_type = \
'password' AND disabled = false",
let email_w_h: Option<(String, String, bool, Option<String>)> = sqlx::query_as(
"SELECT email, password_hash, super_admin, totp_secret FROM password WHERE email = $1 \
AND login_type = 'password' AND disabled = false",
)
.bind(&email)
.fetch_optional(&mut *tx)
.await?;
if let Some((email, hash, super_admin)) = email_w_h {
if let Some((email, hash, super_admin, totp_secret)) = email_w_h {
if argon2
.verify_password(password.as_bytes(), hash.as_str())
.is_err()
@@ -2959,6 +2962,30 @@ async fn login(
windmill_common::login_rate_limit::record_login_failure(&email);
Err(Error::BadRequest("Invalid login".to_string()))
} else {
// Asked only once the password matched, so whether an account has a second
// factor is not disclosed to someone who does not know its password.
if totp_secret.is_some() {
let Some(code) = totp_code.filter(|c| !c.trim().is_empty()) else {
return Err(Error::BadRequest(crate::totp::TOTP_REQUIRED.to_string()));
};
if !crate::totp::check_login_code(&mut tx, &db, &email, &code).await? {
// Committed, unlike a wrong password: it holds the wrong-code count, and a
// guessed code must leave a trace.
audit_log(
&mut *tx,
&audit_author,
"users.login_failure",
ActionKind::Create,
"global",
None,
Some([("reason", "invalid_totp_code")].into()),
)
.await?;
tx.commit().await?;
windmill_common::login_rate_limit::record_login_failure(&email);
return Err(Error::BadRequest(crate::totp::TOTP_INVALID.to_string()));
}
}
let token =
create_session_token(&email, super_admin, None, false, &mut tx, cookies).await?;
@@ -4711,9 +4738,22 @@ async fn overwrite_global_users(
// Replaces the account table, so — unlike the paths that remove one account — it deliberately
// does not call `delete_drafts_of_email`: the addresses are about to be reinstated, and
// dropping every draft on the instance to restore accounts would be pure collateral.
sqlx::query!("DELETE FROM password")
.execute(&mut *tx)
.await?;
// The export leaves TOTP secrets out, since its files end up in git. A second factor is
// kept for every account the overwrite reinstates, rather than silently switched off.
// Read by the DELETE itself: a separate snapshot would miss an enrollment committing
// between the two and then delete it. The secrets are under the `admins` key: its row lock
// keeps a rotation from re-encrypting while the restored rows are not visible to it.
sqlx::query!(
"SELECT 1 AS \"one!\" FROM workspace_key
WHERE workspace_id = 'admins' AND kind = 'cloud' FOR UPDATE"
)
.fetch_optional(&mut *tx)
.await?;
let totp = sqlx::query!(
"DELETE FROM password RETURNING email, totp_secret, totp_last_step, totp_recovery_codes"
)
.fetch_all(&mut *tx)
.await?;
for user in users {
sqlx::query!(
"INSERT INTO password(email, password_hash, login_type, super_admin, verified, name, company, first_time_user, username)
@@ -4731,6 +4771,18 @@ async fn overwrite_global_users(
.execute(&mut *tx)
.await?;
}
for t in totp.into_iter().filter(|t| t.totp_secret.is_some()) {
sqlx::query!(
"UPDATE password SET totp_secret = $2, totp_last_step = $3, totp_recovery_codes = $4
WHERE email = $1",
t.email,
t.totp_secret,
t.totp_last_step,
t.totp_recovery_codes.as_deref()
)
.execute(&mut *tx)
.await?;
}
audit_log(
&mut *tx,
&authed,
@@ -6908,6 +6908,9 @@ async fn set_encryption_key(
&new_encryption_key,
)
.await?;
if w_id == "admins" {
reencrypt_totp_secrets(&mut tx, &previous_encryption_key, &new_encryption_key).await?;
}
tx.commit().await?;
@@ -6946,6 +6949,45 @@ async fn set_encryption_key(
return Ok(());
}
/// Two-factor secrets of password logins are kept under the `admins` workspace key. Never
/// synced, so they move to the new key even when the caller skips re-encryption: one left under
/// the old key would lock its user out.
async fn reencrypt_totp_secrets(
conn: &mut sqlx::PgConnection,
old: &windmill_common::variables::WorkspaceCrypt,
new: &windmill_common::variables::WorkspaceCrypt,
) -> Result<()> {
let rows = sqlx::query!(
"SELECT email, totp_secret, totp_pending_secret FROM password
WHERE totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL FOR UPDATE"
)
.fetch_all(&mut *conn)
.await?;
// Left as is when it does not decrypt: dropping it would switch the second factor off.
let reencrypt = |email: &str, value: Option<String>| {
value.map(|v| match decrypt(old, v.clone()) {
Ok(plain) => encrypt(new, &plain),
Err(e) => {
tracing::warn!("the two-factor secret of {email} does not decrypt under the current key, leaving it as is: {e}");
v
}
})
};
for row in rows {
let secret = reencrypt(&row.email, row.totp_secret);
let pending = reencrypt(&row.email, row.totp_pending_secret);
sqlx::query!(
"UPDATE password SET totp_secret = $2, totp_pending_secret = $3 WHERE email = $1",
row.email,
secret,
pending
)
.execute(&mut *conn)
.await?;
}
Ok(())
}
/// Move the git-sync secrets the server keeps under the workspace key (stored
/// repository tokens, webhook secrets) to the new key. They are never synced, so
/// unlike variables they are still under the old key when the caller skips
+170
View File
@@ -694,6 +694,170 @@ paths:
schema:
type: string
/users/totp:
get:
summary: get whether two-factor authentication is enabled for the current user
operationId: getTotpStatus
tags:
- user
responses:
"200":
description: two-factor status
content:
application/json:
schema:
type: object
properties:
enabled:
type: boolean
required:
- enabled
/users/totp/setup:
post:
summary: start two-factor setup by generating a new authenticator secret
operationId: setupTotp
tags:
- user
requestBody:
description: the account's current password
required: true
content:
application/json:
schema:
type: object
properties:
password:
type: string
required:
- password
responses:
"200":
description: the secret to register in an authenticator app
content:
application/json:
schema:
type: object
properties:
secret:
type: string
otpauth_url:
type: string
required:
- secret
- otpauth_url
/users/totp/enable:
post:
summary: enable two-factor authentication with a code from the secret generated by setup
operationId: enableTotp
tags:
- user
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
code:
type: string
required:
- code
responses:
"200":
description: two-factor authentication enabled, with its recovery codes
content:
application/json:
schema:
type: object
properties:
recovery_codes:
type: array
description: single-use codes accepted in place of an authenticator code, shown only once
items:
type: string
required:
- recovery_codes
/users/totp/recovery_codes:
post:
summary: replace the recovery codes, with a current code or a recovery code
operationId: regenerateTotpRecoveryCodes
tags:
- user
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
code:
type: string
required:
- code
responses:
"200":
description: the new recovery codes
content:
application/json:
schema:
type: object
properties:
recovery_codes:
type: array
description: single-use codes accepted in place of an authenticator code, shown only once
items:
type: string
required:
- recovery_codes
/users/totp/disable:
post:
summary: disable two-factor authentication with a current code or a recovery code
operationId: disableTotp
tags:
- user
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
code:
type: string
required:
- code
responses:
"200":
description: two-factor authentication disabled
content:
text/plain:
schema:
type: string
/users/totp/reset/{user}:
post:
summary: remove the two-factor authentication of a user (require super admin)
operationId: resetTotpOfUser
tags:
- user
parameters:
- name: user
in: path
required: true
schema:
type: string
responses:
"200":
description: two-factor authentication removed
content:
text/plain:
schema:
type: string
/users/set_password_of/{user}:
post:
summary: set password for a specific user (require super admin)
@@ -33922,6 +34086,12 @@ components:
type: string
password:
type: string
totp_code:
type: string
description: >
Current code of the account's authenticator app, or one of its recovery codes. Required once the account has
two-factor authentication enabled; the login answers "Two-factor code required"
when it is missing and the password is correct.
required:
- email
- password
+18
View File
@@ -25,6 +25,24 @@ Symbols, not line numbers, are cited: they drift less.
access-token row, then its grant, the order the trigger also follows. A new path that writes a
user's tokens and may revoke must lock that row first too. `leave_workspace` deletes no tokens
and revokes nothing; `leave_instance` deletes every token of the account, as `delete_user` does.
- **Two-factor (TOTP) guards `POST /auth/login` only** (`windmill-api-users/src/totp_ee.rs`,
with a stub in `totp_oss.rs`; a build without `enterprise` allows it for one user). The
password is checked first, so "Two-factor code required" tells only someone who knows the
password that a code is needed. Every other way into a session skips it on purpose: OAuth and
SAML (the provider owns the second factor), login links (minted by a superadmin, who can reset
the second factor anyway, and never for a superadmin or devops account), and `GET /users/refresh_token` (a session already exists).
Authenticator codes are single-use (`totp_last_step`), and so are the ten recovery codes, stored
as salted argon2 hashes (a code carries about 52 bits, too few for a plain digest) and are
accepted wherever a code is. Wrong codes are capped per account at 5 a minute on the
`password` row, so the cap holds across servers; the caller commits the count even when it
refuses the code. Without that cap, a known password leaves a 6-digit code as the only barrier.
Enrolling (`setup`) asks for the password again, so a stolen session cannot add its own
authenticator and lock the owner out of password login. A superadmin removes a lost second
factor with `POST /users/totp/reset/{user}`. The secret is
encrypted under the `admins` workspace key, and rotating that key re-encrypts it
(`set_encryption_key`); a secret left under an old key locks its user out. The global user
export leaves it out, as its files end up in git: an overwrite keeps the second factor of every
account it reinstates, and a push to another instance arrives without one.
- **Sessions** are `token` rows with `label='session'` plus the HttpOnly `token` cookie, minted only
by `create_session_token` (`windmill-api-users/src/users.rs`). `GET /api/users/refresh_token`
mints one for any non-job token but returns plain text, no redirect.
+7
View File
@@ -96,6 +96,7 @@
"tailwind-merge": "^1.13.2",
"unified": "^11.0.5",
"unist-util-visit": "^5.0.0",
"uqr": "^0.1.3",
"vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0",
"vscode-languageclient": "~9.0.1",
"vscode-uri": "~3.1.0",
@@ -13446,6 +13447,12 @@
"browserslist": ">= 4.21.0"
}
},
"node_modules/uqr": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz",
"integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==",
"license": "MIT"
},
"node_modules/uri-js": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
+1
View File
@@ -161,6 +161,7 @@
"tailwind-merge": "^1.13.2",
"unified": "^11.0.5",
"unist-util-visit": "^5.0.0",
"uqr": "^0.1.3",
"vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0",
"vscode-languageclient": "~9.0.1",
"vscode-uri": "~3.1.0",
@@ -44,6 +44,10 @@
sendUserToast(`Password updated for ${email}`)
}
async function resetTotp() {
sendUserToast(await UserService.resetTotpOfUser({ user: email }))
}
async function saveLoginType() {
await UserService.setLoginTypeForUser({ user: email, requestBody: { login_type } })
sendUserToast(`Login type updated for ${email}`)
@@ -173,6 +177,22 @@
Update login type
</Button>
</label>
<div class="block text-primary">
<div class="pb-1 text-xs font-semibold text-emphasis">Two-factor authentication</div>
<div class="text-2xs text-secondary mb-1">
Removes the user's authenticator, for when they lost access to it. They can set up a new
one from their user settings.
</div>
<Button
unifiedSize="md"
variant="default"
buttonType="button"
btnClasses="mt-2"
onclick={resetTotp}
>
Reset two-factor
</Button>
</div>
</div>
{/snippet}
</Popover>
+212 -125
View File
@@ -42,7 +42,12 @@
import { sameTopDomainOrigin } from '$lib/cookies'
import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect'
import InputError from './InputError.svelte'
import { loginErrorMessage } from '$lib/loginError'
import {
loginErrorDetail,
loginErrorMessage,
TOTP_INVALID_MESSAGE,
TOTP_REQUIRED
} from '$lib/loginError'
import { parseAccountSettingsHash } from './sidebar/settings'
import Badge from './common/badge/Badge.svelte'
import {
@@ -109,6 +114,7 @@
const emailId = `${uid}-email`
const passwordId = `${uid}-password`
const errorId = `${uid}-error`
const totpId = `${uid}-totp`
const emailErrorId = `${uid}-email-error`
const providers = [
@@ -183,6 +189,22 @@
let showPassword = $state(false)
let passwordField = $state<Password | undefined>(undefined)
// The account the server asked an authenticator code for. The code step replaces the form
// and resends the password kept here, so the server needs no half-logged-in state.
let totpFor = $state<string | undefined>(undefined)
let totpCode = $state('')
let totpField = $state<TextInput | undefined>(undefined)
let showTotp = $derived(totpFor !== undefined && totpFor === email)
async function leaveTotp() {
totpFor = undefined
totpCode = ''
formError = undefined
// The swapped-in markup would otherwise replay a shake left on from a failed attempt.
shake = false
await tick()
passwordField?.focus()
}
// Type argument rather than annotation: annotating narrows the declaration to the
// initializer's `undefined`, so a top-level read sees `never` instead of the array.
let logins = $state<OAuthLogin[] | undefined>(undefined)
@@ -200,7 +222,7 @@
let formError = $state<
| {
message: string
fields: 'both' | 'email' | 'password'
fields: 'both' | 'email' | 'password' | 'totp'
email: string | undefined
password: string | undefined
}
@@ -221,7 +243,7 @@
async function failLogin(
message: string,
fields: 'both' | 'email' | 'password' = 'both',
fields: 'both' | 'email' | 'password' | 'totp' = 'both',
// The pair the message is about. Defaults to what is in the fields right now, but a
// rejected request passes what it actually submitted: the user may have typed on since.
attempted: { email: string | undefined; password: string | undefined } = { email, password }
@@ -258,9 +280,15 @@
return
}
if (showTotp && !totpCode.trim()) {
failLogin('Enter the code from your authenticator app.', 'totp')
return
}
const requestBody = {
email,
password
password,
totp_code: showTotp ? totpCode : undefined
}
// Await the DOM update: the field must be back to type="password" before the
@@ -274,7 +302,17 @@
// previous account must not be served to this one.
noteSessionEmail(email)
} catch (err) {
failLogin(loginErrorMessage(err), 'both', requestBody)
if (loginErrorDetail(err) === TOTP_REQUIRED) {
formError = undefined
shake = false
totpFor = requestBody.email
totpCode = ''
await tick()
totpField?.focus()
return
}
const message = loginErrorMessage(err)
failLogin(message, message === TOTP_INVALID_MESSAGE ? 'totp' : 'both', requestBody)
return
}
@@ -760,130 +798,179 @@
<p class="text-sm text-center text-secondary py-4">Signing you in…</p>
{/if}
{#if !passwordFirst}
{@render providerButtons()}
{#if !autoRedirecting && !disablePasswordLogin && (saml || (logins && logins.length > 0))}
{@render orDivider()}
<!-- Only an entry point to the form below: once that is open the divider is what
separates the two ways in. -->
{#if !showPassword}
<div class="center-center">
<Button
unifiedSize="sm"
variant="subtle"
onClick={() => {
showPassword = true
}}
>
Log in without third-party
</Button>
</div>
{/if}
{/if}
{/if}
{#if !autoRedirecting && showPassword && !disablePasswordLogin}
<div>
{#if firstTime}
<p class="text-xs text-center w-full pb-4 text-secondary">
Welcome! Default credentials admin@windmill.dev / changeme have been prefilled.
{#if showTotp}
<div class="space-y-4">
<div class="space-y-1">
<h2 class="text-sm font-semibold text-emphasis">Two-factor authentication</h2>
<p class="text-xs text-secondary">
Enter the code from your authenticator app for {email}, or one of your recovery codes.
</p>
{/if}
<div class="space-y-4">
{#if cloudHosted}
<p class="text-xs text-secondary pb-6">
To get credentials without the OAuth providers above, send an email at
contact@windmill.dev
</p>
{/if}
<div bind:this={fieldsEl} class="space-y-2 {shake ? 'motion-safe:animate-shake' : ''}">
<div class="space-y-1">
<label for={emailId} class="block text-xs font-semibold text-emphasis"> Email </label>
<div>
<TextInput
size="md"
error={emailErrored}
bind:value={email}
inputProps={{
id: emailId,
type: 'email',
autocomplete: 'username',
'aria-invalid': emailErrored ? 'true' : undefined,
'aria-describedby':
errorField === 'email' ? emailErrorId : emailErrored ? errorId : undefined,
onkeydown: (e) => {
// Only move on once the field holds something: while the browser's
// credential dropdown is open, Enter belongs to the dropdown
if (e.key === 'Enter' && !e.isComposing && !e.repeat && e.currentTarget.value) {
e.preventDefault()
passwordField?.focus()
}
}
}}
/>
</div>
<div id={emailErrorId} role="alert" class="min-h-5">
{#if errorField === 'email'}
<InputError error={credentialsError} />
{/if}
</div>
</div>
<div class="space-y-1">
<label for={passwordId} class="block text-xs font-semibold text-emphasis">
Password
</label>
<div>
<Password
bind:this={passwordField}
bind:password
id={passwordId}
placeholder=""
autocomplete="current-password"
allowMultiline={false}
error={passwordErrored}
describedBy={passwordErrored ? errorId : undefined}
onKeyDown={handleKeyDown}
/>
</div>
{@render errorMessage()}
</div>
</div>
<div>
<Button onClick={login} variant="accent" unifiedSize="lg" disabled={!email || !password}>
Log in
</Button>
{#if smtpConfigured}
<div class="text-center pt-2">
<a
href="/user/forgot-password"
class="text-2xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
>
Forgot password?
</a>
</div>
{/if}
</div>
<div bind:this={fieldsEl} class="space-y-1 {shake ? 'motion-safe:animate-shake' : ''}">
<label for={totpId} class="block text-xs font-semibold text-emphasis">
Authentication code
</label>
<TextInput
bind:this={totpField}
size="md"
bind:value={totpCode}
error={!!errorField}
inputProps={{
id: totpId,
name: 'totp',
'aria-invalid': errorField ? 'true' : undefined,
'aria-describedby': errorField ? errorId : undefined,
autocomplete: 'one-time-code',
onkeydown: handleKeyDown
}}
/>
{@render errorMessage()}
</div>
<div class="space-y-2">
<Button onClick={login} variant="accent" unifiedSize="lg" disabled={!totpCode.trim()}>
Verify
</Button>
<div class="center-center">
<Button unifiedSize="sm" variant="subtle" onClick={leaveTotp}>Back</Button>
</div>
</div>
{#if cloudHosted}
<p class="text-2xs text-secondary mt-10 text-center">
By logging in, you agree to our
<a href="https://windmill.dev/terms_of_service" target="_blank" rel="noreferrer">
Terms of service
</a>
and
<a href="https://windmill.dev/privacy_policy" target="_blank" rel="noreferrer">
Privacy policy
</a>
</p>
{/if}
</div>
{/if}
{:else}
{#if !passwordFirst}
{@render providerButtons()}
{#if !autoRedirecting && !disablePasswordLogin && (saml || (logins && logins.length > 0))}
{@render orDivider()}
<!-- Only an entry point to the form below: once that is open the divider is what
separates the two ways in. -->
{#if !showPassword}
<div class="center-center">
<Button
unifiedSize="sm"
variant="subtle"
onClick={() => {
showPassword = true
}}
>
Log in without third-party
</Button>
</div>
{/if}
{/if}
{/if}
{#if passwordFirst && (saml || (logins && logins.length > 0))}
{@render orDivider()}
{@render providerButtons()}
{#if !autoRedirecting && showPassword && !disablePasswordLogin}
<div>
{#if firstTime}
<p class="text-xs text-center w-full pb-4 text-secondary">
Welcome! Default credentials admin@windmill.dev / changeme have been prefilled.
</p>
{/if}
<div class="space-y-4">
{#if cloudHosted}
<p class="text-xs text-secondary pb-6">
To get credentials without the OAuth providers above, send an email at
contact@windmill.dev
</p>
{/if}
<div bind:this={fieldsEl} class="space-y-2 {shake ? 'motion-safe:animate-shake' : ''}">
<div class="space-y-1">
<label for={emailId} class="block text-xs font-semibold text-emphasis"> Email </label>
<div>
<TextInput
size="md"
error={emailErrored}
bind:value={email}
inputProps={{
id: emailId,
type: 'email',
autocomplete: 'username',
'aria-invalid': emailErrored ? 'true' : undefined,
'aria-describedby':
errorField === 'email' ? emailErrorId : emailErrored ? errorId : undefined,
onkeydown: (e) => {
// Only move on once the field holds something: while the browser's
// credential dropdown is open, Enter belongs to the dropdown
if (
e.key === 'Enter' &&
!e.isComposing &&
!e.repeat &&
e.currentTarget.value
) {
e.preventDefault()
passwordField?.focus()
}
}
}}
/>
</div>
<div id={emailErrorId} role="alert" class="min-h-5">
{#if errorField === 'email'}
<InputError error={credentialsError} />
{/if}
</div>
</div>
<div class="space-y-1">
<label for={passwordId} class="block text-xs font-semibold text-emphasis">
Password
</label>
<div>
<Password
bind:this={passwordField}
bind:password
id={passwordId}
placeholder=""
autocomplete="current-password"
allowMultiline={false}
error={passwordErrored}
describedBy={passwordErrored ? errorId : undefined}
onKeyDown={handleKeyDown}
/>
</div>
{@render errorMessage()}
</div>
</div>
<div>
<Button
onClick={login}
variant="accent"
unifiedSize="lg"
disabled={!email || !password}
>
Log in
</Button>
{#if smtpConfigured}
<div class="text-center pt-2">
<a
href="/user/forgot-password"
class="text-2xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
>
Forgot password?
</a>
</div>
{/if}
</div>
</div>
{#if cloudHosted}
<p class="text-2xs text-secondary mt-10 text-center">
By logging in, you agree to our
<a href="https://windmill.dev/terms_of_service" target="_blank" rel="noreferrer">
Terms of service
</a>
and
<a href="https://windmill.dev/privacy_policy" target="_blank" rel="noreferrer">
Privacy policy
</a>
</p>
{/if}
</div>
{/if}
{#if passwordFirst && (saml || (logins && logins.length > 0))}
{@render orDivider()}
{@render providerButtons()}
{/if}
{/if}
</div>
@@ -0,0 +1,202 @@
<script module lang="ts">
export type TotpAction = 'setup' | 'recovery_codes' | 'disable'
</script>
<script lang="ts">
import { UserService } from '$lib/gen'
import { Alert, Button, CopyButton } from '$lib/components/common'
import Modal from '../common/modal/Modal.svelte'
import Stepper from '../common/stepper/Stepper.svelte'
import Checkbox from '../common/checkbox/Checkbox.svelte'
import TextInput from '../text_input/TextInput.svelte'
import CopyableCodeBlock from '../details/CopyableCodeBlock.svelte'
import { plaintext } from 'svelte-highlight/languages'
import { sendUserToast } from '$lib/toast'
import { download } from '$lib/utils'
import { renderSVG } from 'uqr'
interface Props {
action: TotpAction | undefined
onClose: () => void
}
let { action = $bindable(), onClose }: Props = $props()
const SETUP_STEPS = ['Password', 'Authenticator', 'Recovery codes']
let step = $state(0)
let password = $state('')
let code = $state('')
let setup = $state<{ secret: string; otpauth_url: string } | undefined>(undefined)
let recoveryCodes = $state<string[] | undefined>(undefined)
let saved = $state(false)
let busy = $state(false)
const title = $derived(
action == 'setup'
? 'Set up two-factor authentication'
: action == 'recovery_codes'
? 'New recovery codes'
: 'Turn off two-factor authentication'
)
// Closing at any step drops the secret and the codes from the page.
function close() {
step = 0
password = ''
code = ''
setup = undefined
recoveryCodes = undefined
saved = false
action = undefined
onClose()
}
const canContinue = $derived(
recoveryCodes ? saved : action == 'setup' && step == 0 ? !!password : !!code
)
async function next() {
if (!canContinue || busy) return
busy = true
try {
if (recoveryCodes) {
close()
} else if (action == 'setup' && step == 0) {
setup = await UserService.setupTotp({ requestBody: { password } })
password = ''
step = 1
} else if (action == 'disable') {
sendUserToast(await UserService.disableTotp({ requestBody: { code } }))
close()
} else {
const requestBody = { code }
recoveryCodes = (
action == 'setup'
? await UserService.enableTotp({ requestBody })
: await UserService.regenerateTotpRecoveryCodes({ requestBody })
).recovery_codes
setup = undefined
code = ''
step = 2
}
} finally {
busy = false
}
}
const nextLabel = $derived(
recoveryCodes
? 'Done'
: action == 'setup'
? step == 0
? 'Continue'
: 'Turn on'
: action == 'disable'
? 'Turn off'
: 'Create new codes'
)
</script>
{#snippet primary()}
<Button
unifiedSize="sm"
variant="accent"
destructive={action == 'disable'}
disabled={!canContinue}
loading={busy}
onClick={next}
>
{nextLabel}
</Button>
{/snippet}
<Modal
{title}
bind:open={() => action != undefined, (v) => !v && action != undefined && close()}
on:confirmed={next}
kind={recoveryCodes ? 'X' : 'button'}
>
<div class="flex flex-col gap-4">
{#if action == 'setup'}
<Stepper tabs={SETUP_STEPS} selectedIndex={step} maxReachedIndex={step} small />
{/if}
{#if recoveryCodes}
{#if action == 'setup'}
<Alert type="success" title="Two-factor authentication is on" size="xs">
Logging in with your password now also asks for a code from your authenticator app.
</Alert>
{/if}
<div class="flex flex-col gap-1">
<span class="text-xs text-secondary font-normal">
Each code logs you in once if you lose your authenticator.
</span>
<CopyableCodeBlock code={recoveryCodes.join('\n')} language={plaintext} />
<div class="flex">
<Button
unifiedSize="sm"
variant="default"
onClick={() => download('windmill-recovery-codes.txt', recoveryCodes!.join('\n'))}
>
Download
</Button>
</div>
</div>
<Alert type="warning" title="Save these codes now" size="xs">
They are shown only once. Keep them somewhere other than this device.
</Alert>
<label class="flex flex-row gap-2 items-center text-xs text-primary font-normal">
<Checkbox checked={saved} onChange={() => (saved = !saved)} />
I saved my recovery codes
</label>
<div class="flex justify-end">
{@render primary()}
</div>
{:else if action == 'setup' && step == 0}
<label class="flex flex-col gap-1">
<span class="text-xs text-emphasis font-semibold">Password</span>
<span class="text-xs text-secondary font-normal">
Confirm it's you before adding an authenticator to this account.
</span>
<TextInput
inputProps={{ type: 'password', autocomplete: 'current-password' }}
bind:value={password}
/>
</label>
{:else}
{#if setup}
<div class="flex flex-col gap-1">
<span class="text-xs text-secondary font-normal">
Scan this QR code with an authenticator app, or open it on this device.
</span>
<a
href={setup.otpauth_url}
aria-label="Add to an authenticator app"
class="w-40 h-40 bg-white p-1 rounded-md"
>
{@html renderSVG(setup.otpauth_url)}
</a>
<div class="flex flex-row gap-1 items-center text-2xs text-secondary font-normal">
Or enter this key manually:
<span class="font-mono text-emphasis">{setup.secret}</span>
<CopyButton value={setup.secret} />
</div>
</div>
{/if}
<label class="flex flex-col gap-1">
<span class="text-xs text-emphasis font-semibold">Code</span>
<span class="text-xs text-secondary font-normal">
{setup
? 'The 6-digit code your authenticator app shows'
: 'A code from your authenticator app, or one of your recovery codes'}
</span>
<TextInput inputProps={{ autocomplete: 'one-time-code', name: 'totp' }} bind:value={code} />
</label>
{/if}
</div>
{#snippet actions()}
{@render primary()}
{/snippet}
</Modal>
@@ -5,6 +5,7 @@
import { Button } from '$lib/components/common'
import { sendUserToast } from '$lib/toast'
import TextInput from '../text_input/TextInput.svelte'
import TotpModal, { type TotpAction } from './TotpModal.svelte'
let newPassword = $state<string | undefined>(undefined)
let passwordError = $state<string | undefined>(undefined)
@@ -19,11 +20,20 @@
async function loadLoginType(): Promise<void> {
login_type = (await UserService.globalWhoami()).login_type
if (login_type == 'password') await loadTotp()
if (login_type == 'pending_oauth') {
passwordAllowed = !(await UserService.isPasswordLoginDisabled().catch(() => false))
}
}
let totpEnabled = $state<boolean | undefined>(undefined)
let totpAction = $state<TotpAction | undefined>(undefined)
async function loadTotp(): Promise<void> {
// Builds without two-factor support do not serve the route: the section stays hidden.
totpEnabled = (await UserService.getTotpStatus().catch(() => undefined))?.enabled
}
async function setPassword(): Promise<void> {
if (newPassword) {
await UserService.setPassword({
@@ -78,4 +88,34 @@
</span>
</div>
{/if}
{#if login_type == 'password' && totpEnabled != undefined}
<div class="flex flex-col gap-1 w-120">
<span class="text-xs text-emphasis font-semibold">Two-factor authentication</span>
<span class="text-xs text-secondary font-normal">
{totpEnabled
? 'On. Logging in with your password also asks for a code from your authenticator app.'
: 'Ask for a code from an authenticator app each time you log in with your password.'}
</span>
<div class="flex flex-row gap-1">
{#if totpEnabled}
<Button
unifiedSize="sm"
variant="default"
onClick={() => (totpAction = 'recovery_codes')}
>
New recovery codes
</Button>
<Button unifiedSize="sm" variant="default" onClick={() => (totpAction = 'disable')}>
Turn off
</Button>
{:else}
<Button unifiedSize="sm" variant="default" onClick={() => (totpAction = 'setup')}>
Set up two-factor authentication
</Button>
{/if}
</div>
</div>
{/if}
</form>
<TotpModal bind:action={totpAction} onClose={loadTotp} />
+15 -1
View File
@@ -1,5 +1,10 @@
import { describe, it, expect } from 'vitest'
import { loginErrorMessage } from './loginError'
import {
loginErrorDetail,
loginErrorMessage,
TOTP_INVALID_MESSAGE,
TOTP_REQUIRED
} from './loginError'
describe('loginErrorMessage', () => {
it('maps the backend rejection to one message for a wrong email and a wrong password', () => {
@@ -21,6 +26,15 @@ describe('loginErrorMessage', () => {
)
})
it('recognises the two-factor responses of the login endpoint', () => {
expect(loginErrorDetail({ status: 400, body: 'Bad request: Two-factor code required' })).toBe(
TOTP_REQUIRED
)
expect(loginErrorMessage({ status: 400, body: 'Bad request: Invalid two-factor code' })).toBe(
TOTP_INVALID_MESSAGE
)
})
it('never surfaces server text it does not recognise, to an unauthenticated visitor', () => {
const sqlError = {
status: 400,
+16 -4
View File
@@ -3,17 +3,29 @@
// error page — would otherwise be printed verbatim to an unauthenticated visitor.
const KNOWN_LOGIN_ERRORS = ['Password login is disabled on this instance']
/** The password matched and the account asks for its authenticator code: a prompt, not a failure. */
export const TOTP_REQUIRED = 'Two-factor code required'
export const TOTP_INVALID_MESSAGE = 'Invalid authentication code.'
const GENERIC_LOGIN_ERROR = 'Could not sign you in. Please try again.'
export function loginErrorMessage(err: any): string {
// The API returns errors as plain text, prefixed by their class (e.g. "Bad request: Invalid
// login"); ApiError.message is only the HTTP status text.
// The API returns errors as plain text, prefixed by their class (e.g. "Bad request: Invalid
// login"); ApiError.message is only the HTTP status text.
export function loginErrorDetail(err: any): string {
const raw = typeof err?.body === 'string' ? err.body : err?.body?.error?.message
const body = typeof raw === 'string' ? raw : ''
const detail = body.replace(/^(Bad request|Internal|Error): /, '').trim()
return body.replace(/^(Bad request|Internal|Error): /, '').trim()
}
export function loginErrorMessage(err: any): string {
const detail = loginErrorDetail(err)
if (detail === 'Invalid login') {
return 'Invalid email or password.'
}
if (detail === 'Invalid two-factor code') {
return TOTP_INVALID_MESSAGE
}
if (err?.status === 429) {
return 'Too many login attempts. Please try again later.'
}