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!

πŸ¦– Adds env var parsing for backward compatibility widget tokens

Alicia Sykes31a1cbf2781b
diff --git a/docs/widgets.md b/docs/widgets.md
index 5010aa77..57729108 100644
--- a/docs/widgets.md
+++ b/docs/widgets.md
@@ -1809,17 +1809,7 @@ Displays the number of queries blocked by [Pi-Hole](https://pi-hole.net/).
```
> [!TIP]
-> In order to avoid leaking secret data, both `hostname` and `apiKey` can leverage environment variables. Simply pass the name of the variable, which MUST start with `VITE_APP_`.
-
-```yaml
-- type: pi-hole-stats
- options:
- hostname: VITE_APP_pihole_ip
- apiKey: VITE_APP_pihole_key
-```
-
-> [!IMPORTANT]
-> You will need to restart the server (or the docker image) if adding/editing an env var for this to be refreshed.
+> To avoid storing secrets in plaintext, both `hostname` and `apiKey` can be supplied via environment variables. See [Handling Secrets](#handling-secrets).
#### Info
@@ -1855,17 +1845,7 @@ Displays the number of queries blocked by [Pi-Hole](https://pi-hole.net/). Use t
```
> [!TIP]
-> In order to avoid leaking secret data, both `hostname` and `apiKey` can leverage environment variables. Simply pass the name of the variable, which MUST start with `VITE_APP_`.
-
-```yaml
-- type: pi-hole-stats-v6
- options:
- hostname: VITE_APP_pihole_ip
- apiKey: VITE_APP_pihole_key
-```
-
-> [!IMPORTANT]
-> You will need to restart the server (or the docker image) if adding/editing an env var for this to be refreshed.
+> To avoid storing secrets in plaintext, both `hostname` and `apiKey` can be supplied via environment variables. See [Handling Secrets](#handling-secrets).
#### Info
@@ -2662,7 +2642,7 @@ Displays storage statistics and file listings from a [Filebrowser Quantum](https
useProxy: true
options:
hostname: http://filebrowser.local:8080
- apiKey: VITE_APP_FILEBROWSER_KEY
+ apiKey: DASHY_FILEBROWSER_KEY
source: Documents
path: /
showRecent: 5
@@ -2678,7 +2658,7 @@ Displays storage statistics and file listings from a [Filebrowser Quantum](https
useProxy: true
options:
hostname: http://filebrowser.local:8080
- apiKey: VITE_APP_FILEBROWSER_KEY
+ apiKey: DASHY_FILEBROWSER_KEY
source: Downloads
showDetailedStats: true
showRecent: 10
@@ -3407,27 +3387,32 @@ Vary: Origin
### Handling Secrets
-Some widgets require you to pass potentially sensetive info such as API keys. The `conf.yml` is not ideal for this, as it's stored in plaintext.
-Instead, for secrets you should use environmental vairables.
+Some widgets require you to pass potentially sensitive info such as API keys. The `conf.yml` is not ideal for this, as it's stored in plaintext. Instead, for secrets you should use environment variables.
-You can do this, by setting the environmental variable name as the value, instead of the actual key, and then setting that env var in your container or local environment.
+In your widget options, set the value to the name of an environment variable starting with `DASHY_` (or `VITE_APP_` / `VUE_APP_` for backwards compatibility). The Dashy server will substitute it with the matching `process.env` value when proxying the request.
-The key can be named whatever you like, but it must start with `VITE_APP_` (to be picked up by Vite). If you need to update any of these values, a rebuild is required, by running `yarn build` then restarting the container.
+The widget must be set to route through the Dashy server with `useProxy: true`. Without this, the placeholder is sent directly to the upstream API and will fail. Substitution covers the request URL, headers and body, so any auth pattern (Bearer, Basic, query param, POST body) works.
-For more infomation about setting and managing your environmental variables, see [Management Docs --> Environmental Variables](/docs/management.md#passing-in-environmental-variables).
+For more information about setting and managing your environment variables, see [Management Docs --> Environmental Variables](/docs/management.md#passing-in-environmental-variables).
For example:
```yaml
- type: weather
+ useProxy: true
options:
- apiKey: VITE_APP_WEATHER_TOKEN
+ apiKey: DASHY_WEATHER_TOKEN
city: London
units: metric
hideDetails: true
```
-Then, set `VITE_APP_WEATHER_TOKEN='xxx'`
+Then set `DASHY_WEATHER_TOKEN='xxx'` in your container or local environment, and restart Dashy. To rotate the value, just update the env var and restart. No rebuild required.
+
+> [!NOTE]
+> Only env vars starting with `DASHY_`, `VITE_APP_` or `VUE_APP_` are eligible for substitution. Other server-side env vars are never exposed.
+>
+> If you build Dashy from source yourself, `VITE_APP_*` and `DASHY_*` vars set at build time are also baked into the bundle by Vite, which works without `useProxy: true`.
---
diff --git a/services/cors-proxy.js b/services/cors-proxy.js
index 510a719e..8b0522c6 100644
--- a/services/cors-proxy.js
+++ b/services/cors-proxy.js
@@ -19,6 +19,30 @@ const BLOCKED_HOSTS = new Set([
// Operator escape hatch, set this env var to bypass all proxy restrictions
const restrictionsDisabled = !!process.env.DANGEROUSLY_DISABLE_PROXY_RESTRICTIONS;
+// If reference to env var is present, substitute for env var value if set
+const PLACEHOLDER_RE = /\b(?:DASHY_|VITE_APP_|VUE_APP_)\w+/g;
+const warnedPlaceholders = new Set();
+const resolvePlaceholder = (name) => {
+ const value = process.env[name];
+ if (value !== undefined) return value;
+ if (!warnedPlaceholders.has(name)) {
+ warnedPlaceholders.add(name);
+ // eslint-disable-next-line no-console
+ console.warn(`[cors-proxy] Env-var placeholder '${name}' is referenced but not set`);
+ }
+ return name;
+};
+const substituteEnv = (val) => {
+ if (typeof val === 'string') return val.replace(PLACEHOLDER_RE, resolvePlaceholder);
+ if (Array.isArray(val)) return val.map(substituteEnv);
+ if (val && typeof val === 'object') {
+ const out = {};
+ Object.keys(val).forEach((k) => { out[k] = substituteEnv(val[k]); });
+ return out;
+ }
+ return val;
+};
+
// Validate the target URL against scheme and host policies
// Returns { ok: true } on success, or { ok: false, status, error } on rejection
const validateTargetUrl = (raw) => {
@@ -44,7 +68,7 @@ const validateTargetUrl = (raw) => {
return { ok: true };
};
-module.exports = (req, res) => {
+const handler = (req, res) => {
// Apply allow-all response headers
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, PATCH, POST, DELETE');
@@ -58,12 +82,13 @@ module.exports = (req, res) => {
return;
}
- // Get desired URL, from Target-URL header, and validate it against the policy
- const targetURL = req.header('Target-URL');
- if (!targetURL) {
+ // Get desired URL, resolve env-var placeholders, then validate against the policy.
+ const rawTargetURL = req.header('Target-URL');
+ if (!rawTargetURL) {
res.status(400).send({ error: 'Missing required Target-URL header' });
return;
}
+ const targetURL = substituteEnv(rawTargetURL);
const validation = validateTargetUrl(targetURL);
if (!validation.ok) {
res.status(validation.status).send({ error: validation.error });
@@ -75,7 +100,7 @@ module.exports = (req, res) => {
const rawCustomHeaders = req.header('CustomHeaders');
if (rawCustomHeaders) {
try {
- headers = JSON.parse(rawCustomHeaders);
+ headers = substituteEnv(JSON.parse(rawCustomHeaders));
} catch (e) {
res.status(400).send({ error: 'CustomHeaders header contains malformed JSON' });
return;
@@ -86,7 +111,7 @@ module.exports = (req, res) => {
const requestConfig = {
method: req.method,
url: targetURL,
- data: req.body,
+ data: substituteEnv(req.body),
headers,
timeout: 30000,
maxResponseSize: 10 * 1024 * 1024, // 10 MB
@@ -102,3 +127,6 @@ module.exports = (req, res) => {
(error) => send(500, { error }),
);
};
+
+module.exports = handler;
+module.exports.substituteEnv = substituteEnv;
diff --git a/src/mixins/WidgetMixin.js b/src/mixins/WidgetMixin.js
index 0eb4f786..959ec16b 100644
--- a/src/mixins/WidgetMixin.js
+++ b/src/mixins/WidgetMixin.js
@@ -97,7 +97,7 @@ const WidgetMixin = {
/* Used as v-tooltip, pass text content in, and will show on hover */
tooltip(content, html = false) {
return {
- content, html,
+ content, html,
};
},
/* Makes data request, returns promise */
@@ -131,19 +131,13 @@ const WidgetMixin = {
});
});
},
- /* Check if a value is an environment variable, return its value if so. */
+ /* If the string is a build-time env-var placeholder, return its value
+ * Otherwise, will pass it through to the proxy for it to resolve server-side */
parseAsEnvVar(str) {
if (typeof str !== 'string') return str;
- if (str.includes('VUE_APP_') || str.includes('VITE_APP_')) {
- const envKey = str.replace(/^VUE_APP_/, 'VITE_APP_');
- const envVar = import.meta.env[envKey];
- if (!envVar) {
- this.error(`Environment variable ${envKey} not found`);
- } else {
- return envVar;
- }
- }
- return str;
+ if (!/^(?:VITE_APP_|VUE_APP_|DASHY_)/.test(str)) return str;
+ const envKey = str.replace(/^VUE_APP_/, 'VITE_APP_');
+ return import.meta.env[envKey] ?? str;
},
},
};
diff --git a/tests/server/cors-proxy.test.js b/tests/server/cors-proxy.test.js
index bbebd550..7682695a 100644
--- a/tests/server/cors-proxy.test.js
+++ b/tests/server/cors-proxy.test.js
@@ -1,8 +1,11 @@
// @vitest-environment node
-import { describe, it, expect } from 'vitest';
+import {
+ describe, it, expect, afterEach, beforeAll, afterAll, vi,
+} from 'vitest';
import request from 'supertest';
const app = require('../../services/app');
+const { substituteEnv } = require('../../services/cors-proxy');
describe('CORS proxy', () => {
it('rejects missing Target-URL', async () => {
@@ -85,4 +88,85 @@ describe('CORS proxy', () => {
expect(res.status).toBe(200);
expect(res.headers['access-control-allow-origin']).toBe('*');
});
+
+ it('resolves env-var placeholder in Target-URL before validating', async () => {
+ process.env.DASHY_TEST_BLOCKED_HOST = '169.254.169.254';
+ try {
+ const res = await request(app).get('/cors-proxy').set('Target-URL', 'http://DASHY_TEST_BLOCKED_HOST/');
+ expect(res.status).toBe(403);
+ expect(res.body.error).toContain('169.254.169.254');
+ } finally {
+ delete process.env.DASHY_TEST_BLOCKED_HOST;
+ }
+ });
+});
+
+describe('CORS proxy env-var substitution', () => {
+ const SET_KEYS = [];
+ const setEnv = (k, v) => { SET_KEYS.push(k); process.env[k] = v; };
+ afterEach(() => { while (SET_KEYS.length) delete process.env[SET_KEYS.pop()]; });
+
+ let warnSpy;
+ beforeAll(() => { warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); });
+ afterAll(() => { warnSpy.mockRestore(); });
+
+ it('replaces a DASHY_ token with its env value', () => {
+ setEnv('DASHY_FOO', 'secret');
+ expect(substituteEnv('Bearer DASHY_FOO')).toBe('Bearer secret');
+ });
+
+ it('replaces VITE_APP_ and VUE_APP_ tokens (back-compat)', () => {
+ setEnv('VITE_APP_KEY', 'abc');
+ setEnv('VUE_APP_KEY', 'xyz');
+ expect(substituteEnv('VITE_APP_KEY')).toBe('abc');
+ expect(substituteEnv('VUE_APP_KEY')).toBe('xyz');
+ });
+
+ it('leaves unset placeholders verbatim', () => {
+ expect(substituteEnv('Bearer DASHY_NOT_SET')).toBe('Bearer DASHY_NOT_SET');
+ });
+
+ it('does not substitute non-prefixed env vars', () => {
+ setEnv('AWS_SECRET_KEY', 'should-not-leak');
+ expect(substituteEnv('AWS_SECRET_KEY')).toBe('AWS_SECRET_KEY');
+ });
+
+ it('replaces multiple placeholders in one string', () => {
+ setEnv('DASHY_HOST', 'pi.local');
+ setEnv('DASHY_KEY', 'k1');
+ expect(substituteEnv('http://DASHY_HOST/api?key=DASHY_KEY')).toBe('http://pi.local/api?key=k1');
+ });
+
+ it('walks into objects and arrays', () => {
+ setEnv('DASHY_PASS', 'p4ss');
+ setEnv('DASHY_USER', 'admin');
+ const input = { auth: { user: 'DASHY_USER', pass: 'DASHY_PASS' }, tags: ['DASHY_PASS'] };
+ expect(substituteEnv(input)).toEqual({
+ auth: { user: 'admin', pass: 'p4ss' },
+ tags: ['p4ss'],
+ });
+ });
+
+ it('passes through non-string, non-object values unchanged', () => {
+ expect(substituteEnv(undefined)).toBe(undefined);
+ expect(substituteEnv(null)).toBe(null);
+ expect(substituteEnv(42)).toBe(42);
+ expect(substituteEnv(true)).toBe(true);
+ });
+
+ it('substitutes mixed-case suffix (matches process.env case-sensitively)', () => {
+ setEnv('VITE_APP_pihole_ip', '10.0.0.1');
+ expect(substituteEnv('http://VITE_APP_pihole_ip/api')).toBe('http://10.0.0.1/api');
+ });
+
+ it('warns once per unique unset placeholder, then stays quiet', () => {
+ warnSpy.mockClear();
+ // Use names unlikely to collide with any earlier warnings in this run
+ substituteEnv('DASHY_WARN_TEST_ONE');
+ substituteEnv('DASHY_WARN_TEST_ONE'); // repeat - should not re-log
+ substituteEnv('DASHY_WARN_TEST_TWO');
+ expect(warnSpy).toHaveBeenCalledTimes(2);
+ expect(warnSpy.mock.calls[0][0]).toContain('DASHY_WARN_TEST_ONE');
+ expect(warnSpy.mock.calls[1][0]).toContain('DASHY_WARN_TEST_TWO');
+ });
});
diff --git a/vite.config.mjs b/vite.config.mjs
index 3ea60d50..b7c49a21 100644
--- a/vite.config.mjs
+++ b/vite.config.mjs
@@ -48,6 +48,7 @@ function copyUserDataConfig() {
}
export default defineConfig({
+ envPrefix: ['VITE_', 'DASHY_'],
plugins: [
vue(),
svgLoader(),