feat(client): fix square QR layout and add dynamic multi-auth, strictness presets, and backup UI

This commit is contained in:
tyuXX 2026-11-26 21:23:35 +00:00
parent 4915bce1e4
commit 90a8bf8553
8 changed files with 683 additions and 96 deletions

View file

@ -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<void>,
): Promise<void> {
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,
},
});

View file

@ -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<void> {
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<FactorsData>('/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');

View file

@ -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),
);