Path: redb-identity/demos/demo_admin_mfa.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.ps1 ---- # Admin-side MFA enrollment through the management API (/api/v1/identity/mfa). # # An operator with identity:mfa:read identity:mfa:write enrolls a user in TOTP, reads the status, regenerates the # recovery codes and disables TOTP again. Confirm sends the first code together with the setup token of the setup # answer. # # Probes (all asserted): # 1. Admin DCR (cc + identity:users:write identity:mfa:read identity:mfa:write) # 2. Admin cc token # 3. Seed a user # 4. POST /mfa/totp/setup -> secret_base32, qr_uri, setup_token # 5. POST /mfa/totp/confirm -> confirmed, 10 recovery codes # 6. GET /mfa/status/{id} -> enabled, methods contains totp, 10 codes remaining # 7. POST /mfa/recovery-codes/regenerate -> 10 new codes # 8. DELETE /mfa/totp/{id} -> disabled # 9. GET /mfa/status/{id} -> not enabled # 10. Cleanup: delete user # # Usage: pwsh -File demo_admin_mfa.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 $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 } } # Base32 (RFC 4648) decoder. function ConvertFrom-Base32([string]$s) { $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" $s = $s.ToUpperInvariant().TrimEnd('=') $bits = New-Object System.Text.StringBuilder foreach ($c in $s.ToCharArray()) { $v = $alphabet.IndexOf([string]$c) if ($v -lt 0) { throw "invalid base32 char: $c" } [void]$bits.Append([Convert]::ToString($v, 2).PadLeft(5, '0')) } $bitsStr = $bits.ToString() $bytes = [System.Collections.Generic.List[byte]]::new() for ($i = 0; $i + 8 -le $bitsStr.Length; $i += 8) { $bytes.Add([Convert]::ToByte($bitsStr.Substring($i, 8), 2)) } return ,$bytes.ToArray() } # RFC 6238 TOTP / RFC 4226 HOTP, SHA1, 6 digits, 30 s step. function Compute-Totp([string]$base32Secret) { $key = ConvertFrom-Base32 $base32Secret $t = [int64]([Math]::Floor(([DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) / 30)) $tbytes = [BitConverter]::GetBytes($t) if ([BitConverter]::IsLittleEndian) { [Array]::Reverse($tbytes) } $hmac = New-Object System.Security.Cryptography.HMACSHA1(,$key) $hash = $hmac.ComputeHash($tbytes) $offset = $hash[$hash.Length - 1] -band 0x0F $code = (([int]$hash[$offset] -band 0x7F) -shl 24) ` -bor (([int]$hash[$offset+1] -band 0xFF) -shl 16) ` -bor (([int]$hash[$offset+2] -band 0xFF) -shl 8) ` -bor ([int]$hash[$offset+3] -band 0xFF) return ($code % 1000000).ToString("D6") } $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"; 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 = "adminmfa_" + [Guid]::NewGuid().ToString("N").Substring(0,8) $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/totp/setup" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/totp/setup" -Headers $ADMIN ` -Body (@{ userId = $UserId; username = $user } | ConvertTo-Json) if (-not $r.secret_base32 -or -not $r.setup_token) { throw "setup answer lacks secret_base32 or setup_token: $($r | ConvertTo-Json)" } Write-Host " ok: secret and setup token issued" -ForegroundColor Green return $r } Measure-Step "5. POST /mfa/totp/confirm (code + setup token)" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/totp/confirm" -Headers $ADMIN ` -Body (@{ userId = $UserId; code = (Compute-Totp $setup.secret_base32); 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 "6. GET /mfa/status - enabled" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/mfa/status/$UserId" -Headers $ADMIN if (-not $r.enabled -or $r.methods -notcontains "totp" -or $r.recovery_codes_remaining -ne 10) { throw "status: $($r | ConvertTo-Json)" } Write-Host " ok: enabled, totp, 10 codes remaining" -ForegroundColor Green } | Out-Null Measure-Step "7. POST /mfa/recovery-codes/regenerate" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/recovery-codes/regenerate" -Headers $ADMIN ` -Body (@{ userId = $UserId } | ConvertTo-Json) if ($r.recovery_codes.Count -ne 10) { throw "regenerate: $($r | ConvertTo-Json)" } Write-Host " ok: 10 new codes" -ForegroundColor Green } | Out-Null Measure-Step "8. DELETE /mfa/totp - disable" { $r = Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/mfa/totp/$UserId" -Headers $ADMIN if (-not $r.disabled) { throw "disable: $($r | ConvertTo-Json)" } Write-Host " ok: disabled" -ForegroundColor Green } | Out-Null Measure-Step "9. GET /mfa/status - not enabled" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/mfa/status/$UserId" -Headers $ADMIN if ($r.enabled) { throw "still enabled: $($r | ConvertTo-Json)" } Write-Host " ok: not enabled" -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