/
api.ts
401 lines (369 loc) · 12 KB
/
api.ts
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import { useCallback } from "react"
import useToaster from "src/hooks/toaster"
import { ExitNode, NodeData, ServeData, SubnetRoute } from "src/types"
import { assertNever } from "src/utils/util"
import { MutatorOptions, SWRConfiguration, useSWRConfig } from "swr"
import { noExitNode, runAsExitNode } from "./hooks/exit-nodes"
export const swrConfig: SWRConfiguration = {
fetcher: (url: string) => apiFetch(url, "GET"),
onError: (err, _) => console.error(err),
}
type APIType =
| { action: "up"; data: TailscaleUpData }
| { action: "logout" }
| { action: "new-auth-session"; data: AuthSessionNewData }
| { action: "update-prefs"; data: LocalPrefsData }
| { action: "update-routes"; data: SubnetRoute[] }
| { action: "update-exit-node"; data: ExitNode }
| { action: "patch-serve-item"; data: ServeData } // add or update
| { action: "delete-serve-item"; data: ServeData }
/**
* POST /api/up data
*/
type TailscaleUpData = {
Reauthenticate?: boolean // force reauthentication
ControlURL?: string
AuthKey?: string
}
/**
* GET /api/auth/session/new data
*/
type AuthSessionNewData = {
authUrl: string
}
/**
* PATCH /api/local/v0/prefs data
*/
type LocalPrefsData = {
RunSSHSet?: boolean
RunSSH?: boolean
}
/**
* POST /api/routes data
*/
type RoutesData = {
SetExitNode?: boolean
SetRoutes?: boolean
UseExitNode?: string
AdvertiseExitNode?: boolean
AdvertiseRoutes?: string[]
}
/**
* useAPI hook returns an api handler that can execute api calls
* throughout the web client UI.
*/
export function useAPI() {
const toaster = useToaster()
const { mutate } = useSWRConfig() // allows for global mutation
const handlePostError = useCallback(
(toast?: string) => (err: Error) => {
console.error(err)
toast && toaster.show({ variant: "danger", message: toast })
throw err
},
[toaster]
)
/**
* optimisticMutate wraps the SWR `mutate` function to apply some
* type-awareness with the following behavior:
*
* 1. `optimisticData` update is applied immediately on FetchDataType
* throughout the web client UI.
*
* 2. `fetch` data mutation runs.
*
* 3. On completion, FetchDataType is revalidated to exactly reflect the
* updated server state.
*
* The `key` argument is the useSWR key associated with the MutateDataType.
* All `useSWR(key)` consumers throughout the UI will see updates reflected.
*/
const optimisticMutate = useCallback(
<MutateDataType, FetchDataType = any>(
key: string,
fetch: Promise<FetchDataType>,
optimisticData: (current: MutateDataType) => MutateDataType,
revalidate?: boolean // optionally specify whether to run final revalidation (step 3)
): Promise<FetchDataType | undefined> => {
const options: MutatorOptions = {
/**
* populateCache is meant for use when the remote request returns back
* the updated data directly. i.e. When FetchDataType is the same as
* MutateDataType. Most of our data manipulation requests return a 200
* with empty data on success. We turn off populateCache so that the
* cache only gets updated after completion of the remote reqeust when
* the revalidation step runs.
*/
populateCache: false,
optimisticData,
revalidate: revalidate,
}
return mutate(key, fetch, options)
},
[mutate]
)
const api = useCallback(
(t: APIType) => {
switch (t.action) {
/**
* "up" handles authenticating the machine to tailnet.
*/
case "up":
return apiFetch<{ url?: string }>("/up", "POST", t.data)
.then((d) => d.url && window.open(d.url, "_blank")) // "up" login step
.then(() => incrementMetric("web_client_node_connect"))
.then(() => mutate("/data"))
.catch(handlePostError("Failed to login"))
/**
* "logout" handles logging the node out of tailscale, effectively
* expiring its node key.
*/
case "logout":
// For logout, must increment metric before running api call,
// as tailscaled will be unreachable after the call completes.
incrementMetric("web_client_node_disconnect")
return apiFetch("/local/v0/logout", "POST").catch(
handlePostError("Failed to logout")
)
/**
* "new-auth-session" handles creating a new check mode session to
* authorize the viewing user to manage the node via the web client.
*/
case "new-auth-session":
return apiFetch<AuthSessionNewData>("/auth/session/new", "GET").catch(
handlePostError("Failed to create new session")
)
/**
* "update-prefs" handles setting the node's tailscale prefs.
*/
case "update-prefs": {
return optimisticMutate<NodeData>(
"/data",
apiFetch<LocalPrefsData>("/local/v0/prefs", "PATCH", t.data),
(old) => ({
...old,
RunningSSHServer: t.data.RunSSHSet
? Boolean(t.data.RunSSH)
: old.RunningSSHServer,
})
)
.then(
() =>
t.data.RunSSHSet &&
incrementMetric(
t.data.RunSSH
? "web_client_ssh_enable"
: "web_client_ssh_disable"
)
)
.catch(handlePostError("Failed to update node preference"))
}
/**
* "update-routes" handles setting the node's advertised routes.
*/
case "update-routes": {
const body: RoutesData = {
SetRoutes: true,
AdvertiseRoutes: t.data.map((r) => r.Route),
}
return optimisticMutate<NodeData>(
"/data",
apiFetch<void>("/routes", "POST", body),
(old) => ({ ...old, AdvertisedRoutes: t.data })
)
.then(() => incrementMetric("web_client_advertise_routes_change"))
.catch(handlePostError("Failed to update routes"))
}
/**
* "update-exit-node" handles updating the node's state as either
* running as an exit node or using another node as an exit node.
*/
case "update-exit-node": {
const id = t.data.ID
const body: RoutesData = {
SetExitNode: true,
}
if (id !== noExitNode.ID && id !== runAsExitNode.ID) {
body.UseExitNode = id
} else if (id === runAsExitNode.ID) {
body.AdvertiseExitNode = true
}
const metrics: MetricName[] = []
return optimisticMutate<NodeData>(
"/data",
apiFetch<void>("/routes", "POST", body),
(old) => {
// Only update metrics whose values have changed.
if (old.AdvertisingExitNode !== Boolean(body.AdvertiseExitNode)) {
metrics.push(
body.AdvertiseExitNode
? "web_client_advertise_exitnode_enable"
: "web_client_advertise_exitnode_disable"
)
}
if (Boolean(old.UsingExitNode) !== Boolean(body.UseExitNode)) {
metrics.push(
body.UseExitNode
? "web_client_use_exitnode_enable"
: "web_client_use_exitnode_disable"
)
}
return {
...old,
UsingExitNode: Boolean(body.UseExitNode) ? t.data : undefined,
AdvertisingExitNode: Boolean(body.AdvertiseExitNode),
AdvertisingExitNodeApproved: Boolean(body.AdvertiseExitNode)
? true // gets updated in revalidation
: old.AdvertisingExitNodeApproved,
}
},
false // skip final revalidation
)
.then(() => metrics.forEach((m) => incrementMetric(m)))
.catch(handlePostError("Failed to update exit node"))
}
/**
* "patch-serve-item" handles adding or updating an item in the
* node's serve config.
*/
case "patch-serve-item": {
// todo: report metric?
return apiFetch("/serve/items", "PATCH", t.data).catch(
handlePostError("Failed to update item")
)
}
/**
* "delete-serve-item" handles deleting an item in the node's
* serve config.
*/
case "delete-serve-item": {
// todo: report metric?
return apiFetch("/serve/items", "DELETE", t.data).catch(
handlePostError("Failed to delete item")
)
}
default:
assertNever(t)
}
},
[handlePostError, mutate, optimisticMutate]
)
return api
}
let csrfToken: string
let synoToken: string | undefined // required for synology API requests
let unraidCsrfToken: string | undefined // required for unraid POST requests (#8062)
/**
* apiFetch wraps the standard JS fetch function with csrf header
* management and param additions specific to the web client.
*
* apiFetch adds the `api` prefix to the request URL,
* so endpoint should be provided without the `api` prefix
* (i.e. provide `/data` rather than `api/data`).
*/
export function apiFetch<T>(
endpoint: string,
method: "GET" | "POST" | "PATCH" | "DELETE",
body?: any
): Promise<T> {
const urlParams = new URLSearchParams(window.location.search)
const nextParams = new URLSearchParams()
if (synoToken) {
nextParams.set("SynoToken", synoToken)
} else {
const token = urlParams.get("SynoToken")
if (token) {
nextParams.set("SynoToken", token)
}
}
const search = nextParams.toString()
const url = `api${endpoint}${search ? `?${search}` : ""}`
var contentType: string
if (unraidCsrfToken && method === "POST") {
const params = new URLSearchParams()
params.append("csrf_token", unraidCsrfToken)
if (body) {
params.append("ts_data", JSON.stringify(body))
}
body = params.toString()
contentType = "application/x-www-form-urlencoded;charset=UTF-8"
} else {
body = body ? JSON.stringify(body) : undefined
contentType = "application/json"
}
return fetch(url, {
method: method,
headers: {
Accept: "application/json",
"Content-Type": contentType,
"X-CSRF-Token": csrfToken,
},
body: body,
})
.then((r) => {
updateCsrfToken(r)
if (!r.ok) {
return r.text().then((err) => {
throw new Error(err)
})
}
return r
})
.then((r) => {
if (r.headers.get("Content-Type") === "application/json") {
return r.json()
}
})
.then((r) => {
r?.UnraidToken && setUnraidCsrfToken(r.UnraidToken)
return r
})
}
function updateCsrfToken(r: Response) {
const tok = r.headers.get("X-CSRF-Token")
if (tok) {
csrfToken = tok
}
}
export function setSynoToken(token?: string) {
synoToken = token
}
function setUnraidCsrfToken(token?: string) {
unraidCsrfToken = token
}
/**
* incrementMetric hits the client metrics local API endpoint to
* increment the given counter metric by one.
*/
export function incrementMetric(metricName: MetricName) {
const postData: MetricsPOSTData[] = [
{
Name: metricName,
Type: "counter",
Value: 1,
},
]
apiFetch("/local/v0/upload-client-metrics", "POST", postData).catch(
(error) => {
console.error(error)
}
)
}
type MetricsPOSTData = {
Name: MetricName
Type: MetricType
Value: number
}
type MetricType = "counter" | "gauge"
export type MetricName =
| "web_client_advertise_exitnode_enable"
| "web_client_advertise_exitnode_disable"
| "web_client_use_exitnode_enable"
| "web_client_use_exitnode_disable"
| "web_client_ssh_enable"
| "web_client_ssh_disable"
| "web_client_node_connect"
| "web_client_node_disconnect"
| "web_client_advertise_routes_change"