feat(native): client certificates for servers behind mutual TLS

A proxy in front of TREK (Cloudflare, nginx, Caddy, Traefik, HAProxy) can
let in only devices that show a client certificate. The apps could not, so
such a server was unusable from them.

- Address screen: the server check runs natively and notices when the
  server asks for a certificate. Instead of "no server answered" it says so
  and offers to add a .p12/.pfx file; a wrong password asks again, an
  expired, not yet valid or keyless file is named as such.
- The certificate is shown only to the host and port it was added for.
  iOS keeps it in the keychain (this device only), Android seals the key
  with an Android Keystore key. The file's password is never stored.
- The web view answers the server's certificate request on both platforms;
  WebSocket, service worker and API requests go through with it. The
  offline copy, watch requests and the check use it too.
- When the server stops letting the app in (certificate removed, expired
  or no longer trusted) while the page still comes from the service worker
  or the offline copy, a native check sends the app to the address screen,
  which offers to add another. A server that only asks and lets everyone
  in is left alone.
- Cloudflare-style 403 and nginx-style 400 refusals without a certificate
  lead to the same screen instead of staying up as an error page.
- Settings, Account: a Client certificate card (only with one stored)
  shows subject, issuer, server and expiry, with Replace and Remove.
- Wiki: Native-Apps "Client certificates (mTLS)" with Cloudflare, nginx,
  Caddy and Traefik setup and how to make a certificate for the app.
- The app icon on the unreachable screen is black on the light surface.
This commit is contained in:
Maurice
2026-11-09 12:03:31 +01:00
parent d3bdc6de62
commit 07448e662c
56 changed files with 2864 additions and 32 deletions
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '../../../../tests/helpers/render';
import {
removeClientCertificate,
replaceClientCertificate,
storedClientCertificate,
} from '../../../native/clientCertificate';
import { TrekShell } from '../../../native/trekShell';
import MClientCertCard from './MClientCertCard';
vi.mock('../../../native/clientCertificate', () => ({
storedClientCertificate: vi.fn(),
replaceClientCertificate: vi.fn(),
removeClientCertificate: vi.fn(),
}));
vi.mock('../../../native/trekShell', () => ({
TrekShell: { getServer: vi.fn(async () => ({ url: 'https://trek.example.com' })), reload: vi.fn(async () => {}) },
}));
const info = {
host: 'trek.example.com',
port: 443,
subject: 'Phone of the household',
issuer: 'Home CA',
notAfter: Date.UTC(2028, 10, 8),
};
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(storedClientCertificate).mockResolvedValue(info);
});
describe('MClientCertCard', () => {
it('stays away without a stored certificate', async () => {
vi.mocked(storedClientCertificate).mockResolvedValue(null);
const { container } = render(<MClientCertCard />);
await waitFor(() => expect(storedClientCertificate).toHaveBeenCalled());
expect(container).toBeEmptyDOMElement();
});
it('shows whom the certificate names, who issued it and the server it is for', async () => {
render(<MClientCertCard />);
expect(await screen.findByText('Phone of the household')).toBeInTheDocument();
expect(screen.getByText('Issued by Home CA')).toBeInTheDocument();
expect(screen.getByText('trek.example.com')).toBeInTheDocument();
});
it('replaces it for the server shown and reloads, or says why it could not', async () => {
vi.mocked(replaceClientCertificate).mockResolvedValueOnce({ result: 'failed', failure: 'expired' });
render(<MClientCertCard />);
fireEvent.click(await screen.findByRole('button', { name: 'Replace' }));
expect(await screen.findByRole('alert')).toHaveTextContent('This certificate has expired.');
expect(TrekShell.reload).not.toHaveBeenCalled();
vi.mocked(replaceClientCertificate).mockResolvedValueOnce({ result: 'imported', certificate: info });
fireEvent.click(screen.getByRole('button', { name: 'Replace' }));
await waitFor(() => expect(TrekShell.reload).toHaveBeenCalledTimes(1));
expect(replaceClientCertificate).toHaveBeenLastCalledWith(
'https://trek.example.com',
expect.objectContaining({ title: 'Certificate password' })
);
});
it('removes it only after the confirmation, then reloads', async () => {
vi.mocked(removeClientCertificate).mockResolvedValueOnce(true);
render(<MClientCertCard />);
fireEvent.click(await screen.findByRole('button', { name: 'Remove' }));
expect(removeClientCertificate).not.toHaveBeenCalled();
const buttons = await screen.findAllByRole('button', { name: 'Remove' });
fireEvent.click(buttons[buttons.length - 1]);
await waitFor(() => expect(TrekShell.reload).toHaveBeenCalledTimes(1));
expect(removeClientCertificate).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,110 @@
import { FileKey } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from '../../../i18n';
import {
removeClientCertificate,
replaceClientCertificate,
storedClientCertificate,
} from '../../../native/clientCertificate';
import { TrekShell, type ClientCertificateFailure, type ClientCertificateInfo } from '../../../native/trekShell';
import MConfirmSheet from './MConfirmSheet';
import { MSetButton, MSetCard, MSetHint, MSetRow } from './MSettingsUi';
const FAILURE_KEYS: Record<ClientCertificateFailure, string> = {
format: 'native.cert.errorFormat',
no_key: 'native.cert.errorNoKey',
expired: 'native.cert.errorExpired',
not_yet_valid: 'native.cert.errorNotYetValid',
store: 'native.cert.errorStore',
};
/**
* The client certificate the app shows to a server behind mutual TLS, inside
* the app only and only once one is stored: someone without a proxy that asks
* for one never needs to see this. Replacing or removing it reloads the server,
* so the next connection uses what is stored now.
*/
export default function MClientCertCard() {
const { t, locale } = useTranslation();
const [certificate, setCertificate] = useState<ClientCertificateInfo | null>(null);
const [confirmRemove, setConfirmRemove] = useState(false);
const [busy, setBusy] = useState(false);
const [problem, setProblem] = useState<string | null>(null);
useEffect(() => {
let live = true;
void storedClientCertificate().then((found) => {
if (live) setCertificate(found);
});
return () => {
live = false;
};
}, []);
if (!certificate) return null;
const replace = async () => {
setProblem(null);
setBusy(true);
const { url } = await TrekShell.getServer();
const outcome = await replaceClientCertificate(url ?? `https://${certificate.host}:${certificate.port}`, {
title: t('native.cert.passwordTitle'),
message: t('native.cert.passwordMessage'),
placeholder: t('native.cert.passwordPlaceholder'),
ok: t('native.cert.passwordOk'),
cancel: t('native.cert.passwordCancel'),
wrongPassword: t('native.cert.passwordWrong'),
});
setBusy(false);
if (outcome.result === 'imported') {
await TrekShell.reload();
} else if (outcome.result === 'failed') {
setProblem(t(FAILURE_KEYS[outcome.failure ?? 'format']));
}
};
const remove = async () => {
setConfirmRemove(false);
if (await removeClientCertificate()) await TrekShell.reload();
};
const validUntil = new Date(certificate.notAfter).toLocaleDateString(locale, { dateStyle: 'medium' });
return (
<MSetCard title={t('native.cert.settingTitle')} icon={FileKey} className="mt-3">
<div className="-mt-[4px]">
<MSetRow
first
label={certificate.subject}
sub={t('native.cert.settingIssuer', { issuer: certificate.issuer })}
/>
<MSetRow label={t('native.cert.settingServer')} sub={certificate.host} />
<MSetRow label={t('native.cert.settingValidUntil')} sub={validUntil} />
</div>
<MSetHint>{t('native.cert.settingHint', { host: certificate.host })}</MSetHint>
{problem && (
<p role="alert" className="mt-2 text-caption text-[color:var(--m-st-danger)]">
{problem}
</p>
)}
<div className="mt-3 flex gap-2">
<MSetButton variant="ghost" disabled={busy} onClick={() => void replace()}>
{t('native.cert.settingReplace')}
</MSetButton>
<MSetButton variant="danger" disabled={busy} onClick={() => setConfirmRemove(true)}>
{t('native.cert.settingRemove')}
</MSetButton>
</div>
<MConfirmSheet
open={confirmRemove}
onClose={() => setConfirmRemove(false)}
title={t('native.cert.removeTitle')}
message={t('native.cert.removeMessage', { host: certificate.host })}
confirmLabel={t('native.cert.settingRemove')}
cancelLabel={t('common.cancel')}
danger
onConfirm={() => void remove()}
/>
</MSetCard>
);
}
@@ -20,6 +20,7 @@ import { useTranslation } from '../../../i18n'
import { MSetCard, MSetEyebrow, MSetInput, MSetButton, MSetHint } from './MSettingsUi'
import MConfirmSheet from './MConfirmSheet'
import MAppLockCard from './MAppLockCard'
import MClientCertCard from './MClientCertCard'
import PasswordChecklist from '../../../components/shared/PasswordChecklist'
import { fmtDate, usePasskeys } from '../../../components/Settings/usePasskeys'
import { stripTrailingSlashes, useAccountSettings } from '../../../components/Settings/useAccountSettings'
@@ -182,6 +183,8 @@ export default function MSettingsAccount() {
{/* ── Two-factor authentication ───────────────────────────── */}
{/* The app lock, inside the app only (Face ID, Touch ID or the passcode). */}
<MAppLockCard />
{/* The client certificate for a server behind mutual TLS, once one is stored. */}
<MClientCertCard />
<MSetCard title={t('settings.mfa.title')} icon={KeyRound} className="mt-3">
{mfaRequiredByPolicy && (