diff --git a/src/client/css/base.css b/src/client/css/base.css index 692e41a..c6fd96b 100644 --- a/src/client/css/base.css +++ b/src/client/css/base.css @@ -278,6 +278,22 @@ textarea { font-size: 13px; } +input[type="checkbox"] { + width: 20px; + height: 20px; + min-height: 20px; + flex: 0 0 auto; +} + +.chk-row { + display: flex; + align-items: center; + gap: 8px; + font-size: 13px; + color: var(--fg); + cursor: pointer; +} + .input-sm { width: auto; min-height: 32px; @@ -343,6 +359,9 @@ th { .qr-box { display: inline-block; + align-self: flex-start; + width: fit-content; + line-height: 0; background: #ffffff; padding: 8px; border: 1px solid var(--border); diff --git a/src/client/index.html b/src/client/index.html index 19c580b..03dc22b 100644 --- a/src/client/index.html +++ b/src/client/index.html @@ -52,28 +52,16 @@
- + -

Step-Up 2FA Verification

-

Enter a fresh 6-digit TOTP code to elevate this session for 5 minutes.

+

Step-Up Verification

+

Confirm your credentials to elevate this session.

- - +

- +
diff --git a/src/client/ts/dialogs.ts b/src/client/ts/dialogs.ts index 52729ba..2c36b9d 100644 --- a/src/client/ts/dialogs.ts +++ b/src/client/ts/dialogs.ts @@ -1,5 +1,9 @@ import { apiFetch } from './api.js'; -import { el, extractErrorMessage } from './state.js'; +import { + el, + extractErrorMessage, + type ClientAuthRequirements, +} from './state.js'; export interface DiffModalData { revisionId: number; @@ -10,16 +14,75 @@ export interface DiffModalData { onRollback: () => Promise; } -export function promptStepUp(onElevated: (elevatedUntil: number) => void): Promise { +export function promptStepUp( + getRequirements: () => ClientAuthRequirements | undefined, + onElevated: (elevatedUntil: number | null) => void, +): Promise { const dialog = document.getElementById('dialog-stepup') as HTMLDialogElement; const form = document.getElementById('dialog-stepup-form') as HTMLFormElement; - const input = document.getElementById('stepup-code-input') as HTMLInputElement; + const descEl = document.getElementById('stepup-desc') as HTMLElement; + const fieldsEl = document.getElementById('stepup-fields') as HTMLElement; const errEl = document.getElementById('stepup-error') as HTMLElement; const cancelBtn = document.getElementById('stepup-cancel-btn') as HTMLButtonElement; + const reqs = getRequirements(); + const method = reqs?.stepUpMethod ?? 'totp'; + const policy = reqs?.stepUpPolicy ?? '1h'; + const pwMode = reqs?.passwordMode ?? 'any'; + const totpMode = reqs?.totpMode ?? 'any'; + const pwLabels = reqs?.passwordLabels ?? [{ id: 'pw-primary', label: 'Password' }]; + const totpLabels = reqs?.totpLabels ?? [{ id: 'totp-primary', label: 'Authenticator' }]; + + descEl.textContent = + policy === 'every-action' + ? 'Verify to authorize this single sensitive action.' + : `Verify your credentials to elevate this session (${policy}).`; + + fieldsEl.replaceChildren(); + const pwInputs: HTMLInputElement[] = []; + const codeInputs: HTMLInputElement[] = []; + + if (method === 'password' || method === 'both') { + const count = pwMode === 'all' ? Math.max(1, pwLabels.length) : 1; + for (let i = 0; i < count; i++) { + const lbl = pwMode === 'all' ? pwLabels[i]?.label ?? `Password ${i + 1}` : 'Admin Password'; + const inp = el('input', { + id: `stepup-pw-${i}`, + type: 'password', + autocomplete: 'current-password', + required: true, + autofocus: i === 0 ? true : undefined, + }); + pwInputs.push(inp); + fieldsEl.append(el('label', { for: `stepup-pw-${i}` }, lbl), inp); + } + } + + if (method === 'totp' || method === 'both') { + const count = totpMode === 'all' ? Math.max(1, totpLabels.length) : 1; + for (let i = 0; i < count; i++) { + const lbl = + totpMode === 'all' + ? `Authenticator (${totpLabels[i]?.label ?? `#${i + 1}`})` + : '6-Digit TOTP Code'; + const inp = el('input', { + id: `stepup-code-${i}`, + type: 'text', + inputmode: 'numeric', + autocomplete: 'one-time-code', + pattern: '[0-9]{6}', + maxlength: 6, + placeholder: '000000', + required: true, + autofocus: pwInputs.length === 0 && i === 0 ? true : undefined, + }); + codeInputs.push(inp); + fieldsEl.append(el('label', { for: `stepup-code-${i}` }, lbl), inp); + } + } + return new Promise((resolve) => { let settled = false; - input.value = ''; errEl.textContent = ''; const finish = (ok: boolean) => { @@ -40,16 +103,19 @@ export function promptStepUp(onElevated: (elevatedUntil: number) => void): Promi ev.preventDefault(); errEl.textContent = ''; try { - const res = await apiFetch<{ elevatedUntil: number }>('/api/auth/step-up', { + const res = await apiFetch<{ elevatedUntil: number | null }>('/api/auth/step-up', { method: 'POST', - body: { code: input.value.trim() }, + body: { + passwords: pwInputs.map((i) => i.value), + codes: codeInputs.map((i) => i.value.trim()), + }, allowStepUpRetry: false, }); onElevated(res.elevatedUntil); finish(true); } catch (err) { errEl.textContent = extractErrorMessage(err); - input.select(); + (codeInputs[0] ?? pwInputs[0])?.select(); } }; diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts index 33c55b5..2a1dcfe 100644 --- a/src/client/ts/main.ts +++ b/src/client/ts/main.ts @@ -12,6 +12,8 @@ import { THEME_STORAGE_KEY, applyTheme, initialDeviceSafeMode, + type ClientAuthRequirements, + type ClientSecuritySettings, type ClientState, type ConfigOverview, type RouteId, @@ -87,10 +89,13 @@ function updateTopBarUi(): void { themeSelect.value = state.theme; - if (state.elevatedUntil && state.elevatedUntil > Date.now()) { + if (state.security?.stepUpPolicy === 'off') { + stepupBadge.hidden = false; + stepupBadge.textContent = '[STEP-UP: OFF]'; + } else if (state.elevatedUntil && state.elevatedUntil > Date.now()) { const remSec = Math.ceil((state.elevatedUntil - Date.now()) / 1000); stepupBadge.hidden = false; - stepupBadge.textContent = `[2FA: ${remSec}s]`; + stepupBadge.textContent = remSec > 86400 ? '[ELEVATED: SESSION]' : `[2FA: ${remSec}s]`; } else { state.elevatedUntil = null; stepupBadge.hidden = true; @@ -122,9 +127,15 @@ async function renderCurrentView(): Promise { updateTopBarUi(); if (!state.authenticated) { - await renderAuthView(root, state.bootstrapped, state.safeMode, async () => { - await bootstrapApp(); - }); + await renderAuthView( + root, + state.bootstrapped, + state.safeMode, + state.authRequirements, + async () => { + await bootstrapApp(); + }, + ); return; } @@ -210,6 +221,8 @@ async function syncStatusAndRender(): Promise { isPanicLocked?: boolean; defaultMobileSafeMode: boolean; theme: string; + security?: ClientSecuritySettings; + authRequirements?: ClientAuthRequirements; }>('/api/auth/status'); state.bootstrapped = status.bootstrapped; @@ -218,6 +231,8 @@ async function syncStatusAndRender(): Promise { state.isPanicLocked = Boolean(status.isPanicLocked); state.defaultMobileSafeMode = status.defaultMobileSafeMode; state.elevatedUntil = status.elevatedUntil ?? null; + state.security = status.security; + state.authRequirements = status.authRequirements; if (!localStorage.getItem(THEME_STORAGE_KEY)) { state.theme = status.theme; @@ -255,10 +270,13 @@ document.addEventListener('DOMContentLoaded', () => { applyTheme(state.theme); registerStepUpHandler(() => - promptStepUp((until) => { - state.elevatedUntil = until; - updateTopBarUi(); - }), + promptStepUp( + () => state.authRequirements, + (until) => { + state.elevatedUntil = until; + updateTopBarUi(); + }, + ), ); registerUnauthorizedHandler(() => { handleLocalSessionReset(false); diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index 9167c94..bd00c44 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -70,6 +70,29 @@ export interface ServerEntry { } | null; } +export interface ClientSecuritySettings { + requireTotpOnLogin: boolean; + passwordMode: 'any' | 'all'; + totpMode: 'any' | 'all'; + stepUpPolicy: 'off' | 'every-action' | '5m' | '1h' | '24h' | 'session'; + stepUpMethod: 'totp' | 'password' | 'both'; + elevateOnLogin: boolean; + keepElevationOnSafeMode: boolean; + enableEmergencySecretsBackup: boolean; +} + +export interface ClientAuthRequirements { + requireTotpOnLogin: boolean; + passwordMode: 'any' | 'all'; + passwordCount: number; + passwordLabels: Array<{ id: string; label: string }>; + totpMode: 'any' | 'all'; + totpCount: number; + totpLabels: Array<{ id: string; label: string }>; + stepUpPolicy: ClientSecuritySettings['stepUpPolicy']; + stepUpMethod: ClientSecuritySettings['stepUpMethod']; +} + export interface ClientState { bootstrapped: boolean; authenticated: boolean; @@ -82,6 +105,8 @@ export interface ClientState { route: RouteId; selectedServerId?: string; overview: ConfigOverview | null; + security?: ClientSecuritySettings; + authRequirements?: ClientAuthRequirements; } export const SAFE_MODE_STORAGE_KEY = 'gcoord_device_safe_mode'; diff --git a/src/client/ts/views/auth-view.ts b/src/client/ts/views/auth-view.ts index bbcb196..3c45823 100644 --- a/src/client/ts/views/auth-view.ts +++ b/src/client/ts/views/auth-view.ts @@ -1,5 +1,9 @@ import { apiFetch, setCsrfToken } from '../api.js'; -import { el, extractErrorMessage } from '../state.js'; +import { + el, + extractErrorMessage, + type ClientAuthRequirements, +} from '../state.js'; interface BootstrapData { secretBase32: string; @@ -11,6 +15,7 @@ export async function renderAuthView( root: HTMLElement, bootstrapped: boolean, initialSafeMode: boolean, + authRequirements: ClientAuthRequirements | undefined, onAuthenticated: () => Promise, ): Promise { root.replaceChildren(); @@ -22,7 +27,7 @@ export async function renderAuthView( el( 'p', { class: 'muted' }, - 'Create the single admin password and enroll TOTP 2FA. No third-party identity service is used.', + 'Create the admin password and enroll TOTP 2FA. You can adjust re-auth strictness and add multiple passwords/TOTPs in Settings anytime.', ), ); @@ -59,6 +64,14 @@ export async function renderAuthView( showPassBtn.textContent = showing ? 'Show' : 'Hide'; }); + const presetSelect = el( + 'select', + { id: 'boot-preset', name: 'securityPreset' }, + el('option', { value: 'balanced', selected: true }, 'Balanced — TOTP login + 1h re-auth window (Default)'), + el('option', { value: 'relaxed' }, 'Relaxed (Phone Friendly) — Password-only login, no re-auth prompts'), + el('option', { value: 'strict' }, 'Strict — TOTP on login + 5m re-auth window, dropped in Safe Mode'), + ); + const codeInput = el('input', { id: 'boot-totp', name: 'totpCode', @@ -96,6 +109,8 @@ export async function renderAuthView( userInput, el('label', { for: 'boot-password' }, 'Master Login Password (>= 10 chars)'), el('div', { class: 'row' }, el('div', { style: 'flex:1' }, passInput), showPassBtn), + el('label', { for: 'boot-preset' }, 'Auth Strictness Preset'), + presetSelect, el('div', { class: 'stack' }, el('label', {}, 'Scan TOTP QR Code'), qrContainer, secretLine), el('label', { for: 'boot-totp' }, 'Verify 6-Digit TOTP Code'), codeInput, @@ -119,17 +134,17 @@ export async function renderAuthView( totpCode: codeInput.value.trim(), secretBase32, initialSafeMode, + securityPreset: presetSelect.value, }, }); setCsrfToken(res.csrfToken); - // One-time recovery codes step wrap.replaceChildren( el('h1', {}, 'Save Single-Use Recovery Codes'), el( 'p', { class: 'warn-text' }, - 'Each recovery code works once if you lose your TOTP device. These will NOT be shown again.', + 'Each recovery code works once if you lose your TOTP device. A chmod 0600 emergency backup is also stored in data/recovery/emergency-secrets.json.', ), el( 'div', @@ -177,10 +192,23 @@ export async function renderAuthView( return; } - // Standard Sign-In Form + // Standard Sign-In Form respecting dynamic passwordMode / totpMode / requireTotpOnLogin + const reqs = authRequirements; + const requireTotp = reqs ? reqs.requireTotpOnLogin : true; + const pwMode = reqs?.passwordMode ?? 'any'; + const totpMode = reqs?.totpMode ?? 'any'; + const pwLabels = reqs?.passwordLabels ?? [{ id: 'pw-primary', label: 'Password' }]; + const totpLabels = reqs?.totpLabels ?? [{ id: 'totp-primary', label: 'Authenticator' }]; + wrap.append( el('h1', {}, 'GCoordinator — Admin Sign In'), - el('p', { class: 'muted' }, 'Authenticate with password and TOTP 2FA (or a recovery code).'), + el( + 'p', + { class: 'muted' }, + requireTotp + ? 'Authenticate with password and TOTP 2FA (or a recovery code).' + : 'TOTP login requirement is disabled in Security Settings — password sign-in only.', + ), ); const form = el('form', { class: 'stack' }); @@ -195,44 +223,62 @@ export async function renderAuthView( autocorrect: 'off', required: true, }); - const passInput = el('input', { - id: 'login-password', - name: 'password', - type: 'password', - autocomplete: 'current-password', - enterkeyhint: 'next', - required: true, - }); - const showPassBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Show'); - showPassBtn.addEventListener('click', () => { - const showing = passInput.type === 'text'; - passInput.type = showing ? 'password' : 'text'; - showPassBtn.textContent = showing ? 'Show' : 'Hide'; - }); - const codeInput = el('input', { - id: 'login-code', - name: 'code', - type: 'text', - autocomplete: 'one-time-code', - inputmode: 'numeric', - enterkeyhint: 'done', - placeholder: '6-digit TOTP or XXXXX-XXXXX recovery code', - required: true, - }); + form.append(el('label', { for: 'login-username' }, 'Username'), userInput); + + const passwordInputs: HTMLInputElement[] = []; + const pwCount = pwMode === 'all' ? Math.max(1, pwLabels.length) : 1; + for (let i = 0; i < pwCount; i++) { + const labelText = + pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password'; + const inp = el('input', { + id: `login-password-${i}`, + name: `password-${i}`, + type: 'password', + autocomplete: 'current-password', + enterkeyhint: requireTotp || i < pwCount - 1 ? 'next' : 'done', + required: true, + }); + const showBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Show'); + showBtn.addEventListener('click', () => { + const showing = inp.type === 'text'; + inp.type = showing ? 'password' : 'text'; + showBtn.textContent = showing ? 'Show' : 'Hide'; + }); + passwordInputs.push(inp); + form.append( + el('label', { for: `login-password-${i}` }, labelText), + el('div', { class: 'row' }, el('div', { style: 'flex:1' }, inp), showBtn), + ); + } + + const codeInputs: HTMLInputElement[] = []; + if (requireTotp) { + const totpCount = totpMode === 'all' ? Math.max(1, totpLabels.length) : 1; + for (let i = 0; i < totpCount; i++) { + const labelText = + totpMode === 'all' + ? `TOTP Code — ${totpLabels[i]?.label ?? `#${i + 1}`}` + : 'TOTP 2FA / Recovery Code'; + const inp = el('input', { + id: `login-code-${i}`, + name: `code-${i}`, + type: 'text', + autocomplete: 'one-time-code', + inputmode: 'numeric', + enterkeyhint: i < totpCount - 1 ? 'next' : 'done', + placeholder: + totpMode === 'all' ? '6-digit TOTP' : '6-digit TOTP or XXXXX-XXXXX recovery code', + required: true, + }); + codeInputs.push(inp); + form.append(el('label', { for: `login-code-${i}` }, labelText), inp); + } + } + const statusMsg = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' }); const submitBtn = el('button', { type: 'submit', class: 'btn btn-primary' }, 'Sign In'); - - form.append( - el('label', { for: 'login-username' }, 'Username'), - userInput, - el('label', { for: 'login-password' }, 'Password'), - el('div', { class: 'row' }, el('div', { style: 'flex:1' }, passInput), showPassBtn), - el('label', { for: 'login-code' }, 'TOTP 2FA / Recovery Code'), - codeInput, - statusMsg, - submitBtn, - ); + form.append(statusMsg, submitBtn); form.addEventListener('submit', async (ev) => { ev.preventDefault(); @@ -243,8 +289,8 @@ export async function renderAuthView( method: 'POST', body: { username: userInput.value.trim(), - password: passInput.value, - code: codeInput.value.trim(), + passwords: passwordInputs.map((p) => p.value), + codes: codeInputs.map((c) => c.value.trim()), initialSafeMode, }, }); diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index be7d7a0..cd06a24 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -1,6 +1,12 @@ import { apiFetch } from '../api.js'; import { confirmDialog, promptStepUp } from '../dialogs.js'; -import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; +import { + el, + extractErrorMessage, + fmtTime, + type ClientSecuritySettings, + type ClientState, +} from '../state.js'; interface SessionRow { idPrefix: string; @@ -22,6 +28,22 @@ interface AuditRow { details: string | null; } +interface FactorsData { + passwords: Array<{ id: string; label: string; createdAt: number }>; + totps: Array<{ id: string; label: string; createdAt: number }>; + unusedRecoveryCodes: number; + security: ClientSecuritySettings; + recoveryBackup: { + enabled: boolean; + exists: boolean; + filePath: string; + updatedAt?: string; + snapshotCount: number; + hasMasterKey: boolean; + credentialCount: number; + }; +} + export async function renderSettingsView( root: HTMLElement, state: ClientState, @@ -30,26 +52,26 @@ export async function renderSettingsView( ): Promise { root.replaceChildren(); - const [sessRes, auditRes] = await Promise.all([ + const [sessRes, auditRes, factorsRes] = await Promise.all([ apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'), apiFetch<{ total: number; items: AuditRow[] }>('/api/audit?limit=40'), + apiFetch('/api/auth/factors'), ]); - // Preferences & Step-Up Elevation panel + const sec = factorsRes.security; + state.security = sec; + + // 1. Theme & Manual Elevation Row const topGrid = el('div', { class: 'grid-2' }); const prefPanel = el('section', { class: 'panel' }); - prefPanel.append(el('h1', {}, 'Appearance & Mobile Safety')); + prefPanel.append(el('h1', {}, 'Appearance & Theme')); const themeSelect = el( 'select', {}, ...['phosphor-green', 'amber-term', 'nord-dark', 'gruvbox-dark', 'paper-light'].map( (t) => - el( - 'option', - { value: t, selected: state.theme === t ? true : undefined }, - t, - ), + el('option', { value: t, selected: state.theme === t ? true : undefined }, t), ), ); themeSelect.addEventListener('change', () => onThemeChange(themeSelect.value)); @@ -90,26 +112,31 @@ export async function renderSettingsView( ); const mfaPanel = el('section', { class: 'panel' }); - mfaPanel.append(el('h1', {}, 'Step-Up 2FA Elevation')); + mfaPanel.append(el('h1', {}, 'Current Session Elevation')); const isElevated = state.elevatedUntil !== null && state.elevatedUntil > Date.now(); mfaPanel.append( el( 'p', { class: isElevated ? 'ok-text' : 'muted' }, - isElevated - ? `Elevated until ${fmtTime(state.elevatedUntil)}` - : 'Not currently elevated. Sensitive vault actions require a 5-minute step-up TOTP check.', + sec.stepUpPolicy === 'off' + ? 'Step-Up verification is currently OFF (no re-auth prompts).' + : isElevated + ? `Elevated until ${fmtTime(state.elevatedUntil)}` + : `Not elevated (policy=${sec.stepUpPolicy}, method=${sec.stepUpMethod}).`, ), ); const stepBtn = el( 'button', { type: 'button', class: 'btn btn-sm mutating-action' }, - 'Elevate Session (5 min)', + 'Verify / Elevate Now', ); stepBtn.addEventListener('click', async () => { - const ok = await promptStepUp((until) => { - state.elevatedUntil = until; - }); + const ok = await promptStepUp( + () => state.authRequirements, + (until) => { + state.elevatedUntil = until; + }, + ); if (ok) await onReloadState(); }); const dropBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Drop Elevation'); @@ -122,7 +149,403 @@ export async function renderSettingsView( topGrid.append(prefPanel, mfaPanel); root.append(topGrid); - // Active Sessions + // 2. Auth Strictness & Step-Up Policy Panel + const policyPanel = el('section', { class: 'panel panel-region' }); + policyPanel.append( + el('h1', {}, 'Authentication Strictness & Re-Auth Policy'), + el( + 'p', + { class: 'muted' }, + 'Tune how often you re-authenticate on mobile vs desktop, and choose ANY vs ALL matching for multiple passwords or TOTPs.', + ), + ); + + const reqTotpChk = el('input', { + type: 'checkbox', + checked: sec.requireTotpOnLogin ? true : undefined, + }); + const elevateLoginChk = el('input', { + type: 'checkbox', + checked: sec.elevateOnLogin ? true : undefined, + }); + const keepSafeChk = el('input', { + type: 'checkbox', + checked: sec.keepElevationOnSafeMode ? true : undefined, + }); + const backupChk = el('input', { + type: 'checkbox', + checked: sec.enableEmergencySecretsBackup ? true : undefined, + }); + + const pwModeSel = el( + 'select', + {}, + el('option', { value: 'any', selected: sec.passwordMode === 'any' ? true : undefined }, 'ANY (any enrolled password works)'), + el('option', { value: 'all', selected: sec.passwordMode === 'all' ? true : undefined }, 'ALL (must enter every enrolled password)'), + ); + const totpModeSel = el( + 'select', + {}, + el('option', { value: 'any', selected: sec.totpMode === 'any' ? true : undefined }, 'ANY (any enrolled TOTP works)'), + el('option', { value: 'all', selected: sec.totpMode === 'all' ? true : undefined }, 'ALL (must enter every enrolled TOTP)'), + ); + const policySel = el( + 'select', + {}, + el('option', { value: 'off', selected: sec.stepUpPolicy === 'off' ? true : undefined }, 'Off (never re-prompt)'), + el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session (7d)'), + el('option', { value: '24h', selected: sec.stepUpPolicy === '24h' ? true : undefined }, '24 hours'), + el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour (default)'), + el('option', { value: '5m', selected: sec.stepUpPolicy === '5m' ? true : undefined }, '5 minutes'), + el('option', { value: 'every-action', selected: sec.stepUpPolicy === 'every-action' ? true : undefined }, 'Every sensitive action'), + ); + const methodSel = el( + 'select', + {}, + el('option', { value: 'totp', selected: sec.stepUpMethod === 'totp' ? true : undefined }, 'TOTP Authenticator'), + el('option', { value: 'password', selected: sec.stepUpMethod === 'password' ? true : undefined }, 'Password only (no app switching on phone)'), + el('option', { value: 'both', selected: sec.stepUpMethod === 'both' ? true : undefined }, 'Password + TOTP'), + ); + + const applyPreset = (preset: 'relaxed' | 'balanced' | 'strict' | 'paranoid') => { + if (preset === 'relaxed') { + reqTotpChk.checked = false; + pwModeSel.value = 'any'; + totpModeSel.value = 'any'; + policySel.value = 'off'; + methodSel.value = 'password'; + elevateLoginChk.checked = true; + keepSafeChk.checked = true; + } else if (preset === 'balanced') { + reqTotpChk.checked = true; + pwModeSel.value = 'any'; + totpModeSel.value = 'any'; + policySel.value = '1h'; + methodSel.value = 'totp'; + elevateLoginChk.checked = true; + keepSafeChk.checked = true; + } else if (preset === 'strict') { + reqTotpChk.checked = true; + pwModeSel.value = 'any'; + totpModeSel.value = 'any'; + policySel.value = '5m'; + methodSel.value = 'totp'; + elevateLoginChk.checked = false; + keepSafeChk.checked = false; + } else { + reqTotpChk.checked = true; + pwModeSel.value = 'all'; + totpModeSel.value = 'all'; + policySel.value = 'every-action'; + methodSel.value = 'both'; + elevateLoginChk.checked = false; + keepSafeChk.checked = false; + } + }; + + const presetBar = el( + 'div', + { class: 'row', style: 'margin-bottom:8px' }, + el('span', { class: 'muted' }, 'Quick Presets:'), + ...(['relaxed', 'balanced', 'strict', 'paranoid'] as const).map((p) => { + const b = el('button', { type: 'button', class: 'btn btn-sm' }, p); + b.addEventListener('click', () => applyPreset(p)); + return b; + }), + ); + + const policyMsg = el('p', { class: 'form-msg' }); + const savePolicyBtn = el( + 'button', + { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, + 'Save Security Policy', + ); + savePolicyBtn.addEventListener('click', async () => { + policyMsg.textContent = ''; + try { + const nextSecurity: ClientSecuritySettings = { + requireTotpOnLogin: reqTotpChk.checked, + passwordMode: pwModeSel.value as 'any' | 'all', + totpMode: totpModeSel.value as 'any' | 'all', + stepUpPolicy: policySel.value as ClientSecuritySettings['stepUpPolicy'], + stepUpMethod: methodSel.value as ClientSecuritySettings['stepUpMethod'], + elevateOnLogin: elevateLoginChk.checked, + keepElevationOnSafeMode: keepSafeChk.checked, + enableEmergencySecretsBackup: backupChk.checked, + }; + const nextSettings = { + ...(state.overview?.settings ?? {}), + security: nextSecurity, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: 'Update auth strictness & recovery policy', + }, + }); + await onReloadState(); + } catch (err) { + policyMsg.className = 'form-msg err-text'; + policyMsg.textContent = extractErrorMessage(err); + } + }); + + policyPanel.append( + presetBar, + el( + 'div', + { class: 'grid-2' }, + el('div', {}, el('label', {}, 'Password Matching Mode'), pwModeSel), + el('div', {}, el('label', {}, 'TOTP Matching Mode'), totpModeSel), + el('div', {}, el('label', {}, 'Step-Up Re-Auth Window'), policySel), + el('div', {}, el('label', {}, 'Step-Up Method'), methodSel), + ), + el( + 'div', + { class: 'stack', style: 'margin-top:8px' }, + el('label', { class: 'chk-row' }, reqTotpChk, 'Require TOTP code during Login'), + el('label', { class: 'chk-row' }, elevateLoginChk, 'Auto-elevate session on Login (skips immediate Step-Up)'), + el('label', { class: 'chk-row' }, keepSafeChk, 'Keep Step-Up elevation when toggling Safe Mode ON'), + el('label', { class: 'chk-row' }, backupChk, 'Maintain automatic chmod 0600 secrets backup in data/recovery/'), + ), + el('div', { class: 'row', style: 'margin-top:8px' }, savePolicyBtn), + policyMsg, + ); + root.append(policyPanel); + + // 3. Multi-Password & Multi-TOTP Factor Management + const factorsGrid = el('div', { class: 'grid-2' }); + + const pwPanel = el('section', { class: 'panel panel-region' }); + pwPanel.append(el('h2', {}, `Admin Passwords (${factorsRes.passwords.length})`)); + const pwList = el('div', { class: 'stack' }); + for (const pw of factorsRes.passwords) { + const rmBtn = el( + 'button', + { + type: 'button', + class: 'btn btn-sm btn-danger mutating-action', + disabled: factorsRes.passwords.length <= 1 ? true : undefined, + }, + 'Remove', + ); + rmBtn.addEventListener('click', async () => { + const ok = await confirmDialog('dialog-confirm', `Remove password "${pw.label}"?`); + if (!ok) return; + await apiFetch(`/api/auth/factors/passwords/${encodeURIComponent(pw.id)}`, { + method: 'DELETE', + }); + await onReloadState(); + }); + pwList.append( + el( + 'div', + { class: 'row-between' }, + el('span', { class: 'mono' }, `${pw.label} (${pw.id})`), + rmBtn, + ), + ); + } + const addPwLabel = el('input', { placeholder: 'Label (e.g. Phone Quick / Backup)', required: true }); + const addPwSecret = el('input', { type: 'password', minlength: 8, placeholder: 'Password (>= 8 chars)', required: true }); + const pwMsg = el('p', { class: 'form-msg' }); + const addPwForm = el( + 'form', + { class: 'stack', style: 'margin-top:8px' }, + addPwLabel, + addPwSecret, + pwMsg, + el('button', { type: 'submit', class: 'btn btn-sm btn-primary mutating-action' }, '+ Add Password'), + ); + addPwForm.addEventListener('submit', async (ev) => { + ev.preventDefault(); + pwMsg.textContent = ''; + try { + await apiFetch('/api/auth/factors/passwords', { + method: 'POST', + body: { label: addPwLabel.value.trim(), password: addPwSecret.value }, + }); + await onReloadState(); + } catch (err) { + pwMsg.className = 'form-msg err-text'; + pwMsg.textContent = extractErrorMessage(err); + } + }); + pwPanel.append(pwList, addPwForm); + + const totpPanel = el('section', { class: 'panel panel-region' }); + totpPanel.append( + el('h2', {}, `TOTP Authenticators (${factorsRes.totps.length}) | Unused Recovery Codes: ${factorsRes.unusedRecoveryCodes}`), + ); + const totpList = el('div', { class: 'stack' }); + for (const t of factorsRes.totps) { + const rmBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Remove', + ); + rmBtn.addEventListener('click', async () => { + const ok = await confirmDialog('dialog-confirm', `Remove TOTP authenticator "${t.label}"?`); + if (!ok) return; + try { + await apiFetch(`/api/auth/factors/totps/${encodeURIComponent(t.id)}`, { + method: 'DELETE', + }); + await onReloadState(); + } catch (err) { + totpMsg.className = 'form-msg err-text'; + totpMsg.textContent = extractErrorMessage(err); + } + }); + totpList.append( + el( + 'div', + { class: 'row-between' }, + el('span', { class: 'mono' }, `${t.label} (${t.id})`), + rmBtn, + ), + ); + } + const newTotpLabel = el('input', { placeholder: 'Authenticator label (e.g. Backup YubiKey)' }); + const enrollBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Enroll Additional TOTP'); + const enrollArea = el('div', { class: 'stack' }); + const totpMsg = el('p', { class: 'form-msg' }); + + enrollBtn.addEventListener('click', async () => { + totpMsg.textContent = ''; + const label = newTotpLabel.value.trim() || `Authenticator #${factorsRes.totps.length + 1}`; + try { + const res = await apiFetch<{ + enrollmentId: string; + secretBase32: string; + qrSvg: string; + }>('/api/auth/factors/totps/enroll', { + method: 'POST', + body: { label }, + }); + const qrBox = el('div', { class: 'qr-box' }); + const doc = new DOMParser().parseFromString(res.qrSvg, 'image/svg+xml'); + if (doc.documentElement.nodeName === 'svg') { + qrBox.append(document.importNode(doc.documentElement, true)); + } + const codeInp = el('input', { + placeholder: '6-digit verification code', + inputmode: 'numeric', + maxlength: 6, + }); + const confirmBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Confirm TOTP'); + confirmBtn.addEventListener('click', async () => { + try { + await apiFetch('/api/auth/factors/totps/confirm', { + method: 'POST', + body: { enrollmentId: res.enrollmentId, code: codeInp.value.trim() }, + }); + await onReloadState(); + } catch (err) { + totpMsg.className = 'form-msg err-text'; + totpMsg.textContent = extractErrorMessage(err); + } + }); + enrollArea.replaceChildren( + qrBox, + el('div', { class: 'mono warn-text' }, `Secret: ${res.secretBase32}`), + codeInp, + confirmBtn, + ); + } catch (err) { + totpMsg.className = 'form-msg err-text'; + totpMsg.textContent = extractErrorMessage(err); + } + }); + + const regenCodesBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Regenerate 8 Recovery Codes'); + const regenBox = el('div', { class: 'stack' }); + regenCodesBtn.addEventListener('click', async () => { + try { + const res = await apiFetch<{ recoveryCodes: string[] }>('/api/auth/factors/recovery-codes', { + method: 'POST', + }); + regenBox.replaceChildren( + el('div', { class: 'code-grid' }, ...res.recoveryCodes.map((c) => el('div', { class: 'code-chip mono' }, c))), + ); + } catch (err) { + totpMsg.className = 'form-msg err-text'; + totpMsg.textContent = extractErrorMessage(err); + } + }); + + totpPanel.append( + totpList, + el('div', { class: 'row', style: 'margin-top:8px' }, el('div', { style: 'flex:1' }, newTotpLabel), enrollBtn), + enrollArea, + el('div', { class: 'row', style: 'margin-top:8px' }, regenCodesBtn), + regenBox, + totpMsg, + ); + + factorsGrid.append(pwPanel, totpPanel); + root.append(factorsGrid); + + // 4. Local Emergency Secrets Backup Panel + const rb = factorsRes.recoveryBackup; + const backupPanel = el('section', { class: 'panel panel-region' }); + backupPanel.append( + el('h2', {}, `Local Emergency Secrets Backup (${rb.enabled ? 'ENABLED' : 'DISABLED'})`), + el( + 'p', + { class: 'muted mono' }, + `Path: ${rb.filePath} (chmod 0600) | Exists: ${rb.exists ? 'YES' : 'NO'} | MasterKeySaved: ${rb.hasMasterKey ? 'YES' : 'NO'} | VaultCreds: ${rb.credentialCount} | Snapshots: ${rb.snapshotCount}`, + ), + ); + const bMsg = el('p', { class: 'form-msg' }); + const syncBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Sync Backup Now'); + syncBtn.addEventListener('click', async () => { + bMsg.textContent = ''; + try { + await apiFetch('/api/auth/recovery-backup/sync', { method: 'POST' }); + await onReloadState(); + } catch (err) { + bMsg.className = 'form-msg err-text'; + bMsg.textContent = extractErrorMessage(err); + } + }); + + const dlBackupBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Download Emergency Backup JSON'); + dlBackupBtn.addEventListener('click', async () => { + bMsg.textContent = ''; + try { + const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export'); + const blob = new Blob([`${JSON.stringify(res.bundle, null, 2)}\n`], { + type: 'application/json', + }); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = 'gcoordinator-emergency-secrets.json'; + a.click(); + URL.revokeObjectURL(a.href); + } catch (err) { + bMsg.className = 'form-msg err-text'; + bMsg.textContent = extractErrorMessage(err); + } + }); + + const wipeBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Wipe & Disable Local Backup'); + wipeBtn.addEventListener('click', async () => { + const ok = await confirmDialog( + 'dialog-confirm', + 'Shred and delete data/recovery/emergency-secrets.json and snapshots, and disable automatic local backup?', + ); + if (!ok) return; + await apiFetch('/api/auth/recovery-backup?disable=1', { method: 'DELETE' }); + await onReloadState(); + }); + + backupPanel.append(el('div', { class: 'row' }, syncBtn, dlBackupBtn, wipeBtn), bMsg); + root.append(backupPanel); + + // 5. Active Sessions const sessPanel = el('section', { class: 'panel panel-region' }); const revokeOthersBtn = el( 'button', @@ -200,7 +623,7 @@ export async function renderSettingsView( sessPanel.append(el('div', { class: 'table-wrap' }, sTable)); root.append(sessPanel); - // Audit Log + // 6. Audit Log const auditPanel = el('section', { class: 'panel panel-region' }); auditPanel.append(el('h2', {}, `Security & Action Audit Log (${auditRes.total} entries)`)); const aTable = el('table'); diff --git a/src/client/ts/views/vault-view.ts b/src/client/ts/views/vault-view.ts index 81b57b7..25b2d26 100644 --- a/src/client/ts/views/vault-view.ts +++ b/src/client/ts/views/vault-view.ts @@ -70,7 +70,9 @@ export async function renderVaultView( el( 'p', { class: 'warn-text' }, - 'Copy this 64-hex key to your password manager or Docker secret. Without it, vault.enc cannot be unlocked after a restart or Panic Lock.', + state.security?.enableEmergencySecretsBackup !== false + ? 'A readable chmod 0600 local backup has been saved automatically in data/recovery/emergency-secrets.json. You should still keep an offsite copy in your password manager.' + : 'Copy this 64-hex key to your password manager or Docker secret. Without it, vault.enc cannot be unlocked after a restart or Panic Lock.', ), el('pre', { class: 'mono' }, res.generatedKeyHex), );