( refreshToken: string )
| 12 | } |
| 13 | |
| 14 | async function refreshGscToken( |
| 15 | refreshToken: string |
| 16 | ): Promise<{ accessToken: string; expiresAt: Date }> { |
| 17 | if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) { |
| 18 | throw new Error( |
| 19 | 'GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET is not set in this environment' |
| 20 | ); |
| 21 | } |
| 22 | |
| 23 | const params = new URLSearchParams({ |
| 24 | client_id: process.env.GOOGLE_CLIENT_ID, |
| 25 | client_secret: process.env.GOOGLE_CLIENT_SECRET, |
| 26 | refresh_token: refreshToken, |
| 27 | grant_type: 'refresh_token', |
| 28 | }); |
| 29 | |
| 30 | const res = await fetch('https://oauth2.googleapis.com/token', { |
| 31 | method: 'POST', |
| 32 | headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, |
| 33 | body: params.toString(), |
| 34 | }); |
| 35 | |
| 36 | if (!res.ok) { |
| 37 | const text = await res.text(); |
| 38 | throw new Error(`Failed to refresh GSC token: ${text}`); |
| 39 | } |
| 40 | |
| 41 | const data = (await res.json()) as { |
| 42 | access_token: string; |
| 43 | expires_in: number; |
| 44 | }; |
| 45 | const expiresAt = new Date(Date.now() + data.expires_in * 1000); |
| 46 | return { accessToken: data.access_token, expiresAt }; |
| 47 | } |
| 48 | |
| 49 | export async function getGscAccessToken(projectId: string): Promise<string> { |
| 50 | const conn = await db.gscConnection.findUniqueOrThrow({ |
no test coverage detected