Skip to content

armgit / dashy

Public Imported from GitHub
0

πŸš€ A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!

πŸ› Rebuilt Pi-Hole v6 widget to account for new pi-hole API (#1819)

Alicia Sykes68520507d9e5
diff --git a/src/components/Widgets/PiHoleStatsV6.vue b/src/components/Widgets/PiHoleStatsV6.vue
index df37e3e6..546f9588 100644
--- a/src/components/Widgets/PiHoleStatsV6.vue
+++ b/src/components/Widgets/PiHoleStatsV6.vue
@@ -20,43 +20,21 @@
<script>
import WidgetMixin from '@/mixins/WidgetMixin';
import ChartingMixin from '@/mixins/ChartingMixin';
+import PiHoleV6Mixin from '@/mixins/PiHoleV6Mixin';
import { capitalize } from '@/utils/MiscHelpers';
export default {
- mixins: [WidgetMixin, ChartingMixin],
+ mixins: [WidgetMixin, ChartingMixin, PiHoleV6Mixin],
data() {
return {
status: null,
dataTable: null,
- csrfToken: null,
- sid: null,
};
},
computed: {
- /* Let user select which comic to display: random, latest or a specific number */
- hostname() {
- const usersChoice = this.parseAsEnvVar(this.options.hostname);
- if (!usersChoice) this.error('You must specify the hostname for your Pi-Hole server');
- return usersChoice;
- },
- apiKey() {
- const usersChoice = this.parseAsEnvVar(this.options.apiKey);
- if (!usersChoice) this.error('App Password is required, please see the docs');
- return usersChoice;
- },
hideStatus() { return this.options.hideStatus; },
hideChart() { return this.options.hideChart; },
hideInfo() { return this.options.hideInfo; },
- authHeader() {
- return {
- 'X-FTL-SID': this.sid,
- 'X-FTL-CSRF': this.csrfToken,
- Accept: 'application/json',
- };
- },
- authEndpoint() {
- return `${this.hostname}/api/auth`;
- },
blockingStatusEndpoint() {
return `${this.hostname}/api/dns/blocking`;
},
@@ -91,40 +69,12 @@ export default {
methods: {
capitalize,
fetchData() {
- this.makeRequest(
- this.authEndpoint,
- { 'Content-Type': 'application/json' },
- 'POST',
- { password: this.apiKey },
- )
- .then(this.processAuthData)
- .then(
- () => {
- if (!this.sid || !this.csrfToken) return;
-
- Promise.all([
- this.fetchBlockingStatus(),
- this.fetchInMemoryStats(),
- this.fetchTodayStats(),
- this.fetchAllTimeStats(),
- ]).then(this.processData);
- },
- );
- },
- processAuthData({ session }) {
- if (!session) {
- this.error('Missing session info in auth response');
- } else if (session.valid !== true) {
- this.error('Authentication failed: Invalid credentials or 2FA token required');
- } else {
- const { sid, csrf } = session;
- if (!sid || !csrf) {
- this.error('No CSRF token or SID received');
- } else {
- this.sid = sid;
- this.csrfToken = csrf;
- }
- }
+ this.withSession(() => Promise.all([
+ this.fetchBlockingStatus(),
+ this.fetchInMemoryStats(),
+ this.fetchTodayStats(),
+ this.fetchAllTimeStats(),
+ ]).then(this.processData));
},
fetchBlockingStatus() {
return this.makeRequest(this.blockingStatusEndpoint, this.authHeader);
diff --git a/src/components/Widgets/PiHoleTopQueriesV6.vue b/src/components/Widgets/PiHoleTopQueriesV6.vue
index 2da16342..7b68f853 100644
--- a/src/components/Widgets/PiHoleTopQueriesV6.vue
+++ b/src/components/Widgets/PiHoleTopQueriesV6.vue
@@ -12,45 +12,23 @@
<script>
import WidgetMixin from '@/mixins/WidgetMixin';
+import PiHoleV6Mixin from '@/mixins/PiHoleV6Mixin';
import { showNumAsThousand } from '@/utils/MiscHelpers';
export default {
- mixins: [WidgetMixin],
+ mixins: [WidgetMixin, PiHoleV6Mixin],
components: {},
data() {
return {
results: null,
- csrfToken: null,
- sid: null,
};
},
computed: {
- /* Let user select which comic to display: random, latest or a specific number */
- hostname() {
- const usersChoice = this.parseAsEnvVar(this.options.hostname);
- if (!usersChoice) this.error('You must specify the hostname for your Pi-Hole server');
- return usersChoice;
- },
- apiKey() {
- const usersChoice = this.parseAsEnvVar(this.options.apiKey);
- if (!usersChoice) this.error('App Password is required, please see the docs');
- return usersChoice;
- },
count() {
const usersChoice = this.options.count;
if (usersChoice && typeof usersChoice === 'number') return usersChoice;
return 10;
},
- authHeader() {
- return {
- 'X-FTL-SID': this.sid,
- 'X-FTL-CSRF': this.csrfToken,
- Accept: 'application/json',
- };
- },
- authEndpoint() {
- return `${this.hostname}/api/auth`;
- },
/* This is actually just the stats that are shown on the Pi-Hole dashboard, which amounts to
24hrs when the service first boots up, but will drift to be a little more than 24hrs worth of
data as the server runs. If you need accurate stats to a particular timeframe, then the
@@ -63,38 +41,10 @@ export default {
},
methods: {
fetchData() {
- this.makeRequest(
- this.authEndpoint,
- { 'Content-Type': 'application/json' },
- 'POST',
- { password: this.apiKey },
- )
- .then(this.processAuthData)
- .then(
- () => {
- if (!this.sid || !this.csrfToken) return;
-
- Promise.all([
- this.fetchTopAllowedDomains(),
- this.fetchTopBlockedDomains(),
- ]).then(this.processData);
- },
- );
- },
- processAuthData({ session }) {
- if (!session) {
- this.error('Missing session info in auth response');
- } else if (session.valid !== true) {
- this.error('Authentication failed: Invalid credentials or 2FA token required');
- } else {
- const { sid, csrf } = session;
- if (!sid || !csrf) {
- this.error('No CSRF token or SID received');
- } else {
- this.sid = sid;
- this.csrfToken = csrf;
- }
- }
+ this.withSession(() => Promise.all([
+ this.fetchTopAllowedDomains(),
+ this.fetchTopBlockedDomains(),
+ ]).then(this.processData));
},
fetchTopAllowedDomains() {
const url = new URL(this.topDomainsEndpoint);
diff --git a/src/components/Widgets/PiHoleTrafficV6.vue b/src/components/Widgets/PiHoleTrafficV6.vue
index aa0b02f9..16c03595 100644
--- a/src/components/Widgets/PiHoleTrafficV6.vue
+++ b/src/components/Widgets/PiHoleTrafficV6.vue
@@ -5,77 +5,23 @@
<script>
import WidgetMixin from '@/mixins/WidgetMixin';
import ChartingMixin from '@/mixins/ChartingMixin';
+import PiHoleV6Mixin from '@/mixins/PiHoleV6Mixin';
export default {
- mixins: [WidgetMixin, ChartingMixin],
+ mixins: [WidgetMixin, ChartingMixin, PiHoleV6Mixin],
components: {},
- data() {
- return {
- csrfToken: null,
- sid: null,
- };
- },
computed: {
- /* Let user select which comic to display: random, latest or a specific number */
- hostname() {
- const usersChoice = this.parseAsEnvVar(this.options.hostname);
- if (!usersChoice) this.error('You must specify the hostname for your Pi-Hole server');
- return usersChoice;
- },
- apiKey() {
- const usersChoice = this.parseAsEnvVar(this.options.apiKey);
- if (!usersChoice) this.error('App Password is required, please see the docs');
- return usersChoice;
- },
- authHeader() {
- return {
- 'X-FTL-SID': this.sid,
- 'X-FTL-CSRF': this.csrfToken,
- Accept: 'application/json',
- };
- },
- authEndpoint() {
- return `${this.hostname}/api/auth`;
- },
historyEndpoint() {
return `${this.hostname}/api/history`;
},
},
methods: {
fetchData() {
- this.makeRequest(
- this.authEndpoint,
- { 'Content-Type': 'application/json' },
- 'POST',
- { password: this.apiKey },
- )
- .then(this.processAuthData)
- .then(
- () => {
- if (!this.sid || !this.csrfToken) return;
-
- this.fetchHistory().then((response) => {
- if (this.validate(response)) {
- this.processData(response);
- }
- });
- },
- );
- },
- processAuthData({ session }) {
- if (!session) {
- this.error('Missing session info in auth response');
- } else if (session.valid !== true) {
- this.error('Authentication failed: Invalid credentials or 2FA token required');
- } else {
- const { sid, csrf } = session;
- if (!sid || !csrf) {
- this.error('No CSRF token or SID received');
- } else {
- this.sid = sid;
- this.csrfToken = csrf;
+ this.withSession(() => this.fetchHistory().then((response) => {
+ if (this.validate(response)) {
+ this.processData(response);
}
- }
+ }));
},
fetchHistory() {
return this.makeRequest(this.historyEndpoint, this.authHeader);
diff --git a/src/mixins/PiHoleV6Mixin.js b/src/mixins/PiHoleV6Mixin.js
new file mode 100644
index 00000000..bd1fe52f
--- /dev/null
+++ b/src/mixins/PiHoleV6Mixin.js
@@ -0,0 +1,79 @@
+import { localStorageKeys } from '@/utils/config/defaults';
+
+const logins = {};
+
+/* Shared auth and session handling for the Pi-hole v6 widgets */
+export default {
+ data() {
+ return { session: null };
+ },
+ computed: {
+ hostname() {
+ const usersChoice = this.parseAsEnvVar(this.options.hostname);
+ if (!usersChoice) this.error('You must specify the hostname for your Pi-Hole server');
+ return usersChoice;
+ },
+ apiKey() {
+ const usersChoice = this.parseAsEnvVar(this.options.apiKey);
+ if (!usersChoice) this.error('App Password is required, please see the docs');
+ return usersChoice;
+ },
+ authEndpoint() {
+ return `${this.hostname}/api/auth`;
+ },
+ authHeader() {
+ const { sid, csrf } = this.session || {};
+ return { 'X-FTL-SID': sid, 'X-FTL-CSRF': csrf, Accept: 'application/json' };
+ },
+ sessionKey() {
+ return `${localStorageKeys.PI_HOLE_SESSION}-${this.hostname}`;
+ },
+ },
+ methods: {
+ /* Runs the widget's fetch under a live session, logging in first if needed */
+ withSession(run) {
+ return this.ensureSession().then(run).then(
+ () => this.saveSession(this.session),
+ () => this.clearSession(),
+ );
+ },
+ ensureSession() {
+ const stored = this.readSession();
+ if (stored && stored.expires > Date.now()) {
+ this.session = stored;
+ return Promise.resolve();
+ }
+ return this.login();
+ },
+ /* Widgets for the same host share a single in-flight login */
+ login() {
+ const key = this.sessionKey;
+ if (!logins[key]) {
+ const headers = { 'Content-Type': 'application/json' };
+ logins[key] = this.makeRequest(this.authEndpoint, headers, 'POST', { password: this.apiKey })
+ .then(({ session }) => {
+ if (!session?.valid) {
+ this.error('Authentication failed: Invalid credentials or 2FA token required');
+ throw new Error('Pi-hole login failed');
+ }
+ const { sid, csrf, validity } = session;
+ return this.saveSession({ sid, csrf, validity: validity * 1000 });
+ })
+ .finally(() => { delete logins[key]; });
+ }
+ return logins[key].then((session) => { this.session = session; });
+ },
+ readSession() {
+ try { return JSON.parse(localStorage.getItem(this.sessionKey)); } catch { return null; }
+ },
+ saveSession(session) {
+ this.session = { ...session, expires: Date.now() + session.validity };
+ localStorage.setItem(this.sessionKey, JSON.stringify(this.session));
+ return this.session;
+ },
+ clearSession() {
+ this.session = null;
+ localStorage.removeItem(this.sessionKey);
+ },
+ },
+};
diff --git a/src/mixins/WidgetMixin.js b/src/mixins/WidgetMixin.js
index 2a79c026..94964928 100644
--- a/src/mixins/WidgetMixin.js
+++ b/src/mixins/WidgetMixin.js
@@ -112,6 +112,7 @@ const WidgetMixin = {
return {
'Target-URL': endpoint,
CustomHeaders: JSON.stringify(customHeaders),
+ 'Content-Type': 'application/json',
...(this.allowInsecure ? { 'Allow-Insecure': 'true' } : {}),
};
},
diff --git a/src/utils/config/defaults.js b/src/utils/config/defaults.js
index 946c0b33..ec9ce1f5 100644
--- a/src/utils/config/defaults.js
+++ b/src/utils/config/defaults.js
@@ -148,6 +148,7 @@ const defaults = {
ISADMIN: 'isAdmin',
ID_TOKEN: 'idToken',
DISABLE_CRITICAL_WARNING: 'disableCriticalWarning',
+ PI_HOLE_SESSION: 'piHoleSession',
},
/* Key names for cookie identifiers */
cookieKeys: {
diff --git a/tests/components/widgets/piholev6.test.js b/tests/components/widgets/piholev6.test.js
new file mode 100644
index 00000000..79937bf8
--- /dev/null
+++ b/tests/components/widgets/piholev6.test.js
@@ -0,0 +1,97 @@
+import {
+ describe, it, expect, beforeEach, vi,
+} from 'vitest';
+import { shallowMount, flushPromises } from '@vue/test-utils';
+import request from '@/utils/request';
+import PiHoleTopQueriesV6 from '@/components/Widgets/PiHoleTopQueriesV6.vue';
+
+vi.mock('@/utils/request', () => ({ default: vi.fn() }));
+vi.mock('@/utils/logging/ErrorHandler', () => ({ default: vi.fn() }));
+
+const session = {
+ valid: true, sid: 'sid-1', csrf: 'csrf-1', validity: 1800,
+};
+const domains = { domains: [{ domain: 'example.com', count: 3 }] };
+const sessionKey = 'piHoleSession-http://pi.hole';
+const storage = new Map();
+
+function mount(options = {}) {
+ return shallowMount(PiHoleTopQueriesV6, {
+ props: { options: { hostname: 'http://pi.hole', apiKey: 'app-pw', ...options } },
+ });
+}
+
+const calls = () => request.mock.calls.map(([config]) => config);
+const methods = () => calls().map((c) => c.method);
+
+describe('PiHoleTopQueriesV6 widget', () => {
+ beforeEach(() => {
+ request.mockReset();
+ request.mockImplementation(({ method }) => Promise.resolve({
+ data: method === 'POST' ? { session } : domains,
+ }));
+ storage.clear();
+ localStorage.getItem.mockImplementation((key) => storage.get(key) ?? null);
+ localStorage.setItem.mockImplementation((key, value) => storage.set(key, value));
+ localStorage.removeItem.mockImplementation((key) => storage.delete(key));
+ });
+
+ it('logs in, then sends the session with each request', async () => {
+ const wrapper = mount();
+ await flushPromises();
+ const [login, ...queries] = calls();
+ expect(login).toMatchObject({ method: 'POST', url: 'http://pi.hole/api/auth' });
+ expect(JSON.parse(login.data)).toEqual({ password: 'app-pw' });
+ expect(queries).toHaveLength(2);
+ queries.forEach(({ headers }) => {
+ expect(headers).toMatchObject({ 'X-FTL-SID': 'sid-1', 'X-FTL-CSRF': 'csrf-1' });
+ });
+ expect(wrapper.find('.domain').text()).toBe('example.com');
+ });
+
+ it('stores the session, and reuses it while still valid', async () => {
+ mount();
+ await flushPromises();
+ expect(JSON.parse(storage.get(sessionKey))).toMatchObject({ sid: 'sid-1', csrf: 'csrf-1' });
+
+ request.mockClear();
+ mount();
+ await flushPromises();
+ expect(methods()).toEqual(['GET', 'GET']);
+ });
+
+ it('logs in again once the stored session has expired', async () => {
+ storage.set(sessionKey, JSON.stringify({ sid: 'old', expires: Date.now() - 1 }));
+ mount();
+ await flushPromises();
+ expect(methods()[0]).toBe('POST');
+ });
+
+ it('shares one login between widgets mounted together', async () => {
+ const wrappers = [mount(), mount()];
+ await flushPromises();
+ expect(methods().filter((m) => m === 'POST')).toHaveLength(1);
+ wrappers.forEach((w) => expect(w.find('.domain').text()).toBe('example.com'));
+ });
+
+ it('sends the login body as JSON when going through the proxy', async () => {
+ mount({ useProxy: true });
+ await flushPromises();
+ const [login] = calls();
+ expect(login.url).toContain('/cors-proxy');
+ expect(login.headers).toMatchObject({
+ 'Target-URL': 'http://pi.hole/api/auth',
+ 'Content-Type': 'application/json',
+ });
+ expect(JSON.parse(login.data)).toEqual({ password: 'app-pw' });
+ });
+
+ it('forgets the session when a request with it fails', async () => {
+ request.mockImplementation(({ method }) => (method === 'POST'
+ ? Promise.resolve({ data: { session } })
+ : Promise.reject(new Error('Request failed with status 401'))));
+ mount();
+ await flushPromises();
+ expect(storage.has(sessionKey)).toBe(false);
+ });
+});
diff --git a/tests/server/cors-proxy.test.js b/tests/server/cors-proxy.test.js
index 003afb89..975abcc8 100644
--- a/tests/server/cors-proxy.test.js
+++ b/tests/server/cors-proxy.test.js
@@ -283,3 +283,34 @@ describe('CORS proxy env-var substitution', () => {
expect(warnSpy.mock.calls[1][0]).toContain('DASHY_WARN_TEST_TWO');
});
});
+
+describe('CORS proxy body forwarding', () => {
+ let target;
+ let targetUrl;
+ let received;
+
+ beforeAll(() => new Promise((resolve) => {
+ target = http.createServer((req, res) => {
+ let body = '';
+ req.on('data', (chunk) => { body += chunk; });
+ req.on('end', () => {
+ received = { contentType: req.headers['content-type'], body };
+ res.end('{}');
+ });
+ });
+ target.listen(0, '127.0.0.1', () => {
+ targetUrl = `http://127.0.0.1:${target.address().port}`;
+ resolve();
+ });
+ }));
+ afterAll(() => new Promise((resolve) => target.close(resolve)));
+
+ it('forwards a JSON body to the target', async () => {
+ await request(app).post('/cors-proxy')
+ .set('Target-URL', targetUrl)
+ .set('CustomHeaders', JSON.stringify({ 'Content-Type': 'application/json' }))
+ .send({ password: 'hunter2' });
+ expect(received.body).toBe('{"password":"hunter2"}');
+ expect(received.contentType).toBe('application/json');
+ });
+});