Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: bind password-risk consent to each browser
[._.]/ Adam Eivyf75d6a88dd14
diff --git a/PRD.md b/PRD.mdindex eadd36294d..8dd82b272e 100644--- a/PRD.md+++ b/PRD.md@@ -178,7 +178,7 @@ PortOS is a high-stakes control surface for the host computer. Its APIs, terminaPortOS MUST remain on the user's private network. Publishing its administration UI, APIs, sockets, sidecars, or execution controls through Cloudflare tunnels/DNS gateways, Tailscale Funnel, ngrok, reverse proxies, router forwarding, or equivalent public relays is prohibited. TLS, a password, or an opt-in feature switch does not make public deployment supported. Separately managed applications can be public under their own security models without exposing PortOS.-A private network is necessary but does not make every connected machine trustworthy. A compromised LAN or tailnet peer can abuse reachable password-free APIs to control the host. PortOS MUST strongly encourage a unique password while retaining opt-in authentication. On the first visit after upgrading, every password-free instance MUST show an explanation and offer password setup or explicit risk acceptance and dismissal. The acknowledgement MUST persist only on that install, survive restart, and reset when a password is set and later removed. Failed status reads or writes MUST NOT dismiss the warning. This warning is informed consent, not a substitute for authentication or network isolation.+A private network is necessary but does not make every connected machine trustworthy. A compromised LAN or tailnet peer can abuse reachable password-free APIs to control the host. PortOS MUST strongly encourage a unique password while retaining opt-in authentication. On the first visit after upgrading, every password-free instance MUST show an explanation and offer password setup or explicit risk acceptance and dismissal. Acknowledgement MUST be specific to the browser and instance origin, survive browser restart, and reset when a password is set and later removed. A reachable network peer MUST NOT be able to dismiss another browser’s warning through an unauthenticated API. Failed status reads or writes MUST NOT dismiss the warning. This warning is informed consent, not a substitute for authentication or network isolation.CoS MUST assess the actual behavior proposed by external GitHub issues, comments, and PRs against this model, separately from prompt-injection screening. Benign wording, green CI, labels, and claimed contributor approval MUST NOT authorize a conflicting feature. Programmatic screening MUST withhold actions when the security assessment is missing, malformed, unavailable, or uncertain; pending PR approvals MUST be reassessed before further action. Autonomous claim instructions MUST enforce the same eligibility rule. Private federation between the user's own machines remains supported through configured peer/category permissions; network reachability alone never grants command-execution authority.diff --git a/client/src/components/PasswordRiskWarning.jsx b/client/src/components/PasswordRiskWarning.jsxindex 133f067a92..f8e21cf7a1 100644--- a/client/src/components/PasswordRiskWarning.jsx+++ b/client/src/components/PasswordRiskWarning.jsx@@ -1,27 +1,36 @@import { useCallback, useEffect, useRef, useState } from 'react';import { Link, useLocation } from 'react-router';-import { getPasswordRiskStatus, acknowledgePasswordRisk } from '../services/apiAuth.js';+import { getPasswordRiskStatus } from '../services/apiAuth.js';+import { safeReadStorage, safeWriteStorage, safeRemoveStorage } from '../lib/safeStorage.js';import Modal from './ui/Modal.jsx';+const ACKNOWLEDGEMENT_KEY = 'portos-password-risk-v1';+export default function PasswordRiskWarning() {const { pathname } = useLocation();const [status, setStatus] = useState(null);const [error, setError] = useState('');const [accepted, setAccepted] = useState(false);- const [saving, setSaving] = useState(false);+ const [acknowledgedRevision, setAcknowledgedRevision] = useState(null);const generation = useRef(0);const load = useCallback(() => {const current = ++generation.current;getPasswordRiskStatus({ silent: true }).then((value) => {if (current !== generation.current) return;- if (typeof value?.enabled !== 'boolean' || typeof value?.acknowledgementRequired !== 'boolean') {+ if (typeof value?.enabled !== 'boolean' || typeof value?.revision !== 'string' || !value.revision) {+ setStatus(null);setError('PortOS could not confirm password protection. Check Security settings or retry.');return;}+ if (value.enabled) safeRemoveStorage(ACKNOWLEDGEMENT_KEY);+ setAcknowledgedRevision(value.enabled ? null : safeReadStorage(ACKNOWLEDGEMENT_KEY));+ setAccepted(false);setStatus(value);setError('');}).catch(() => {- if (current === generation.current) setError('PortOS could not confirm password protection. Check Security settings or retry.');+ if (current !== generation.current) return;+ setStatus(null);+ setError('PortOS could not confirm password protection. Check Security settings or retry.');});}, []);@@ -36,17 +45,14 @@ export default function PasswordRiskWarning() {};}, [load, pathname]);- const acknowledge = async () => {- if (!accepted || saving) return;- setSaving(true);- const result = await acknowledgePasswordRisk({ silent: true }).catch(() => null);- setSaving(false);- if (result?.acknowledgementRequired !== false || typeof result?.enabled !== 'boolean') {- setError('Risk acceptance could not be saved. Try again or set a password.');+ const acknowledge = () => {+ if (!accepted || status?.enabled !== false) return;+ safeWriteStorage(ACKNOWLEDGEMENT_KEY, status.revision);+ if (safeReadStorage(ACKNOWLEDGEMENT_KEY) !== status.revision) {+ setError('Risk acceptance could not be saved in this browser. Try again or set a password.');return;}- generation.current += 1;- setStatus(result);+ setAcknowledgedRevision(status.revision);setError('');setAccepted(false);};@@ -54,7 +60,7 @@ export default function PasswordRiskWarning() {// Leave the password form usable without silently acknowledging the risk.// Leaving this route rechecks server state; a failed/cancelled setup warns again.if (pathname === '/settings/security') return null;- const required = status?.acknowledgementRequired === true;+ const required = status?.enabled === false && acknowledgedRevision !== status.revision;if (!required && !error) return null;return (<Modal open closeOnEsc={false} closeOnBackdrop={false} usePortal ariaLabelledBy="password-risk-title"@@ -64,19 +70,20 @@ export default function PasswordRiskWarning() {</h2><p>PortOS can run commands and read or change files on this computer. Without a password, any device that can reach its APIs may gain that access, including a compromised machine on your LAN or Tailscale network.</p><p>Set a strong, unique PortOS password to reduce this risk. Keep PortOS on your private network: a password does not make public internet exposure through Cloudflare tunnels, gateways, or port forwarding safe.</p>+ <p>Risk acceptance applies only to this browser. Other browsers will ask separately.</p>{error && <p role="alert" className="text-port-error">{error}</p>}{required && <label htmlFor="password-risk-accept" className="flex items-start gap-3">- <input id="password-risk-accept" type="checkbox" checked={accepted} disabled={saving}+ <input id="password-risk-accept" type="checkbox" checked={accepted}onChange={(event) => setAccepted(event.target.checked)} className="mt-1" /><span>I understand and accept the risk of other reachable devices accessing this host without a PortOS password.</span></label>}<div className="flex flex-col sm:flex-row gap-3"><Link to="/settings/security" className="min-h-11 px-4 py-2 bg-port-accent text-white rounded text-center">Set a PortOS password</Link>- {required && <button type="button" disabled={!accepted || saving} onClick={acknowledge}+ {required && <button type="button" disabled={!accepted} onClick={acknowledge}className="min-h-11 px-4 py-2 border border-port-border rounded disabled:opacity-50">- {saving ? 'Saving…' : 'Accept risk and dismiss'}+ Accept risk and dismiss</button>}- {error && <button type="button" onClick={load} disabled={saving} className="min-h-11 px-4 py-2 border border-port-border rounded">Retry</button>}+ {error && <button type="button" onClick={load} className="min-h-11 px-4 py-2 border border-port-border rounded">Retry</button>}</div></Modal>);diff --git a/client/src/components/PasswordRiskWarning.test.jsx b/client/src/components/PasswordRiskWarning.test.jsxindex 9dc7ea232c..1e0825cc84 100644--- a/client/src/components/PasswordRiskWarning.test.jsx+++ b/client/src/components/PasswordRiskWarning.test.jsx@@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { Link, MemoryRouter } from 'react-router';import PasswordRiskWarning from './PasswordRiskWarning.jsx';-import { acknowledgePasswordRisk, getPasswordRiskStatus } from '../services/apiAuth.js';+import { getPasswordRiskStatus } from '../services/apiAuth.js';-vi.mock('../services/apiAuth.js', () => ({ getPasswordRiskStatus: vi.fn(), acknowledgePasswordRisk: vi.fn() }));+vi.mock('../services/apiAuth.js', () => ({ getPasswordRiskStatus: vi.fn() }));const renderWarning = () => render(<MemoryRouter><PasswordRiskWarning /><Link to="/">Home</Link></MemoryRouter>);beforeEach(() => {vi.resetAllMocks();- getPasswordRiskStatus.mockResolvedValue({ enabled: false, acknowledgementRequired: true });- acknowledgePasswordRisk.mockResolvedValue({ enabled: false, acknowledgementRequired: false });+ localStorage.clear();+ getPasswordRiskStatus.mockResolvedValue({ enabled: false, revision: 'initial' });});-afterEach(cleanup);+afterEach(() => { cleanup(); vi.restoreAllMocks(); });describe('password risk warning', () => {- it('explains host-control risk and requires explicit, successfully saved acceptance', async () => {+ it('requires explicit consent saved in this browser and survives remount', async () => {renderWarning();const dialog = await screen.findByRole('dialog');expect(dialog).toHaveTextContent('compromised machine');@@ -25,29 +25,51 @@ describe('password risk warning', () => {fireEvent.click(dialog.parentElement);expect(screen.getByRole('dialog')).toBeInTheDocument();fireEvent.click(screen.getByRole('checkbox'));- acknowledgePasswordRisk.mockRejectedValueOnce(new Error('write failed'));+ const write = vi.spyOn(window.localStorage, 'setItem').mockImplementationOnce(() => { throw new Error('storage blocked'); });fireEvent.click(dismiss);- expect(await screen.findByRole('alert')).toHaveTextContent('could not be saved');+ expect(screen.getByRole('alert')).toHaveTextContent('could not be saved in this browser');expect(screen.getByRole('dialog')).toBeInTheDocument();+ write.mockRestore();fireEvent.click(dismiss);- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());- expect(acknowledgePasswordRisk).toHaveBeenCalledWith({ silent: true });+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ cleanup();+ renderWarning();+ await waitFor(() => expect(getPasswordRiskStatus).toHaveBeenCalledTimes(2));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();++ // A different browser has its own empty storage: another browser's consent+ // (or a server-side acknowledgement field) cannot suppress this warning.+ cleanup();+ localStorage.clear();+ getPasswordRiskStatus.mockResolvedValue({ enabled: false, revision: 'initial', acknowledgementRequired: false });+ renderWarning();+ expect(await screen.findByRole('dialog')).toBeInTheDocument();+ });++ it('invalidates an offline browser acknowledgement when the password revision changes', async () => {+ renderWarning();+ fireEvent.click(await screen.findByRole('checkbox'));+ fireEvent.click(screen.getByRole('button', { name: 'Accept risk and dismiss' }));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ cleanup();+ getPasswordRiskStatus.mockResolvedValue({ enabled: false, revision: 'after-password-removal' });+ renderWarning();+ expect(await screen.findByRole('dialog')).toBeInTheDocument();});it('leaves password settings accessible but warns again if setup was abandoned', async () => {renderWarning();fireEvent.click(await screen.findByRole('link', { name: 'Set a PortOS password' }));expect(screen.queryByRole('dialog')).not.toBeInTheDocument();- expect(acknowledgePasswordRisk).not.toHaveBeenCalled();fireEvent.click(screen.getByRole('link', { name: 'Home' }));expect(await screen.findByRole('dialog')).toBeInTheDocument();- getPasswordRiskStatus.mockResolvedValue({ enabled: true, acknowledgementRequired: false });+ getPasswordRiskStatus.mockResolvedValue({ enabled: true, revision: 'password-set' });fireEvent(window, new Event('portos:auth-changed'));await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());});- it.each([{ enabled: true, acknowledgementRequired: false }, { enabled: false, acknowledgementRequired: false }])('respects the saved instance status %j', async (value) => {- getPasswordRiskStatus.mockResolvedValue(value);+ it('does not warn an instance with a password', async () => {+ getPasswordRiskStatus.mockResolvedValue({ enabled: true, revision: 'password-set' });renderWarning();await waitFor(() => expect(getPasswordRiskStatus).toHaveBeenCalled());expect(screen.queryByRole('dialog')).not.toBeInTheDocument();diff --git a/client/src/services/README.md b/client/src/services/README.mdindex b46f1c3a99..092fe3646e 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -66,7 +66,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. || `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. || `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. Also the Eidoverse world controls and its foundation ledger (`listEidoverseFoundations`, `recordEidoverseFoundation`, `packageEidoverseFoundationCandidate`, `promoteEidoverseFoundation`, `getEidoverseContributions`) — the last three answer 200 with a refusal verdict when a promote gate says no, so callers read `outcome` rather than catching. |-| `apiAuth.js` | Optional login password — status, login, set/clear password, list/revoke sessions, and instance-local password-risk acknowledgement. |+| `apiAuth.js` | Optional login password — status, login, set/clear password, list/revoke sessions, and read-only password-risk status. || `apiLoops.js` | Scheduled loops. |## Personal data / identitydiff --git a/client/src/services/apiAuth.js b/client/src/services/apiAuth.jsindex 8f6ccecfeb..cf8516bc9b 100644--- a/client/src/services/apiAuth.js+++ b/client/src/services/apiAuth.js@@ -5,11 +5,6 @@ import { request } from './apiCore.js';export const getAuthStatus = (options) => request('/auth/status', options);export const getPasswordRiskStatus = (options) => request('/auth/password-risk', options);-export const acknowledgePasswordRisk = (options) => request('/auth/password-risk', {- ...options,- method: 'POST',- body: JSON.stringify({ acceptRisk: true }),-});export const loginWithPassword = (password) => request('/auth/login', {method: 'POST',diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex a36d2fa195..5dee1149b5 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -519,4 +519,6 @@ before manually retiring history.### Password-free access acknowledgement-`passwordRiskAcknowledgement` is an optional, versioned machine-local setting in the existing file-primary `data/settings.json` store, alongside instance authentication configuration. It contains only the accepted policy version, has no record relationships or search needs, and never federates. Absence means the warning is required, so existing installs enroll on upgrade without a seed or data rewrite. Password changes clear it. Existing settings backup and serialized writes apply.+Password-risk acceptance is browser-local, stored for this origin under the versioned `portos-password-risk-v1` key. No API can acknowledge the warning for another browser. Missing or unreadable storage requires consent again; acceptance is not federated or included in instance backups. This is a browser preference, not an app-native record.++`passwordRiskRevision` is an optional, opaque machine-local setting in the existing file-primary `data/settings.json` store, alongside authentication configuration. Password changes rotate it so old browser acknowledgements become invalid even if that browser was offline. Its absence means the initial revision, enrolling existing installs without a seed or migration. Generic settings updates cannot replace it; the read-only password-risk endpoint exposes only the revision and whether password protection is enabled.diff --git a/server/routes/auth.js b/server/routes/auth.jsindex 6f6c524970..8f1e1778aa 100644--- a/server/routes/auth.js+++ b/server/routes/auth.js@@ -1,7 +1,6 @@import { Router } from 'express';import { z } from 'zod';import {- acknowledgePasswordRisk,getPasswordRiskStatus,buildClearCookie,buildSessionCookie,@@ -32,7 +31,6 @@ const setPasswordSchema = z.object({}).strict();const clearPasswordSchema = z.object({ currentPassword: z.string().min(1).max(256) }).strict();const sessionIdParamSchema = z.object({ id: z.string().min(1).max(64).regex(/^[a-f0-9]+$/) }).strict();-const passwordRiskSchema = z.object({ acceptRisk: z.literal(true) }).strict();// Whether the request reached us over HTTPS (so the cookie should carry the// Secure flag). `req.secure` reflects the actual socket; we don't trust@@ -50,11 +48,6 @@ router.get('/password-risk', asyncHandler(async (_req, res) => {res.json(await getPasswordRiskStatus());}));-router.post('/password-risk', asyncHandler(async (req, res) => {- validateRequest(passwordRiskSchema, req.body || {});- res.json(await acknowledgePasswordRisk());-}));-// GET /api/auth/whoami — confirm the current cookie/header is still valid.// Returns { authenticated: true|false, required: true|false } so the client// can disambiguate "auth off" from "auth on, you're signed in" from "auth on,diff --git a/server/routes/auth.test.js b/server/routes/auth.test.jsindex 7c32608e14..e87056bcbb 100644--- a/server/routes/auth.test.js+++ b/server/routes/auth.test.js@@ -192,25 +192,32 @@ describe('auth routes', () => {});});-describe('password-free risk acknowledgement', () => {- it('enrolls existing installs, requires explicit consent, persists across restart, and re-arms after password removal', async () => {+describe('password-free risk status', () => {+ it('enrolls existing installs without letting network callers acknowledge the warning', async () => {let app = await buildApp();- expect((await request(app).get('/api/auth/password-risk')).body).toEqual({ enabled: false, acknowledgementRequired: true });- expect((await request(app).post('/api/auth/password-risk').send({ acceptRisk: false })).status).toBe(400);- expect((await request(app).get('/api/auth/password-risk')).body.acknowledgementRequired).toBe(true);- expect((await request(app).post('/api/auth/password-risk').send({ acceptRisk: true })).body).toEqual({ enabled: false, acknowledgementRequired: false });+ const initial = { enabled: false, revision: 'initial' };+ expect((await request(app).get('/api/auth/password-risk')).body).toEqual(initial);+ expect((await request(app).post('/api/auth/password-risk').send({ acceptRisk: true })).status).toBe(404);app = await buildApp();- expect((await request(app).get('/api/auth/password-risk')).body.acknowledgementRequired).toBe(false);+ expect((await request(app).get('/api/auth/password-risk')).body).toEqual(initial);+await request(app).post('/api/auth/password').send({ newPassword: 'example-password' });- expect((await request(app).get('/api/auth/password-risk')).body).toEqual({ enabled: true, acknowledgementRequired: false });+ const protectedStatus = (await request(app).get('/api/auth/password-risk')).body;+ expect(protectedStatus).toEqual({ enabled: true, revision: expect.any(String) });+ expect(protectedStatus.revision).not.toBe(initial.revision);await request(app).delete('/api/auth/password').send({ currentPassword: 'example-password' });- expect((await request(app).get('/api/auth/password-risk')).body).toEqual({ enabled: false, acknowledgementRequired: true });+ const unprotectedStatus = (await request(app).get('/api/auth/password-risk')).body;+ expect(unprotectedStatus.enabled).toBe(false);+ expect(unprotectedStatus.revision).not.toBe(initial.revision);+ expect(unprotectedStatus.revision).not.toBe(protectedStatus.revision);+ app = await buildApp();+ expect((await request(app).get('/api/auth/password-risk')).body).toEqual(unprotectedStatus);});- it('refuses corrupt settings for status and acknowledgement without removing password state', async () => {++ it('refuses corrupt settings without removing password state', async () => {const app = await buildApp();writeFileSync(join(tempRoot, 'settings.json'), '{corrupt');expect((await request(app).get('/api/auth/password-risk')).status).toBe(503);- expect((await request(app).post('/api/auth/password-risk').send({ acceptRisk: true })).status).toBe(503);const { readFileSync } = await import('fs');expect(readFileSync(join(tempRoot, 'settings.json'), 'utf8')).toBe('{corrupt');});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 20ac0a8b04..fd15f718de 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -592,7 +592,7 @@ router.put('/', asyncHandler(async (req, res) => {// replace a map by dropping keys the incoming patch did not mention.const {secrets: _ignoredSecrets,- passwordRiskAcknowledgement: _ignoredPasswordRisk,+ passwordRiskRevision: _ignoredPasswordRiskRevision,catalogUserTypes: _ignoredTypes,subscriptionCosts: subscriptionCostsPatch,subscriptionPlanTiers: subscriptionPlanTiersPatch,diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex 8460e84874..02593cdc9e 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -1315,9 +1315,9 @@ describe('Settings routes — backup excludePaths bounds (#7241)', () => {});});-it('generic settings updates cannot acknowledge password-free host access', async () => {- store = { passwordRiskAcknowledgement: null };- const res = await request(buildApp()).put('/api/settings').send({ passwordRiskAcknowledgement: { version: 1 } });+it('generic settings updates cannot replace the password-risk revision', async () => {+ store = { passwordRiskRevision: 'current-revision' };+ const res = await request(buildApp()).put('/api/settings').send({ passwordRiskRevision: 'old-revision' });expect(res.status).toBe(200);- expect(store.passwordRiskAcknowledgement).toBeNull();+ expect(store.passwordRiskRevision).toBe('current-revision');});diff --git a/server/services/auth.js b/server/services/auth.jsindex b022ac8968..ac92525e72 100644--- a/server/services/auth.js+++ b/server/services/auth.js@@ -14,7 +14,7 @@ import {hashToken,parseCookieToken,} from '../../lib/portosAuthCore.js';-import { getSettings, readSettingsStrict, settingsEvents, updateSettings, updateSettingsWith } from './settings.js';+import { getSettings, readSettingsStrict, settingsEvents, updateSettings } from './settings.js';import { ServerError } from '../lib/errorHandler.js';// Auth gates the PortOS UI + API behind a single user-set password. PortOS is@@ -167,26 +167,15 @@ export const getAuthStatus = async () => {return { enabled };};-// Additive, machine-local settings: absence enrolls existing installs on their-// first visit after updating, without a seed or a boot-time background job.-const PASSWORD_RISK_VERSION = 1;+// The server only reports password posture. Risk acceptance lives in each+// browser, so an unauthenticated peer cannot dismiss another browser's warning.+// Password changes rotate the revision, invalidating even an offline browser's+// old acknowledgement. Absence enrolls existing installs without a migration.export const getPasswordRiskStatus = async () => {const { corrupt, settings } = await readSettingsStrict();if (corrupt) throw new ServerError('Security settings could not be read', { status: 503, code: 'AUTH_SETTINGS_UNREADABLE' });const enabled = await isAuthEnabled();- return { enabled, acknowledgementRequired: !enabled && settings.passwordRiskAcknowledgement?.version !== PASSWORD_RISK_VERSION };-};--export const acknowledgePasswordRisk = async () => {- await updateSettingsWith(async (settings) => {- // Check inside the write queue: corrupt auth settings must never be- // replaced with a password-free acknowledgement.- if ((await readSettingsStrict()).corrupt) {- throw new ServerError('Security settings could not be read', { status: 503, code: 'AUTH_SETTINGS_UNREADABLE' });- }- return { ...settings, passwordRiskAcknowledgement: settings.secrets?.auth?.enabled ? null : { version: PASSWORD_RISK_VERSION } };- }, { actor: 'user' });- return getPasswordRiskStatus();+ return { enabled, revision: settings.passwordRiskRevision || 'initial' };};// Set or replace the password. When `currentPassword` is provided we verify it@@ -220,7 +209,7 @@ export const setPassword = async ({ newPassword, currentPassword = null }) => {salt,updatedAt: new Date().toISOString(),};- await updateSettings({ secrets, passwordRiskAcknowledgement: null });+ await updateSettings({ secrets, passwordRiskRevision: randomBytes(16).toString('hex') });// Existing sessions are invalidated on password change — the user (or anyone// holding a stolen token) starts over.await revokeAllSessions();@@ -242,7 +231,7 @@ export const clearPassword = async ({ currentPassword }) => {const settings = await getSettings();const secrets = { ...(settings.secrets || {}) };delete secrets.auth;- await updateSettings({ secrets, passwordRiskAcknowledgement: null });+ await updateSettings({ secrets, passwordRiskRevision: randomBytes(16).toString('hex') });await revokeAllSessions();return { enabled: false };};