client/web: add csrf protection to web client api

Adds csrf protection and hooks up an initial POST request from
the React web client.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
This commit is contained in:
Sonia Appasamy
2023-08-16 18:52:31 -04:00
committed by Sonia Appasamy
parent 77ff705545
commit 077bbb8403
11 changed files with 245 additions and 47 deletions

32
client/web/src/api.ts Normal file
View File

@ -0,0 +1,32 @@
let csrfToken: string
// apiFetch wraps the standard JS fetch function
// with csrf header management.
export function apiFetch(
input: RequestInfo | URL,
init?: RequestInit | undefined
): Promise<Response> {
return fetch(input, {
...init,
headers: withCsrfToken(init?.headers),
}).then((r) => {
updateCsrfToken(r)
if (!r.ok) {
return r.text().then((err) => {
throw new Error(err)
})
}
return r
})
}
function withCsrfToken(h?: HeadersInit): HeadersInit {
return { ...h, "X-CSRF-Token": csrfToken }
}
function updateCsrfToken(r: Response) {
const tok = r.headers.get("X-CSRF-Token")
if (tok) {
csrfToken = tok
}
}