1 import type { ReactNode } from 'react';
2 import { useEffect, useState } from 'react';
4 import useKTActivation from '@proton/components/containers/keyTransparency/useKTActivation';
5 import useApiStatus from '@proton/components/hooks/useApiStatus';
6 import { serverTime } from '@proton/crypto';
7 import { ktSentryReportError } from '@proton/key-transparency/lib';
8 import type { APP_NAMES } from '@proton/shared/lib/constants';
9 import { SECOND } from '@proton/shared/lib/constants';
10 import { KeyTransparencyActivation } from '@proton/shared/lib/interfaces';
12 import useOnline from '../../hooks/useOnline';
13 import type { KTContext } from './ktContext';
14 import useKTState from './useKTState';
15 import { KeyTransparencyContext } from './useKeyTransparencyContext';
16 import useRunSelfAudit from './useRunSelfAudit';
17 import useVerifyOutboundPublicKeys from './useVerifyOutboundPublicKeys';
24 const KeyTransparencyManager = ({ children }: Props) => {
25 const ktActivation = useKTActivation();
27 const [ktStateLoaded, ktState, setKTState] = useKTState();
29 const [selfAuditPending, setSelfAuditPending] = useState(false);
31 const verifyOutboundPublicKeys = useVerifyOutboundPublicKeys();
33 const runSelfAudit = useRunSelfAudit();
35 const { offline } = useApiStatus();
36 const onlineStatus = useOnline();
37 const safeIsOnline = onlineStatus && !offline;
40 const run = async () => {
42 const { selfAuditResult } = await runSelfAudit(ktState.selfAuditResult);
43 setKTState({ selfAuditResult });
45 ktSentryReportError(error, { context: 'runSelfAuditPeriodically' });
48 if (selfAuditPending && ktActivation !== KeyTransparencyActivation.DISABLED && safeIsOnline) {
49 setSelfAuditPending(false);
52 }, [selfAuditPending, ktActivation, safeIsOnline]);
58 // Determine when the next self-audit should happen.
59 const pendingDelay = 10 * SECOND;
60 const now = +serverTime();
61 // If the self-audit result does not exist or the nextAuditTime has passed
62 // run the self-audit after pendingDelay else run it at nextAuditTime.
64 ktState.selfAuditResult && ktState.selfAuditResult.nextAuditTime > now
65 ? ktState.selfAuditResult.nextAuditTime - now
67 const timeoutID = setTimeout(() => setSelfAuditPending(true), delay);
68 return () => clearTimeout(timeoutID);
69 }, [ktStateLoaded, ktState]);
71 const ktFunctions: KTContext = {
74 verifyOutboundPublicKeys,
77 return <KeyTransparencyContext.Provider value={ktFunctions}>{children}</KeyTransparencyContext.Provider>;
80 export default KeyTransparencyManager;