@@ -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