|
| 1 | +import { encode } from '@stablelib/base64'; |
| 2 | +import { useMutation } from '@tanstack/react-query'; |
| 3 | +import { fetch } from '@tauri-apps/plugin-http'; |
| 4 | +import { error } from '@tauri-apps/plugin-log'; |
| 5 | +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; |
| 6 | +import { api } from '../../../rust-api/api'; |
| 7 | +import { useLocationCardContext } from '../context/context'; |
| 8 | +import { LocationCardViews } from '../context/types'; |
| 9 | + |
| 10 | +const MFA_ENDPOINT = 'api/v1/client-mfa'; |
| 11 | + |
| 12 | +type MfaStartResponse = { |
| 13 | + token: string; |
| 14 | + challenge: string; |
| 15 | +}; |
| 16 | + |
| 17 | +type MfaErrorResponse = { |
| 18 | + error: string; |
| 19 | +}; |
| 20 | + |
| 21 | +type TokenData = { |
| 22 | + token: string; |
| 23 | + challenge: string; |
| 24 | +}; |
| 25 | + |
| 26 | +export const useMfaMobileConnect = () => { |
| 27 | + const { location, instance, setView } = useLocationCardContext(); |
| 28 | + |
| 29 | + const [isStarting, setIsStarting] = useState(false); |
| 30 | + const [startError, setStartError] = useState<string | null>(null); |
| 31 | + const [tokenData, setTokenData] = useState<TokenData | null>(null); |
| 32 | + const [isConnecting, setIsConnecting] = useState(false); |
| 33 | + const [connectionError, setConnectionError] = useState<string | null>(null); |
| 34 | + |
| 35 | + const wsRef = useRef<WebSocket | null>(null); |
| 36 | + const expectedCloseRef = useRef(false); |
| 37 | + |
| 38 | + const { mutate: connectMutate } = useMutation({ |
| 39 | + mutationFn: api.connect, |
| 40 | + onSuccess: () => { |
| 41 | + setView(LocationCardViews.Connected); |
| 42 | + }, |
| 43 | + onError: (err) => { |
| 44 | + error(`Connect command failed after successful mobile MFA\n${err}`); |
| 45 | + setConnectionError('Failed to establish VPN connection'); |
| 46 | + }, |
| 47 | + }); |
| 48 | + |
| 49 | + // Open WebSocket when tokenData is available |
| 50 | + useEffect(() => { |
| 51 | + if (!tokenData) return; |
| 52 | + |
| 53 | + const wsUrl = `${instance.proxy_url |
| 54 | + .replace(/^http:/, 'ws:') |
| 55 | + .replace( |
| 56 | + /^https:/, |
| 57 | + 'wss:', |
| 58 | + )}${MFA_ENDPOINT}/remote?token=${encodeURIComponent(tokenData.token)}`; |
| 59 | + |
| 60 | + expectedCloseRef.current = false; |
| 61 | + const ws = new WebSocket(wsUrl); |
| 62 | + wsRef.current = ws; |
| 63 | + |
| 64 | + ws.onopen = () => { |
| 65 | + setIsConnecting(true); |
| 66 | + setConnectionError(null); |
| 67 | + }; |
| 68 | + |
| 69 | + ws.onmessage = (event: MessageEvent) => { |
| 70 | + try { |
| 71 | + const parsed = JSON.parse(event.data as string) as unknown; |
| 72 | + if ( |
| 73 | + typeof parsed === 'object' && |
| 74 | + parsed !== null && |
| 75 | + 'preshared_key' in parsed && |
| 76 | + typeof (parsed as Record<string, unknown>).preshared_key === 'string' |
| 77 | + ) { |
| 78 | + const presharedKey = (parsed as { preshared_key: string }).preshared_key; |
| 79 | + expectedCloseRef.current = true; |
| 80 | + connectMutate({ |
| 81 | + locationId: location.id, |
| 82 | + connectionType: location.connection_type, |
| 83 | + presharedKey, |
| 84 | + }); |
| 85 | + } else { |
| 86 | + error( |
| 87 | + `Unexpected mobile MFA WS message for location ${location.id}: ${event.data}`, |
| 88 | + ); |
| 89 | + } |
| 90 | + } catch (e) { |
| 91 | + error(`Failed to parse mobile MFA WS message for location ${location.id}: ${e}`); |
| 92 | + } |
| 93 | + }; |
| 94 | + |
| 95 | + ws.onerror = () => { |
| 96 | + if (!expectedCloseRef.current) { |
| 97 | + setIsConnecting(false); |
| 98 | + setConnectionError('Connection error. Please try again.'); |
| 99 | + error(`Mobile MFA WebSocket error for location ${location.id}`); |
| 100 | + } |
| 101 | + }; |
| 102 | + |
| 103 | + ws.onclose = () => { |
| 104 | + if (!expectedCloseRef.current) { |
| 105 | + setIsConnecting(false); |
| 106 | + setConnectionError('Connection closed unexpectedly. Please try again.'); |
| 107 | + error(`Mobile MFA WebSocket closed unexpectedly for location ${location.id}`); |
| 108 | + } |
| 109 | + }; |
| 110 | + |
| 111 | + return () => { |
| 112 | + expectedCloseRef.current = true; |
| 113 | + ws.close(); |
| 114 | + wsRef.current = null; |
| 115 | + setIsConnecting(false); |
| 116 | + }; |
| 117 | + }, [tokenData, instance, connectMutate, location]); |
| 118 | + |
| 119 | + // Clean up WebSocket on unmount |
| 120 | + useEffect(() => { |
| 121 | + return () => { |
| 122 | + if (wsRef.current) { |
| 123 | + expectedCloseRef.current = true; |
| 124 | + wsRef.current.close(); |
| 125 | + wsRef.current = null; |
| 126 | + } |
| 127 | + }; |
| 128 | + }, []); |
| 129 | + |
| 130 | + const qrValue = useMemo(() => { |
| 131 | + if (!tokenData) return null; |
| 132 | + const json = JSON.stringify({ |
| 133 | + token: tokenData.token, |
| 134 | + challenge: tokenData.challenge, |
| 135 | + instance_id: instance.uuid, |
| 136 | + }); |
| 137 | + return encode(new TextEncoder().encode(json)); |
| 138 | + }, [tokenData, instance.uuid]); |
| 139 | + |
| 140 | + const start = useCallback(async () => { |
| 141 | + setIsStarting(true); |
| 142 | + setStartError(null); |
| 143 | + setConnectionError(null); |
| 144 | + // Clear previous token → triggers WS cleanup via effect |
| 145 | + setTokenData(null); |
| 146 | + |
| 147 | + let headers: Record<string, string>; |
| 148 | + try { |
| 149 | + headers = await api.getEdgeRequestHeaders(); |
| 150 | + } catch { |
| 151 | + setStartError('Failed to load request headers'); |
| 152 | + setIsStarting(false); |
| 153 | + return; |
| 154 | + } |
| 155 | + |
| 156 | + try { |
| 157 | + const res = await fetch(`${instance.proxy_url}${MFA_ENDPOINT}/start`, { |
| 158 | + method: 'POST', |
| 159 | + headers: { 'Content-Type': 'application/json', ...headers }, |
| 160 | + body: JSON.stringify({ |
| 161 | + method: 4, |
| 162 | + pubkey: instance.pubkey, |
| 163 | + location_id: location.network_id, |
| 164 | + }), |
| 165 | + }); |
| 166 | + |
| 167 | + if (res.ok) { |
| 168 | + const data = (await res.json()) as MfaStartResponse; |
| 169 | + setTokenData({ token: data.token, challenge: data.challenge }); |
| 170 | + } else { |
| 171 | + const data = (await res.json()) as MfaErrorResponse; |
| 172 | + setStartError(data.error ?? 'Failed to start mobile authentication'); |
| 173 | + error(`Mobile MFA start failed for location ${location.id}: ${data.error}`); |
| 174 | + } |
| 175 | + } catch (e) { |
| 176 | + setStartError('Failed to reach server'); |
| 177 | + error(`Mobile MFA start network error for location ${location.id}: ${e}`); |
| 178 | + } finally { |
| 179 | + setIsStarting(false); |
| 180 | + } |
| 181 | + }, [instance, location]); |
| 182 | + |
| 183 | + const reset = useCallback(() => { |
| 184 | + if (wsRef.current) { |
| 185 | + expectedCloseRef.current = true; |
| 186 | + wsRef.current.close(); |
| 187 | + wsRef.current = null; |
| 188 | + } |
| 189 | + setTokenData(null); |
| 190 | + setIsStarting(false); |
| 191 | + setStartError(null); |
| 192 | + setIsConnecting(false); |
| 193 | + setConnectionError(null); |
| 194 | + }, []); |
| 195 | + |
| 196 | + return { start, isStarting, startError, qrValue, isConnecting, connectionError, reset }; |
| 197 | +}; |
0 commit comments