From 9be9e3963a120734966cac3d24b5e7f12d28a175 Mon Sep 17 00:00:00 2001 From: DR Date: Thu, 20 Feb 2025 22:27:48 -0500 Subject: [PATCH] Update PiHole authentication. https://docs.pi-hole.net/api/auth/#__tabbed_1_1 --- src/tools/server/sdk/pihole/piHole.ts | 47 ++++++++++++++++++--------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/src/tools/server/sdk/pihole/piHole.ts b/src/tools/server/sdk/pihole/piHole.ts index 52c55867f..a2267bcbd 100644 --- a/src/tools/server/sdk/pihole/piHole.ts +++ b/src/tools/server/sdk/pihole/piHole.ts @@ -12,26 +12,43 @@ export class PiHoleClient { this.baseHostName = trimStringEnding(hostname, ['/admin/index.php', '/admin', '/']); } - async getSummary() { - const response = await fetch( - new URL(`${this.baseHostName}/admin/api.php?summaryRaw&auth=${this.apiToken}`) - ); + async getSummary() { + const authResponse = await fetch(`${this.baseHostName}/api/auth`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ password: this.apiToken }) + }); - if (response.status !== 200) { - throw new Error(`Status code does not indicate success: ${response.status}`); - } + if (!authResponse.ok) { + throw new Error(`Authentication failed: ${authResponse.status}`); + } - const json = await response.json(); + const authJson = await authResponse.json(); + if (!authJson.session?.valid || !authJson.session.sid) { + throw new Error(`Invalid session response: ${JSON.stringify(authJson)}`); + } - if (Array.isArray(json)) { - throw new Error( - `Response does not indicate success. Authentication is most likely invalid: ${json}` + const sessionId = authJson.session.sid; + + const response = await fetch( + new URL(`${this.baseHostName}/api.php?summaryRaw&auth=${sessionId}`) ); - } - return json as PiHoleApiSummaryResponse; + if (response.status !== 200) { + throw new Error(`Failed to fetch summary: ${response.status}`); + } + + const json = await response.json(); + + if (Array.isArray(json)) { + throw new Error( + `Response does not indicate success. Authentication might be invalid: ${json}` + ); + } + return json as PiHoleApiSummaryResponse; } + async enable() { const response = await this.sendStatusChangeRequest('enable'); return response.status === 'enabled'; @@ -48,8 +65,8 @@ export class PiHoleClient { ): Promise { const response = await fetch( duration !== 0 - ? `${this.baseHostName}/admin/api.php?${action}=${duration}&auth=${this.apiToken}` - : `${this.baseHostName}/admin/api.php?${action}&auth=${this.apiToken}` + ? `${this.baseHostName}/api?${action}=${duration}&auth=${this.apiToken}` + : `${this.baseHostName}/api?${action}&auth=${this.apiToken}` ); if (response.status !== 200) {