diff --git a/SharpbinV3.Client/src/lib/components/Modal.svelte b/SharpbinV3.Client/src/lib/components/Modal.svelte index 4b64cef..468893c 100644 --- a/SharpbinV3.Client/src/lib/components/Modal.svelte +++ b/SharpbinV3.Client/src/lib/components/Modal.svelte @@ -4,25 +4,18 @@ import { parseTotpEnabled } from '$lib/utils/totp'; import { tick } from 'svelte'; import { extractError } from '$lib/utils/misc'; + import type { ModalItem, ModalMode } from '$lib/types/modal'; interface Props { show?: boolean; - mode?: - | 'decrypt' - | 'encrypt' - | 'confirm' - | 'prompt' - | 'multiselect' - | 'totp' - | 'totpSetup' - | 'report'; + mode?: ModalMode; title?: string; message?: string; error?: string; placeholder?: string; inputType?: string; inputMaxLength?: number | null; - items?: { label: string; value: unknown }[]; + items?: ModalItem[]; initialValue?: unknown; totpActive?: boolean | null; reportTarget?: 'user' | 'paste' | null; diff --git a/SharpbinV3.Client/src/lib/stores/modal.ts b/SharpbinV3.Client/src/lib/stores/modal.ts index 7e5e9c6..9c7227e 100644 --- a/SharpbinV3.Client/src/lib/stores/modal.ts +++ b/SharpbinV3.Client/src/lib/stores/modal.ts @@ -1,39 +1,5 @@ import { writable } from 'svelte/store'; - -type ModalMode = - | 'decrypt' - | 'encrypt' - | 'confirm' - | 'prompt' - | 'multiselect' - | 'totp' - | 'totpSetup' - | 'report'; - -type ModalItem = { label: string; value: unknown }; - -type ModalState = { - show: boolean; - mode: ModalMode; - title: string; - message: string; - error: string; - placeholder: string; - inputType: string; - maxInputLength?: number; - items: ModalItem[]; - initialValue: unknown; - totpActive: boolean | null; - reportTarget: 'user' | 'paste' | null; - reportTargetId: string | number | null; - reportSiteKey: string | null; - confirmButtonText: string; -}; - -type ModalOpenOptions = Partial> & { - mode: ModalMode; - cancelValue?: unknown; -}; +import type { ModalOpenOptions, ModalState } from '$lib/types/modal'; const initialState: ModalState = { show: false, diff --git a/SharpbinV3.Client/src/lib/types/modal.ts b/SharpbinV3.Client/src/lib/types/modal.ts new file mode 100644 index 0000000..88dba03 --- /dev/null +++ b/SharpbinV3.Client/src/lib/types/modal.ts @@ -0,0 +1,34 @@ +export type ModalMode = + | 'decrypt' + | 'encrypt' + | 'confirm' + | 'prompt' + | 'multiselect' + | 'totp' + | 'totpSetup' + | 'report'; + +export type ModalItem = { label: string; value: unknown }; + +export type ModalState = { + show: boolean; + mode: ModalMode; + title: string; + message: string; + error: string; + placeholder: string; + inputType: string; + maxInputLength?: number; + items: ModalItem[]; + initialValue: unknown; + totpActive: boolean | null; + reportTarget: 'user' | 'paste' | null; + reportTargetId: string | number | null; + reportSiteKey: string | null; + confirmButtonText: string; +}; + +export type ModalOpenOptions = Partial> & { + mode: ModalMode; + cancelValue?: unknown; +}; diff --git a/SharpbinV3.Client/src/lib/utils/totp.ts b/SharpbinV3.Client/src/lib/utils/totp.ts index acacecf..08e01b7 100644 --- a/SharpbinV3.Client/src/lib/utils/totp.ts +++ b/SharpbinV3.Client/src/lib/utils/totp.ts @@ -9,10 +9,3 @@ export function parseTotpEnabled(tokenValue: string | null) { return false; } } - -export function needsAdminTotp(totpEnabled: boolean, currentRoles: number, nextRoles: number) { - if (!totpEnabled) return false; - const nextHasAdmin = (nextRoles & 4) !== 0; - const alreadyAdmin = (currentRoles & 4) !== 0; - return nextHasAdmin && !alreadyAdmin; -} diff --git a/SharpbinV3.Client/src/routes/user/[username]/+page.svelte b/SharpbinV3.Client/src/routes/user/[username]/+page.svelte index 00d44b2..2c0127f 100644 --- a/SharpbinV3.Client/src/routes/user/[username]/+page.svelte +++ b/SharpbinV3.Client/src/routes/user/[username]/+page.svelte @@ -31,7 +31,6 @@ extractError } from '$lib/utils/misc'; import { getToken, hasRole, roles } from '$lib/utils/auth'; - import { needsAdminTotp } from '$lib/utils/totp'; import { openModal } from '$lib/stores/modal'; import { user } from '$lib/stores/user'; import { onMount } from 'svelte'; @@ -135,6 +134,76 @@ { label: 'Administrator', value: 4 } ]; + type ActionSecurityRequirements = { + requiresTotp?: boolean; + blocked?: boolean; + message?: string; + }; + + type SecurityAction = 'UpdateRoles' | 'DeleteUser'; + + async function fetchActionSecurityRequirements(action: SecurityAction) { + const token = getToken(); + if (!token || !data.user?.uuid) { + return { requiresTotp: false, blocked: false } satisfies ActionSecurityRequirements; + } + + const res = await fetch(`/api/user/uuid/${data.user.uuid}/requirements?action=${action}`, { + headers: { + Authorization: `Bearer ${token}` + } + }); + + const payload = ((await res.json().catch(() => null)) ?? {}) as ActionSecurityRequirements; + if (!res.ok) { + const message = extractError(payload) || 'Failed to check security requirements.'; + throw new Error(message); + } + + return { + requiresTotp: Boolean(payload.requiresTotp), + blocked: Boolean(payload.blocked), + message: payload.message || '' + } satisfies ActionSecurityRequirements; + } + + async function refreshUserInfo() { + if (!data.user?.uuid) return; + const token = getToken(); + const res = await fetch(`/api/user/uuid/${data.user.uuid}?page=${currentPage}`, { + headers: token ? { Authorization: `Bearer ${token}` } : {} + }); + if (!res.ok) return; + const json = await res.json().catch(() => null); + if (!json?.user) return; + data.user = json.user; + if (isOwner) { + user.update((u) => + u + ? { + ...u, + displayName: json.user.displayName ?? u.displayName, + roles: json.user.roles ?? u.roles, + isBanned: json.user.isBanned ?? u.isBanned + } + : u + ); + } + } + + async function promptTotpCode(title: string, confirmButtonText: string) { + return String( + await openModal({ + mode: 'totp', + title, + placeholder: 'Enter 6-digit code', + inputType: 'text', + confirmButtonText, + cancelValue: '' + }) + ).trim(); + } + async function fetchPage(pageNum: number) { if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return; loading = true; @@ -153,29 +222,10 @@ loading = false; } - async function handleUserUpdate(displayName?: string, selectedRoles?: number) { + async function handleUserUpdate(displayName?: string, selectedRoles?: number, totpcode?: string) { loading = true; modalError = ''; const token = getToken(); - const currentRoles = data.user?.roles ?? 0; - const nextRoles = selectedRoles ?? currentRoles; - let totpcode = ''; - if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) { - totpcode = String( - await openModal({ - mode: 'totp', - title: 'Admin role requires TOTP', - placeholder: 'Enter 6-digit code', - inputType: 'text', - confirmButtonText: 'Continue', - cancelValue: '' - }) - ).trim(); - if (!totpcode) { - loading = false; - return; - } - } const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, { method: 'PATCH', headers: { @@ -185,11 +235,12 @@ body: JSON.stringify({ ...(displayName !== undefined ? { displayName: displayName.trim() } : {}), ...(selectedRoles !== undefined ? { roles: selectedRoles } : {}), - ...(totpcode ? { totpcode } : {}) + ...(totpcode?.trim() ? { totpcode: totpcode.trim() } : {}) }) }); loading = false; if (!res.ok) { + loading = false; const err = await res.json(); modalError = extractError(err) || 'Failed to update user'; await openModal({ @@ -201,10 +252,12 @@ }); return; } - data.user!.displayName = displayName || data.user!.displayName; - if (selectedRoles !== undefined) { - data.user!.roles = selectedRoles; + try { + await refreshUserInfo(); + } catch { + // ignore refresh failures and keep successful update result } + loading = false; modalError = ''; } @@ -232,7 +285,8 @@ const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, { method: 'DELETE', headers: { - Authorization: `Bearer ${token}` + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json' }, body: totpEnabled && totpcode ? JSON.stringify({ totpcode }) : undefined }); @@ -385,7 +439,36 @@ }); if (!Array.isArray(value)) return; const bitfield = value.reduce((acc, val) => acc | val, 0); - await handleUserUpdate(undefined, bitfield); + + let totpcode = ''; + try { + const requirements = await fetchActionSecurityRequirements('UpdateRoles'); + if (requirements.blocked) { + await openModal({ + mode: 'confirm', + title: 'Action blocked', + message: requirements.message || 'You cannot perform this action right now.', + confirmButtonText: 'OK', + cancelValue: true + }); + return; + } + if (requirements.requiresTotp) { + totpcode = await promptTotpCode('TOTP required to update roles', 'Continue'); + if (!totpcode) return; + } + } catch (e) { + await openModal({ + mode: 'confirm', + title: 'Error', + message: e instanceof Error ? e.message : 'Failed to check security requirements.', + confirmButtonText: 'OK', + cancelValue: true + }); + return; + } + + await handleUserUpdate(undefined, bitfield, totpcode); } async function openDeleteAccount() { @@ -409,6 +492,7 @@ }); if (result) { handleTotpConfirm(result); + await refreshUserInfo(); } } diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index dcfa174..372de1b 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -59,6 +59,51 @@ namespace SharpbinV3.Server.Controllers return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page); } + [HttpGet("uuid/{uuid}/requirements")] + [Authorize(Policy = "JwtOnly")] + [EnableRateLimiting("Strict")] + public async Task GetUserActionRequirements(Guid uuid, [FromQuery] SecurityAction action) + { + var jwtUser = HttpContext.GetJwtUser()!; + var targetUser = await _userService.GetByUUID(uuid); + if (targetUser == null) + return NotFound(new { success = false, message = "User not found." }); + + if ( + (targetUser.Roles.HasFlag(Role.Admin) && !jwtUser.Roles.HasFlag(Role.Admin)) + || (!jwtUser.Roles.HasFlag(Role.Admin) && targetUser.UUID != jwtUser.UUID) + ) + return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." }); + + if (action == SecurityAction.UpdateRoles && !jwtUser.Roles.HasFlag(Role.Admin)) + return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." }); + + if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) + { + return Ok( + new + { + success = true, + action, + requiresTotp = false, + blocked = true, + message = "2FA is required to perform this action.", + } + ); + } + + return Ok( + new + { + success = true, + action, + requiresTotp = jwtUser.TotpEnabled, + blocked = false, + message = jwtUser.TotpEnabled ? "TOTP verification is required." : "No TOTP verification required.", + } + ); + } + [HttpPatch("uuid/{uuid}")] [Authorize(Policy = "JwtOnly")] [EnableRateLimiting("Strict")] @@ -82,6 +127,10 @@ namespace SharpbinV3.Server.Controllers if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); + var updatingAdminFields = + (updatedUser.Roles.HasValue && updatedUser.Roles.Value != user.Roles) + || (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != user.IsBanned); + user.DisplayName = updatedUser.DisplayName ?? user.DisplayName; if (jwtUser.Roles.HasFlag(Role.Admin) || user.UUID == jwtUser.UUID) // only admins or self { @@ -90,7 +139,7 @@ namespace SharpbinV3.Server.Controllers } if (jwtUser.Roles.HasFlag(Role.Admin)) { - if (jwtUser.TotpEnabled) + if (jwtUser.TotpEnabled && updatingAdminFields) { if ( string.IsNullOrEmpty(updatedUser.TotpCode) diff --git a/SharpbinV3.Server/Data/Enums/SecurityAction.cs b/SharpbinV3.Server/Data/Enums/SecurityAction.cs new file mode 100644 index 0000000..266ff1e --- /dev/null +++ b/SharpbinV3.Server/Data/Enums/SecurityAction.cs @@ -0,0 +1,8 @@ +namespace SharpbinV3.Server.Data.Enums +{ + public enum SecurityAction + { + UpdateRoles = 1, + DeleteUser = 2 + } +}