feat(settings): password change, 2FA enable/disable, API-key UI + Swagger; fix Owner RBAC drift
All checks were successful
CI / backend-types (push) Successful in 9s
CI / frontend-build (push) Successful in 15s
CI / agent-tests (push) Successful in 42s
CI / integration (push) Successful in 21s

Settings was missing self-service account security and any API-key UI:
- Account security (new Security tab): change password (POST /auth/change-password
  — verifies current via Argon2, rejects unchanged), enable 2FA (wires the
  existing /auth/2fa/setup QR + /auth/2fa/verify), and disable 2FA (new
  POST /auth/2fa/disable, requires a current code so a hijacked session can't
  strip the second factor).
- New API tab: create/list/revoke per-license API keys (the overnight backend
  had no UI), plaintext shown once, plus an 'API docs' button to /api/docs (Swagger).

Root-cause RBAC fix — the system-default Owner role enumerated per-resource
wildcards (server.*, wipe.*, ...) and drifted: apikeys, webhooks, alerts,
analytics, chat, schedules, notifications, map, users and ALL plugin-config
modules (plus singular plugin.* vs granted plugins.*) were locked out for any
non-super-admin Owner. Owner = full control of its license:
- migration 025 sets the Owner role to {"*": true}
- PermissionsGuard honors '*' as allow-all
- frontend hasPermission honors '*' and resource.* wildcards (was exact-match
  only, so wildcard-based roles silently failed)

Backend tsc + frontend build green. NOTE: migration 025 auto-applies on a fresh
DB (Saturday); the live DB needs the one-line UPDATE applied to unlock the API
tab for a non-super-admin owner.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Vantz Stockwell
2026-06-12 08:57:17 -04:00
parent 57858a1e1c
commit 7f2207bc28
7 changed files with 417 additions and 1 deletions

View File

@@ -28,6 +28,10 @@ export class PermissionsGuard implements CanActivate {
const permissions = user.permissions as Record<string, boolean> | undefined;
if (!permissions) return false;
// Global wildcard — the Owner role (full control of its license) carries
// {"*": true}, so new features never need to amend the role enumeration.
if (permissions['*'] === true) return true;
// Support wildcard: "server.*" matches "server.view", "server.console", etc.
const parts = requiredPermission.split('.');
const wildcard = parts[0] + '.*';

View File

@@ -13,6 +13,7 @@ import { LoginDto } from './dto/login.dto';
import { RefreshTokenDto } from './dto/refresh-token.dto';
import { VerifyTotpDto } from './dto/verify-totp.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { ForgotPasswordDto } from './dto/forgot-password.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { Public } from '../../common/decorators/public.decorator';
@@ -61,6 +62,30 @@ export class AuthController {
return this.authService.verifyTotp(userId, dto.code);
}
@Post('2fa/disable')
@ApiBearerAuth()
@ApiOperation({ summary: 'Disable TOTP 2FA (requires a current code)' })
async disableTotp(
@CurrentUser('sub') userId: string,
@Body() dto: VerifyTotpDto,
) {
return this.authService.disableTotp(userId, dto.code);
}
@Post('change-password')
@ApiBearerAuth()
@ApiOperation({ summary: 'Change the current user password' })
async changePassword(
@CurrentUser('sub') userId: string,
@Body() dto: ChangePasswordDto,
) {
return this.authService.changePassword(
userId,
dto.current_password,
dto.new_password,
);
}
@Get('me')
@ApiBearerAuth()
@ApiOperation({ summary: 'Get current user profile' })

View File

@@ -335,6 +335,56 @@ export class AuthService {
throw new NotImplementedException('Password reset not yet configured');
}
async changePassword(userId: string, currentPassword: string, newPassword: string) {
const user = await this.userRepository.findOne({ where: { id: userId } });
if (!user) {
throw new NotFoundException('User not found');
}
const valid = await argon2.verify(user.password_hash, currentPassword);
if (!valid) {
throw new UnauthorizedException('Current password is incorrect');
}
if (await argon2.verify(user.password_hash, newPassword)) {
throw new BadRequestException('New password must be different from the current one');
}
const password_hash = await argon2.hash(newPassword);
await this.userRepository.update(user.id, { password_hash });
this.logger.log(`Password changed for user ${user.id}`);
// NOTE: existing JWTs remain valid until expiry — this design has no
// server-side refresh-token store to revoke. Session invalidation on
// password change is a follow-up (tracked separately).
return { success: true };
}
async disableTotp(userId: string, code: string) {
const user = await this.userRepository.findOne({ where: { id: userId } });
if (!user) {
throw new NotFoundException('User not found');
}
if (!user.totp_enabled) {
throw new BadRequestException('2FA is not enabled');
}
// Require a valid current code — proves possession of the second factor
// before removing it, so a hijacked session can't silently strip 2FA.
const valid = await this.verifyTotpCode(user, code);
if (!valid) {
throw new UnauthorizedException('Invalid TOTP code');
}
await this.userRepository.update(user.id, {
totp_enabled: false,
totp_secret: null,
});
this.logger.log(`TOTP disabled for user ${user.id}`);
return { success: true };
}
// Helper methods
private async generateTokens(user: User, licenseId?: string) {

View File

@@ -0,0 +1,14 @@
import { IsString, MinLength, MaxLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class ChangePasswordDto {
@ApiProperty({ description: 'Current account password' })
@IsString()
current_password: string;
@ApiProperty({ description: 'New password', minLength: 8, maxLength: 128 })
@IsString()
@MinLength(8)
@MaxLength(128)
new_password: string;
}

View File

@@ -0,0 +1,15 @@
-- 025_owner_full_access.sql
--
-- The system-default Owner role enumerated per-resource wildcards
-- (server.*, wipe.*, players.*, ...). Every feature added since drift past that
-- enumeration: apikeys, webhooks, alerts, analytics, chat, schedules,
-- notifications, map, users, and ALL plugin-config modules (plus a singular
-- 'plugin.*' vs granted 'plugins.*' mismatch) were silently locked out for any
-- non-super-admin Owner — PermissionsGuard denies a permission the role doesn't
-- grant. The Owner has "full control of their license" by definition, so grant
-- a global wildcard instead of an enumeration that must be amended per feature.
--
-- PermissionsGuard and the frontend auth store both honor "*" as allow-all.
UPDATE roles
SET permissions = '{"*": true}'::jsonb
WHERE role_name = 'Owner' AND is_system_default = true;

View File

@@ -97,7 +97,12 @@ export const useAuthStore = defineStore('auth', () => {
? decodeJwtPermissions(accessToken.value)
: {}
return perms[permission] === true
// Honor the global wildcard (Owner) and resource wildcards ("server.*")
// so role permissions stored as wildcards aren't missed by an exact match.
if (perms['*'] === true) return true
if (perms[permission] === true) return true
const resourceWildcard = permission.split('.')[0] + '.*'
return perms[resourceWildcard] === true
}
return {

View File

@@ -33,6 +33,31 @@ const publicSiteForm = ref({
status_page_description: '',
})
// --- Security: password change ---
const pwForm = ref({ current_password: '', new_password: '', confirm: '' })
const changingPw = ref(false)
// --- Security: 2FA enrollment flow ---
const totp = ref<{ qr: string; secret: string; code: string; setting: boolean }>({
qr: '', secret: '', code: '', setting: false,
})
const disable2fa = ref({ open: false, code: '', busy: false })
// --- API keys ---
interface ApiKeyRow {
id: string
name: string
key_prefix: string
last_used_at: string | null
is_active: boolean
created_at: string
}
const apiKeys = ref<ApiKeyRow[]>([])
const newKeyName = ref('')
const creatingKey = ref(false)
const createdKey = ref<string | null>(null)
const loadingKeys = ref(false)
async function loadForms() {
if (auth.user) {
accountForm.value.username = auth.user.username
@@ -89,16 +114,144 @@ async function savePublicSite() {
}
}
async function changePassword() {
if (pwForm.value.new_password.length < 8) {
toast.error('New password must be at least 8 characters')
return
}
if (pwForm.value.new_password !== pwForm.value.confirm) {
toast.error('New password and confirmation do not match')
return
}
changingPw.value = true
try {
await api.post('/auth/change-password', {
current_password: pwForm.value.current_password,
new_password: pwForm.value.new_password,
})
toast.success('Password changed')
pwForm.value = { current_password: '', new_password: '', confirm: '' }
} catch (err) {
toast.error('Failed to change password: ' + (err as Error).message)
} finally {
changingPw.value = false
}
}
async function startTotpSetup() {
totp.value.setting = true
try {
const res = await api.post<{ qr_code: string; secret: string }>('/auth/2fa/setup', {})
totp.value.qr = res.qr_code
totp.value.secret = res.secret
} catch (err) {
totp.value.setting = false
toast.error('Failed to start 2FA setup: ' + (err as Error).message)
}
}
async function confirmTotpSetup() {
if (totp.value.code.length !== 6) {
toast.error('Enter the 6-digit code from your authenticator')
return
}
try {
await api.post('/auth/2fa/verify', { code: totp.value.code })
await auth.validateSession()
toast.success('Two-factor authentication enabled')
totp.value = { qr: '', secret: '', code: '', setting: false }
} catch (err) {
toast.error('Invalid code — try again: ' + (err as Error).message)
}
}
function cancelTotpSetup() {
totp.value = { qr: '', secret: '', code: '', setting: false }
}
async function confirmDisable2fa() {
if (disable2fa.value.code.length !== 6) {
toast.error('Enter your current 6-digit code to disable 2FA')
return
}
disable2fa.value.busy = true
try {
await api.post('/auth/2fa/disable', { code: disable2fa.value.code })
await auth.validateSession()
toast.success('Two-factor authentication disabled')
disable2fa.value = { open: false, code: '', busy: false }
} catch (err) {
toast.error('Failed to disable 2FA: ' + (err as Error).message)
} finally {
disable2fa.value.busy = false
}
}
async function loadApiKeys() {
loadingKeys.value = true
try {
apiKeys.value = await api.get<ApiKeyRow[]>('/api-keys')
} catch (err) {
toast.error('Failed to load API keys: ' + (err as Error).message)
} finally {
loadingKeys.value = false
}
}
async function createApiKey() {
if (!newKeyName.value.trim()) {
toast.error('Give the key a name')
return
}
creatingKey.value = true
createdKey.value = null
try {
const res = await api.post<{ plaintext_key: string }>('/api-keys', {
name: newKeyName.value.trim(),
})
createdKey.value = res.plaintext_key
newKeyName.value = ''
await loadApiKeys()
} catch (err) {
toast.error('Failed to create API key: ' + (err as Error).message)
} finally {
creatingKey.value = false
}
}
async function revokeApiKey(id: string) {
try {
await api.del(`/api-keys/${id}`)
toast.success('API key revoked')
await loadApiKeys()
} catch (err) {
toast.error('Failed to revoke key: ' + (err as Error).message)
}
}
function copyKey(value: string) {
navigator.clipboard?.writeText(value)
toast.success('Copied to clipboard')
}
onMounted(() => {
loadForms()
loadApiKeys()
})
const tabItems = [
{ value: 'account', label: 'Account', icon: 'user' },
{ value: 'security', label: 'Security', icon: 'shield' },
{ value: 'api', label: 'API', icon: 'code' },
{ value: 'license', label: 'License', icon: 'key' },
{ value: 'domain', label: 'Domain', icon: 'globe' },
{ value: 'public', label: 'Public status', icon: 'eye' },
]
const swaggerUrl = '/api/docs'
function openApiDocs() {
window.open(swaggerUrl, '_blank', 'noopener')
}
</script>
<template>
@@ -142,6 +295,120 @@ const tabItems = [
>
{{ auth.user?.totp_enabled ? 'Enabled' : 'Not configured' }}
</Badge>
<span class="totp-hint">Manage in the Security tab</span>
</div>
</Panel>
<!-- Security -->
<Panel v-if="section === 'security'" title="Security" eyebrow="Password &amp; 2FA">
<div class="sec-stack">
<!-- Change password -->
<div class="sec-block">
<h3 class="sec-title">Change password</h3>
<div class="pw-grid">
<Input v-model="pwForm.current_password" type="password" label="Current password" placeholder="••••••••" />
<Input v-model="pwForm.new_password" type="password" label="New password" placeholder="At least 8 characters" />
<Input v-model="pwForm.confirm" type="password" label="Confirm new password" placeholder="Re-enter new password" />
</div>
<Button size="sm" icon="save" :loading="changingPw" @click="changePassword">Update password</Button>
</div>
<!-- Two-factor authentication -->
<div class="sec-block">
<div class="sec-head">
<h3 class="sec-title">Two-factor authentication</h3>
<Badge :tone="auth.user?.totp_enabled ? 'online' : 'warn'" :dot="true">
{{ auth.user?.totp_enabled ? 'Enabled' : 'Not configured' }}
</Badge>
</div>
<!-- Enabled -> offer disable -->
<template v-if="auth.user?.totp_enabled">
<p class="sec-note">Your account is protected with an authenticator app.</p>
<Button v-if="!disable2fa.open" size="sm" variant="danger" icon="shield-off" @click="disable2fa.open = true">
Disable 2FA
</Button>
<div v-else class="twofa-confirm">
<p class="sec-note">Enter your current 6-digit code to confirm.</p>
<Input v-model="disable2fa.code" label="Authenticator code" placeholder="123456" />
<div class="btn-row">
<Button size="sm" variant="danger" :loading="disable2fa.busy" @click="confirmDisable2fa">Confirm disable</Button>
<Button size="sm" variant="ghost" @click="disable2fa.open = false">Cancel</Button>
</div>
</div>
</template>
<!-- Not enabled -> enrollment -->
<template v-else>
<p class="sec-note">Add a second factor with an authenticator app (Google Authenticator, Authy, 1Password).</p>
<Button v-if="!totp.setting" size="sm" icon="shield" @click="startTotpSetup">Enable 2FA</Button>
<div v-else class="twofa-enroll">
<div v-if="totp.qr" class="qr-wrap">
<img :src="totp.qr" alt="2FA QR code" class="qr-img" />
<div class="qr-side">
<p class="sec-note">Scan with your authenticator app, or enter the secret manually:</p>
<code class="secret">{{ totp.secret }}</code>
</div>
</div>
<Input v-model="totp.code" label="Enter the 6-digit code to confirm" placeholder="123456" />
<div class="btn-row">
<Button size="sm" icon="check" @click="confirmTotpSetup">Verify &amp; enable</Button>
<Button size="sm" variant="ghost" @click="cancelTotpSetup">Cancel</Button>
</div>
</div>
</template>
</div>
</div>
</Panel>
<!-- API access -->
<Panel v-if="section === 'api'" title="API access" eyebrow="Programmatic">
<template #actions>
<Button size="sm" variant="secondary" icon="book-open" icon-right="external-link" @click="openApiDocs">API docs</Button>
</template>
<div class="api-stack">
<p class="section-note">
Create a key to call the Corrosion REST API from your own tooling. Send it as
<code class="inline-code">Authorization: Bearer corr_</code> a key acts as the license owner.
The full key is shown once at creation.
</p>
<!-- Create -->
<div class="key-create">
<Input v-model="newKeyName" label="New key name" placeholder="e.g. CI deploy, monitoring" style="flex:1" />
<Button size="sm" icon="plus" :loading="creatingKey" @click="createApiKey">Create key</Button>
</div>
<!-- Just-created plaintext key (shown once) -->
<div v-if="createdKey" class="key-reveal">
<div class="key-reveal__head">
<span class="field-label">Copy your key now it won't be shown again</span>
<Button size="sm" variant="ghost" icon="copy" @click="copyKey(createdKey!)">Copy</Button>
</div>
<code class="key-reveal__value">{{ createdKey }}</code>
</div>
<!-- Existing keys -->
<div v-if="loadingKeys" class="key-empty">Loading…</div>
<div v-else-if="apiKeys.length === 0" class="key-empty">No API keys yet.</div>
<table v-else class="key-table">
<thead>
<tr><th>Name</th><th>Prefix</th><th>Last used</th><th>Status</th><th></th></tr>
</thead>
<tbody>
<tr v-for="k in apiKeys" :key="k.id">
<td>{{ k.name }}</td>
<td><code class="field-mono">corr_{{ k.key_prefix }}…</code></td>
<td>{{ k.last_used_at ? new Date(k.last_used_at).toLocaleString() : 'Never' }}</td>
<td>
<Badge :tone="k.is_active ? 'online' : 'offline'">{{ k.is_active ? 'Active' : 'Revoked' }}</Badge>
</td>
<td class="key-actions">
<Button v-if="k.is_active" size="sm" variant="danger-soft" icon="trash-2" @click="revokeApiKey(k.id)">Revoke</Button>
</td>
</tr>
</tbody>
</table>
</div>
</Panel>
@@ -309,8 +576,44 @@ const tabItems = [
.cc-textarea::placeholder { color: var(--text-muted); }
.cc-textarea:focus { box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }
.totp-hint { font-size: var(--text-xs); color: var(--text-muted); margin-left: auto; }
/* Security tab */
.sec-stack { display: flex; flex-direction: column; gap: 22px; }
.sec-block { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
.sec-block + .sec-block { padding-top: 20px; border-top: 1px solid var(--border-subtle); }
.sec-head { display: flex; align-items: center; gap: 10px; }
.sec-title { font-size: var(--text-sm); font-weight: 600; color: var(--text-primary); margin: 0; }
.sec-note { font-size: var(--text-sm); color: var(--text-tertiary); margin: 0; max-width: 60ch; }
.pw-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; width: 100%; }
.btn-row { display: flex; gap: 8px; }
.twofa-enroll, .twofa-confirm { display: flex; flex-direction: column; gap: 12px; width: 100%; max-width: 420px; }
.qr-wrap { display: flex; gap: 16px; align-items: center; }
.qr-img { width: 148px; height: 148px; border-radius: var(--radius-md); background: #fff; padding: 6px; flex: none; }
.qr-side { display: flex; flex-direction: column; gap: 8px; }
.secret { font-family: var(--font-mono); font-size: var(--text-xs); color: var(--text-primary);
background: var(--surface-inset); padding: 6px 9px; border-radius: var(--radius-sm); word-break: break-all; }
/* API tab */
.api-stack { display: flex; flex-direction: column; gap: 16px; }
.inline-code, .field-mono code, code.inline-code { font-family: var(--font-mono); font-size: var(--text-xs);
background: var(--surface-inset); padding: 1px 5px; border-radius: var(--radius-sm); color: var(--text-primary); }
.key-create { display: flex; gap: 10px; align-items: flex-end; }
.key-reveal { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px;
background: var(--surface-raised-2); border-radius: var(--radius-md); box-shadow: var(--ring-default); }
.key-reveal__head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.key-reveal__value { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--accent-text);
word-break: break-all; }
.key-empty { font-size: var(--text-sm); color: var(--text-muted); padding: 12px 0; }
.key-table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); }
.key-table th { text-align: left; font-size: var(--text-xs); font-weight: 600; color: var(--text-secondary);
padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); }
.key-table td { padding: 9px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary); vertical-align: middle; }
.key-actions { text-align: right; }
@media (max-width: 680px) {
.form-grid { grid-template-columns: 1fr; }
.lic-grid { grid-template-columns: 1fr 1fr; }
.pw-grid { grid-template-columns: 1fr; }
}
</style>