Skip to content

Commit 2da28d0

Browse files
committed
fix: add private CSRF token utility and harden error handling
Extract __getCsrfToken(prefix) with TSDoc and use it in signIn/signOut. Improves clarity and yields explicit errors for non-OK/non-JSON CSRF responses without changing unrelated code paths
1 parent f9f9f46 commit 2da28d0

1 file changed

Lines changed: 34 additions & 6 deletions

File tree

src/client.ts

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,32 @@ import type {
55
SignInAuthorizationParams,
66
} from './types.ts';
77

8+
/**
9+
* Retrieves a CSRF token from the authentication endpoint.
10+
*
11+
* @param prefix - The authentication base path.
12+
* @returns A promise that resolves to the CSRF token string.
13+
* @throws {Error} When the request fails, returns non-JSON, or lacks a token.
14+
* @private
15+
*/
16+
async function __getCsrfToken(prefix: string): Promise<string> {
17+
const res = await fetch(`${prefix}/csrf`);
18+
if (!res.ok) {
19+
throw new Error('Failed to fetch CSRF token');
20+
}
21+
let json: unknown;
22+
try {
23+
json = await res.json();
24+
} catch {
25+
throw new Error('CSRF endpoint returned non-JSON response');
26+
}
27+
const token = (json as { csrfToken?: string })?.csrfToken;
28+
if (!token) {
29+
throw new Error('Missing CSRF token');
30+
}
31+
return token;
32+
}
33+
834
/**
935
* Initiates a sign-in flow for the specified authentication provider.
1036
*
@@ -103,9 +129,10 @@ export async function signIn<P extends string | undefined = undefined>(
103129
signInUrlWithParams = `${signInUrl}?${params}`;
104130
}
105131

106-
// Retrieve CSRF token for request protection
107-
const csrfTokenResponse = await fetch(`${prefix}/csrf`);
108-
const { csrfToken } = await csrfTokenResponse.json();
132+
const csrfToken: string = await __getCsrfToken(prefix);
133+
if (!csrfToken) {
134+
throw new Error('Missing CSRF token');
135+
}
109136

110137
const res = await fetch(signInUrlWithParams, {
111138
method: 'post',
@@ -184,9 +211,10 @@ export async function signOut(options?: AstroSignOutParams): Promise<void> {
184211
}
185212
}
186213

187-
// Retrieve CSRF token for request protection
188-
const csrfTokenResponse = await fetch(`${prefix}/csrf`);
189-
const { csrfToken } = await csrfTokenResponse.json();
214+
const csrfToken: string = await __getCsrfToken(prefix);
215+
if (!csrfToken) {
216+
throw new Error('Missing CSRF token');
217+
}
190218

191219
const res = await fetch(`${prefix}/signout`, {
192220
method: 'post',

0 commit comments

Comments
 (0)