-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathuseMfaConnect.ts
More file actions
150 lines (128 loc) · 4.75 KB
/
useMfaConnect.ts
File metadata and controls
150 lines (128 loc) · 4.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { useMutation, useQuery } from '@tanstack/react-query';
import { fetch } from '@tauri-apps/plugin-http';
import { error } from '@tauri-apps/plugin-log';
import { useCallback, useEffect, useRef, useState } from 'react';
import { api } from '../../../rust-api/api';
import { getInstancesQueryOptions } from '../../../rust-api/query';
import type { EdgeRequestHeaders } from '../../../rust-api/types';
import {
CLIENT_MFA_ENDPOINT,
type MfaStartMethod,
startClientMfaSession,
} from '../api/startClientMfaSession';
import { useLocationCardContext } from '../context/context';
import { LocationCardViews } from '../context/types';
import { handleMfaStartError } from './handleMfaStartError';
type MfaFinishResponse = {
preshared_key: string;
};
type MfaErrorResponse = {
error: string;
};
type CodeMfaStartMethod = Extract<MfaStartMethod, 0 | 1>;
type UseMfaConnectOptions = {
debounceMs?: number;
};
const waitForMinimumDuration = async (startedAt: number, minimumMs: number) => {
const remainingMs = Math.max(minimumMs - (performance.now() - startedAt), 0);
if (remainingMs === 0) return;
await new Promise((resolve) => window.setTimeout(resolve, remainingMs));
};
export const useMfaConnect = (
method: CodeMfaStartMethod,
{ debounceMs = 0 }: UseMfaConnectOptions = {},
) => {
const { location, setPostureError, setView } = useLocationCardContext();
const [token, setToken] = useState<string | null>(null);
const [isStarting, setIsStarting] = useState(debounceMs > 0);
const [startError, setStartError] = useState<string | null>(null);
const [isVerifying, setIsVerifying] = useState(false);
const [verifyError, setVerifyError] = useState<string | null>(null);
const [requestHeaders, setRequestHeaders] = useState<EdgeRequestHeaders | null>(null);
const { data: instances } = useQuery(getInstancesQueryOptions);
const instance = instances?.find((i) => i.id === location.instance_id);
const { mutate: connectMutate } = useMutation({
mutationFn: api.connect,
meta: { invalidate: ['locations'] },
onSuccess: () => {
setView(LocationCardViews.Connected);
},
onError: (err) => {
error(`Connect command failed after successful code verification\n${err}`);
},
});
// Fire the /start request exactly once when instance data is ready.
const startCalled = useRef(false);
// biome-ignore lint/correctness/useExhaustiveDependencies: intentional one-shot trigger via startCalled ref
useEffect(() => {
if (!instance || startCalled.current) return;
startCalled.current = true;
const startedAt = performance.now();
setIsStarting(true);
(async () => {
try {
const { response, headers } = await startClientMfaSession({
instance,
location,
method,
});
await waitForMinimumDuration(startedAt, debounceMs);
setRequestHeaders(headers);
setToken(response.token);
} catch (err) {
await waitForMinimumDuration(startedAt, debounceMs);
if (handleMfaStartError({ err, location, setPostureError, setView })) {
return;
}
setStartError(err instanceof Error ? err.message : 'Failed to start MFA');
} finally {
setIsStarting(false);
}
})();
}, [instance]);
const verifyCode = useCallback(
async (code: string) => {
if (!token || !instance || !requestHeaders) return;
setIsVerifying(true);
setVerifyError(null);
const body = JSON.stringify({ token, code });
try {
const res = await fetch(`${instance.proxy_url}${CLIENT_MFA_ENDPOINT}/finish`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...requestHeaders,
},
body,
});
if (res.ok) {
const data = (await res.json()) as MfaFinishResponse;
connectMutate({
locationId: location.id,
connectionType: location.connection_type,
presharedKey: data.preshared_key,
});
} else {
const data = (await res.json()) as MfaErrorResponse;
const { error: errorMessage } = data;
if (errorMessage === 'Unauthorized') {
setVerifyError('Invalid code');
} else if (
errorMessage === 'invalid token' ||
errorMessage === 'login session not found'
) {
setView(LocationCardViews.Default);
} else {
setVerifyError('Verification failed');
}
}
} catch {
setVerifyError('Failed to reach server');
} finally {
setIsVerifying(false);
}
},
[token, instance, requestHeaders, location, connectMutate, setView],
);
return { token, isStarting, startError, verifyCode, isVerifying, verifyError };
};