Path: redb-identity/demos/demo_admin_mfa_email.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_admin_mfa_email.ps1 ---- # Admin-side e-mail MFA enrollment through the management API (/api/v1/identity/mfa/email). # # Setup sends the one-time code to the NEW address (through the SMTP channel of context.json, caught by GreenMail) # and answers with mfa_state and setup_token; confirm takes the code with both. # # Probes: # 1. Admin DCR (cc + identity:users:write identity:mfa:read identity:mfa:write) # 2. client_credentials token # 3. seed a user # 4. POST /mfa/email/setup -> masked_email, mfa_state, setup_token; the code is e-mailed # 5. read the code from GreenMail # 6. POST /mfa/email/confirm (wrong code) -> 400 invalid_code # 7. POST /mfa/email/confirm -> confirmed, 10 recovery codes # 8. GET /mfa/status/{id} -> enabled, methods contains email # 9. DELETE /mfa/email/{id} -> disabled # 10. cleanup: delete user # # Requires the GreenMail container (SMTP 3025 / REST 8080), as demo_password_reset does. # # Usage: pwsh -File demo_admin_mfa_email.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $GM = "http://127.0.0.1:8080" # GreenMail REST API $SCOPES = "identity:users:write identity:mfa:read identity:mfa:write" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function Wait-Email { param([string]$Email, [int]$TimeoutMs = 8000) $deadline = [DateTimeOffset]::UtcNow.AddMilliseconds($TimeoutMs) while ([DateTimeOffset]::UtcNow -lt $deadline) { try { $msgs = Invoke-RestMethod -Method Get "$GM/api/user/$Email/messages/INBOX" -ErrorAction Stop if ($msgs -and $msgs.Count -ge 1) { return $msgs[0] } } catch { # 404 until the user is auto-created by GreenMail on first mail, retry. } Start-Sleep -Milliseconds 300 } return $null } function Decode-QuotedPrintable { param([string]$s) if ([string]::IsNullOrEmpty($s)) { return $s } $s = $s -replace "=\r\n", "" -replace "=\n", "" return [regex]::Replace($s, "=([0-9A-Fa-f]{2})", { param($m) [char][Convert]::ToInt32($m.Groups[1].Value, 16) }) } $total = [System.Diagnostics.Stopwatch]::StartNew() $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "admin-mfa-email"; grant_types = @("client_credentials"); scope = $SCOPES } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = $SCOPES } } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } $user = "mfamail_" + [Guid]::NewGuid().ToString("N").Substring(0,8) $address = "$user-mfa@example.com" $UserId = Measure-Step "3. seed user" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = "AdminMfaPass1234!"; displayName = $user } | ConvertTo-Json) if (-not $r.success -or -not $r.userId) { throw "register failed: $($r | ConvertTo-Json)" } return [long]$r.userId } $setup = Measure-Step "4. POST /mfa/email/setup" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/email/setup" -Headers $ADMIN ` -Body (@{ userId = $UserId; username = $user; destination = $address } | ConvertTo-Json) if (-not $r.mfa_state -or -not $r.setup_token -or -not $r.masked_email) { throw "setup answer lacks mfa_state, setup_token or masked_email: $($r | ConvertTo-Json)" } Write-Host " ok: code sent to $($r.masked_email), mfa_state and setup token issued" -ForegroundColor Green return $r } $code = Measure-Step "5. read the code from GreenMail" { $msg = Wait-Email -Email $address if ($null -eq $msg) { throw "no e-mail for $address in GreenMail" } $body = Decode-QuotedPrintable $msg.mimeMessage $m = [regex]::Match($body, 'verification code is:\s*(\d{6})') if (-not $m.Success) { throw "no 6-digit code in the e-mail" } Write-Host " ok: code read from the e-mail" -ForegroundColor Green return $m.Groups[1].Value } Measure-Step "6. POST /mfa/email/confirm (wrong code) - 400 invalid_code" { $wrong = if ($code -eq "000000") { "111111" } else { "000000" } $resp = Invoke-WebRequest -Method Post "$BASE/api/v1/identity/mfa/email/confirm" -Headers $ADMIN -SkipHttpErrorCheck ` -Body (@{ userId = $UserId; code = $wrong; mfaState = $setup.mfa_state; setupToken = $setup.setup_token } | ConvertTo-Json) $err = ($resp.Content | ConvertFrom-Json).error if ($resp.StatusCode -ne 400 -or $err -ne "invalid_code") { throw "expected 400 invalid_code, got $($resp.StatusCode) $($resp.Content)" } Write-Host " ok: wrong code refused" -ForegroundColor Green } | Out-Null Measure-Step "7. POST /mfa/email/confirm (code + mfa_state + setup token)" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/email/confirm" -Headers $ADMIN ` -Body (@{ userId = $UserId; code = $code; mfaState = $setup.mfa_state; setupToken = $setup.setup_token } | ConvertTo-Json) if (-not $r.confirmed -or $r.recovery_codes.Count -ne 10) { throw "confirm failed: $($r | ConvertTo-Json)" } Write-Host " ok: confirmed, 10 recovery codes" -ForegroundColor Green } | Out-Null Measure-Step "8. GET /mfa/status - email enabled" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/mfa/status/$UserId" -Headers $ADMIN if (-not $r.enabled -or $r.methods -notcontains "email") { throw "status: $($r | ConvertTo-Json)" } Write-Host " ok: enabled, email" -ForegroundColor Green } | Out-Null Measure-Step "9. DELETE /mfa/email - disable" { $r = Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/mfa/email/$UserId" -Headers $ADMIN if (-not $r.disabled) { throw "disable: $($r | ConvertTo-Json)" } Write-Host " ok: disabled" -ForegroundColor Green } | Out-Null Measure-Step "10. cleanup: delete user" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN | Out-Null } catch { Write-Host " (cleanup) user delete returned: $($_.Exception.Message)" -ForegroundColor DarkGray } } | Out-Null $total.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Magenta