mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-05 18:48:41 +00:00
feat(modal): refactor modal types and integrate security action requirements
This commit is contained in:
@@ -4,25 +4,18 @@
|
|||||||
import { parseTotpEnabled } from '$lib/utils/totp';
|
import { parseTotpEnabled } from '$lib/utils/totp';
|
||||||
import { tick } from 'svelte';
|
import { tick } from 'svelte';
|
||||||
import { extractError } from '$lib/utils/misc';
|
import { extractError } from '$lib/utils/misc';
|
||||||
|
import type { ModalItem, ModalMode } from '$lib/types/modal';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
show?: boolean;
|
show?: boolean;
|
||||||
mode?:
|
mode?: ModalMode;
|
||||||
| 'decrypt'
|
|
||||||
| 'encrypt'
|
|
||||||
| 'confirm'
|
|
||||||
| 'prompt'
|
|
||||||
| 'multiselect'
|
|
||||||
| 'totp'
|
|
||||||
| 'totpSetup'
|
|
||||||
| 'report';
|
|
||||||
title?: string;
|
title?: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
inputType?: string;
|
inputType?: string;
|
||||||
inputMaxLength?: number | null;
|
inputMaxLength?: number | null;
|
||||||
items?: { label: string; value: unknown }[];
|
items?: ModalItem[];
|
||||||
initialValue?: unknown;
|
initialValue?: unknown;
|
||||||
totpActive?: boolean | null;
|
totpActive?: boolean | null;
|
||||||
reportTarget?: 'user' | 'paste' | null;
|
reportTarget?: 'user' | 'paste' | null;
|
||||||
|
|||||||
@@ -1,39 +1,5 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store';
|
||||||
|
import type { ModalOpenOptions, ModalState } from '$lib/types/modal';
|
||||||
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<Omit<ModalState, 'show'>> & {
|
|
||||||
mode: ModalMode;
|
|
||||||
cancelValue?: unknown;
|
|
||||||
};
|
|
||||||
|
|
||||||
const initialState: ModalState = {
|
const initialState: ModalState = {
|
||||||
show: false,
|
show: false,
|
||||||
|
|||||||
@@ -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<Omit<ModalState, 'show'>> & {
|
||||||
|
mode: ModalMode;
|
||||||
|
cancelValue?: unknown;
|
||||||
|
};
|
||||||
@@ -9,10 +9,3 @@ export function parseTotpEnabled(tokenValue: string | null) {
|
|||||||
return false;
|
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;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -31,7 +31,6 @@
|
|||||||
extractError
|
extractError
|
||||||
} from '$lib/utils/misc';
|
} from '$lib/utils/misc';
|
||||||
import { getToken, hasRole, roles } from '$lib/utils/auth';
|
import { getToken, hasRole, roles } from '$lib/utils/auth';
|
||||||
import { needsAdminTotp } from '$lib/utils/totp';
|
|
||||||
import { openModal } from '$lib/stores/modal';
|
import { openModal } from '$lib/stores/modal';
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '$lib/stores/user';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
@@ -135,6 +134,76 @@
|
|||||||
{ label: 'Administrator', value: 4 }
|
{ 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<string>({
|
||||||
|
mode: 'totp',
|
||||||
|
title,
|
||||||
|
placeholder: 'Enter 6-digit code',
|
||||||
|
inputType: 'text',
|
||||||
|
confirmButtonText,
|
||||||
|
cancelValue: ''
|
||||||
|
})
|
||||||
|
).trim();
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchPage(pageNum: number) {
|
async function fetchPage(pageNum: number) {
|
||||||
if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return;
|
if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return;
|
||||||
loading = true;
|
loading = true;
|
||||||
@@ -153,29 +222,10 @@
|
|||||||
loading = false;
|
loading = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleUserUpdate(displayName?: string, selectedRoles?: number) {
|
async function handleUserUpdate(displayName?: string, selectedRoles?: number, totpcode?: string) {
|
||||||
loading = true;
|
loading = true;
|
||||||
modalError = '';
|
modalError = '';
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
const currentRoles = data.user?.roles ?? 0;
|
|
||||||
const nextRoles = selectedRoles ?? currentRoles;
|
|
||||||
let totpcode = '';
|
|
||||||
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) {
|
|
||||||
totpcode = String(
|
|
||||||
await openModal<string>({
|
|
||||||
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}`, {
|
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -185,11 +235,12 @@
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
...(displayName !== undefined ? { displayName: displayName.trim() } : {}),
|
...(displayName !== undefined ? { displayName: displayName.trim() } : {}),
|
||||||
...(selectedRoles !== undefined ? { roles: selectedRoles } : {}),
|
...(selectedRoles !== undefined ? { roles: selectedRoles } : {}),
|
||||||
...(totpcode ? { totpcode } : {})
|
...(totpcode?.trim() ? { totpcode: totpcode.trim() } : {})
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
loading = false;
|
loading = false;
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
loading = false;
|
||||||
const err = await res.json();
|
const err = await res.json();
|
||||||
modalError = extractError(err) || 'Failed to update user';
|
modalError = extractError(err) || 'Failed to update user';
|
||||||
await openModal({
|
await openModal({
|
||||||
@@ -201,10 +252,12 @@
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
data.user!.displayName = displayName || data.user!.displayName;
|
try {
|
||||||
if (selectedRoles !== undefined) {
|
await refreshUserInfo();
|
||||||
data.user!.roles = selectedRoles;
|
} catch {
|
||||||
|
// ignore refresh failures and keep successful update result
|
||||||
}
|
}
|
||||||
|
loading = false;
|
||||||
modalError = '';
|
modalError = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,7 +285,8 @@
|
|||||||
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
|
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${token}`
|
Authorization: `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
body: totpEnabled && totpcode ? JSON.stringify({ totpcode }) : undefined
|
body: totpEnabled && totpcode ? JSON.stringify({ totpcode }) : undefined
|
||||||
});
|
});
|
||||||
@@ -385,7 +439,36 @@
|
|||||||
});
|
});
|
||||||
if (!Array.isArray(value)) return;
|
if (!Array.isArray(value)) return;
|
||||||
const bitfield = value.reduce((acc, val) => acc | val, 0);
|
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() {
|
async function openDeleteAccount() {
|
||||||
@@ -409,6 +492,7 @@
|
|||||||
});
|
});
|
||||||
if (result) {
|
if (result) {
|
||||||
handleTotpConfirm(result);
|
handleTotpConfirm(result);
|
||||||
|
await refreshUserInfo();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -59,6 +59,51 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
|
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<IActionResult> 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}")]
|
[HttpPatch("uuid/{uuid}")]
|
||||||
[Authorize(Policy = "JwtOnly")]
|
[Authorize(Policy = "JwtOnly")]
|
||||||
[EnableRateLimiting("Strict")]
|
[EnableRateLimiting("Strict")]
|
||||||
@@ -82,6 +127,10 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
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." });
|
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;
|
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
|
||||||
if (jwtUser.Roles.HasFlag(Role.Admin) || user.UUID == jwtUser.UUID) // only admins or self
|
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.Roles.HasFlag(Role.Admin))
|
||||||
{
|
{
|
||||||
if (jwtUser.TotpEnabled)
|
if (jwtUser.TotpEnabled && updatingAdminFields)
|
||||||
{
|
{
|
||||||
if (
|
if (
|
||||||
string.IsNullOrEmpty(updatedUser.TotpCode)
|
string.IsNullOrEmpty(updatedUser.TotpCode)
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace SharpbinV3.Server.Data.Enums
|
||||||
|
{
|
||||||
|
public enum SecurityAction
|
||||||
|
{
|
||||||
|
UpdateRoles = 1,
|
||||||
|
DeleteUser = 2
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user