π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
β¨ Server-side item launch alias, much faster
Alicia Sykes5e0ca067d3d5
diff --git a/services/app.js b/services/app.jsindex 787b72f3..67341533 100644--- a/services/app.js+++ b/services/app.js@@ -35,6 +35,7 @@ const sslServer = require('./utils/ssl-server'); // TLS-enabled web serverconst corsProxy = require('./endpoints/cors-proxy'); // Enables API requests to CORS-blocked servicesconst getUser = require('./endpoints/get-user'); // Enables server side user lookupconst openSearch = require('./endpoints/opensearch'); // Descriptor for browser keyword search+const aliasTarget = require('./endpoints/alias-target'); // Resolves /<alias> to an item's URLconst { apiEnabledGate, apiErrorHandler, createApiRouter } = require('./endpoints/api'); // Opt-in REST APIconst { loadOidcSettings, createOidcMiddleware, maybeBootstrapConfig } = require('./utils/auth-oidc');@@ -194,6 +195,9 @@ const authIsConfigured = Boolean();const guestAccessOn = Boolean(initialAuthConfig?.enableGuestAccess);+/* Dashy's own login page is client-side, so users[] gates access even without ENABLE_HTTP_AUTH */+const anyLoginConfigured = authIsConfigured || Boolean(initialAuthConfig.users?.length);+/* Require an authenticated identity on this request. No-op for zero-auth deploys. */function requireAuth(req, res, next) {if (!authIsConfigured) return next();@@ -373,6 +377,16 @@ const app = express().use(express.static(path.resolve(rootDir, process.env.USER_DATA_DIR || 'user-data'))).use(express.static(path.join(rootDir, 'dist'))).use(express.static(path.join(rootDir, 'public'), { index: 'initialization.html' }))+ // Jump straight to an aliased item, skipping the SPA boot (deploys with no login only)+ .use(method('GET', (req, res, next) => {+ try {+ const url = anyLoginConfigured ? undefined : aliasTarget(config, req);+ if (url) return res.set('Cache-Control', 'no-store').redirect(302, url);+ } catch (e) {+ printWarning('Could not resolve alias, falling back to the app', e);+ }+ return next();+ }))// If no other route is matched, serve up the index.html with a 404 status.use((req, res) => {res.status(404).sendFile('index.html', { root: path.join(rootDir, 'dist') }, (err) => {diff --git a/services/endpoints/alias-target.js b/services/endpoints/alias-target.jsnew file mode 100644index 00000000..42bc52ac--- /dev/null+++ b/services/endpoints/alias-target.js@@ -0,0 +1,36 @@+/**+ * Resolves a request path like /jelly to the URL of the item that claims+ * that alias, so the server can redirect without the browser booting the app+ */++const configSchema = require('../../src/utils/config/ConfigSchema.json');+const { hostFromRequest } = require('../utils/request-origin');++/* Taken from the schema, so the server and the client can't disagree on what's reserved */+const RESERVED = configSchema.properties.sections.items+ .properties.items.items.properties.alias.not.enum;++/* Anything carrying visibility rules is left to the client, which can evaluate them */+const isUnrestricted = (entity) => !entity.displayData;++/* Only redirect somewhere absolute, browsable, and not back at this same path */+const isSafeTarget = (url, req) => {+ try {+ const target = new URL(url);+ if (!['http:', 'https:'].includes(target.protocol)) return false;+ return target.host.toLowerCase() !== hostFromRequest(req)+ || target.pathname.replace(/\/+$/, '') !== req.path;+ } catch {+ return false;+ }+};++module.exports = (config, req) => {+ const alias = req.path.slice(1).toLowerCase();+ if (!alias || alias.includes('/') || RESERVED.includes(alias)) return undefined;+ const item = (config?.sections || [])+ .filter(isUnrestricted)+ .flatMap((section) => section.items || [])+ .find((i) => isUnrestricted(i) && String(i.alias || '').toLowerCase() === alias);+ return item && isSafeTarget(item.url, req) ? item.url : undefined;+};diff --git a/services/endpoints/opensearch.js b/services/endpoints/opensearch.jsindex fff65f71..cdd5ea3d 100644--- a/services/endpoints/opensearch.js+++ b/services/endpoints/opensearch.js@@ -3,6 +3,8 @@* Dashy as a keyword search engine, for jumping to items by their alias*/+const { originFromRequest } = require('../utils/request-origin');+/* Must match the title on index.html's <link rel="search">, which browsers check on discovery */const SHORT_NAME = 'Dashy';@@ -12,14 +14,6 @@ const xmlEscape = (input) => String(input ?? '').replace((c) => ({ '<': '<', '>': '>', '&': '&', "'": ''', '"': '"' }[c]),);-/* The public origin this request arrived on, honouring a reverse proxy's forwarded headers */-const originFromRequest = (req) => {- const firstHeader = (name) => (req.headers[name] || '').split(',')[0].trim();- const proto = firstHeader('x-forwarded-proto') || (req.socket.encrypted ? 'https' : 'http');- const host = firstHeader('x-forwarded-host') || req.headers.host || 'localhost';- return `${proto}://${host}`;-};-module.exports = (config, req) => {const origin = xmlEscape(originFromRequest(req));const title = xmlEscape(config?.pageInfo?.title || SHORT_NAME);diff --git a/services/utils/request-origin.js b/services/utils/request-origin.jsnew file mode 100644index 00000000..c8b01bca--- /dev/null+++ b/services/utils/request-origin.js@@ -0,0 +1,19 @@+/**+ * Works out the public host and origin a request arrived on,+ * honouring the headers a reverse proxy sets in front of Dashy+ */++/* Proxy chains send a comma-separated list, the first entry is the original client-facing value */+const firstHeader = (req, name) => (req.headers[name] || '').split(',')[0].trim();++/* Hosts are case-insensitive, so always compare and emit them lowercased */+const hostFromRequest = (req) => (+ firstHeader(req, 'x-forwarded-host') || req.headers.host || 'localhost'+).toLowerCase();++const originFromRequest = (req) => {+ const proto = firstHeader(req, 'x-forwarded-proto') || (req.socket.encrypted ? 'https' : 'http');+ return `${proto}://${hostFromRequest(req)}`;+};++module.exports = { hostFromRequest, originFromRequest };diff --git a/src/components/LinkItems/Item.vue b/src/components/LinkItems/Item.vueindex 7b46d2a0..41ff37b5 100644--- a/src/components/LinkItems/Item.vue+++ b/src/components/LinkItems/Item.vue@@ -177,14 +177,16 @@ export default {const {title, description, provider, hotkey, alias,} = this.item;- const hasShortcut = hotkey || alias;+ // Aliases only resolve against the root config, so never promise one on a sub-page+ const aliasWorksHere = alias && !this.$store.getters.isSubConfig;+ const hasShortcut = hotkey || aliasWorksHere;if (!description && !provider && !hasShortcut && !this.titleTruncated) return {}; // Nothing to showconst parts = [];if (this.titleTruncated) parts.push(`<b>${title}</b>`);if (provider) parts.push(`<b>Provider</b>: ${provider}`);if (description) parts.push(description);if (hotkey) parts.push(`Press '${hotkey}' to launch`);- if (alias) parts.push(`Visit '/${alias}' to launch`);+ if (aliasWorksHere) parts.push(`Visit '/${alias}' to launch`);const editKey = this.appConfig.disableContextMenu? 'interactive-editor.edit-section.edit-tooltip-basic': 'interactive-editor.edit-section.edit-tooltip';diff --git a/src/main.js b/src/main.jsindex 3872fb99..52788e21 100644--- a/src/main.js+++ b/src/main.js@@ -72,9 +72,11 @@ const handleAuthFailure = (provider, err) => {const needsOidcLoginPage = () => isOidcLoginPageEnabled() && !isLoggedIn()&& router.currentRoute.value.name !== 'login';-/* An alias redirect aborts the first navigation on purpose, anything else failing is worth logging */-const skipMount = (failure) => {- if (failure?.to?.name !== 'alias') ErrorHandler('Initial navigation failed', failure);+/* An alias redirect aborts the first navigation on purpose, anything else should still render */+const handleAbortedNavigation = (failure) => {+ if (failure?.to?.name === 'alias') return;+ ErrorHandler('Initial navigation failed', failure);+ router.replace({ name: '404' }).catch(() => {}).finally(mount);};router.isReady().then(() => {@@ -91,4 +93,4 @@ router.isReady().then(() => {} else {mount();}-}, skipMount);+}, handleAbortedNavigation);diff --git a/tests/server/alias-redirect-auth.test.js b/tests/server/alias-redirect-auth.test.jsnew file mode 100644index 00000000..48b12b96--- /dev/null+++ b/tests/server/alias-redirect-auth.test.js@@ -0,0 +1,34 @@+// @vitest-environment node+import fs from 'fs';+import os from 'os';+import path from 'path';+import { describe, it, expect, afterAll } from 'vitest';+import request from 'supertest';++// Auth strategy is chosen when the app module loads, so env must be set first+const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-alias-auth-'));+process.env.USER_DATA_DIR = tmpDir;+process.env.BASIC_AUTH_USERNAME = 'admin';+process.env.BASIC_AUTH_PASSWORD = 'test-pass';+fs.writeFileSync(path.join(tmpDir, 'conf.yml'), `pageInfo: { title: Test }+sections:+ - name: Open+ items:+ - { title: Jellyfin, url: 'https://jelly.lab.local', alias: jelly }+`);++afterAll(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ delete process.env.BASIC_AUTH_USERNAME;+ delete process.env.BASIC_AUTH_PASSWORD;+});++const app = require('../../services/app');++describe('Server-side alias redirect, with auth configured', () => {+ it('never redirects, so the client can enforce login and visibility rules', async () => {+ const res = await request(app).get('/jelly');+ expect(res.headers.location).toBeUndefined();+ expect(res.text || '').not.toContain('jelly.lab.local');+ });+});diff --git a/tests/server/alias-redirect-userauth.test.js b/tests/server/alias-redirect-userauth.test.jsnew file mode 100644index 00000000..04bd157b--- /dev/null+++ b/tests/server/alias-redirect-userauth.test.js@@ -0,0 +1,32 @@+// @vitest-environment node+import fs from 'fs';+import os from 'os';+import path from 'path';+import { describe, it, expect, afterAll } from 'vitest';+import request from 'supertest';++// conf.yml users without ENABLE_HTTP_AUTH is Dashy's standard client-side login+const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-alias-userauth-'));+process.env.USER_DATA_DIR = tmpDir;+fs.writeFileSync(path.join(tmpDir, 'conf.yml'), `pageInfo: { title: Test }+appConfig:+ auth:+ users:+ - { user: alicia, hash: ABC123 }+sections:+ - name: Open+ items:+ - { title: Jellyfin, url: 'https://jelly.lab.local', alias: jelly }+`);++afterAll(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++const app = require('../../services/app');++describe('Server-side alias redirect, with client-side login configured', () => {+ it('never redirects past the login page', async () => {+ const res = await request(app).get('/jelly');+ expect(res.headers.location).toBeUndefined();+ expect(res.text || '').not.toContain('jelly.lab.local');+ });+});diff --git a/tests/server/alias-redirect.test.js b/tests/server/alias-redirect.test.jsnew file mode 100644index 00000000..f16f6241--- /dev/null+++ b/tests/server/alias-redirect.test.js@@ -0,0 +1,71 @@+// @vitest-environment node+import fs from 'fs';+import os from 'os';+import path from 'path';+import { describe, it, expect, afterAll } from 'vitest';+import request from 'supertest';++// Each item below exists to make one assertion below load-bearing+const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-alias-redirect-'));+process.env.USER_DATA_DIR = tmpDir;+fs.writeFileSync(path.join(tmpDir, 'conf.yml'), `pageInfo: { title: Test }+sections:+ - name: Open+ items:+ - { title: Jellyfin, url: 'https://jelly.lab.local', alias: Jelly }+ - { title: Not browsable, url: 'mailto:[email protected]', alias: mail }+ - { title: Points at itself, url: 'http://dash.lab.local/loopy', alias: loopy }+ - { title: Shadows a route, url: 'https://evil.lab.local', alias: login }+ - { title: Shadows a file, url: 'https://evil.lab.local', alias: changelog }+ - { title: Path shaped, url: 'https://evil.lab.local', alias: jelly/extra }+ - { title: Restricted, url: 'https://secret.lab.local', alias: secret,+ displayData: { showForGroups: [admins] } }+ - name: Hidden+ displayData: { hideForGuests: true }+ items:+ - { title: In hidden section, url: 'https://nope.lab.local', alias: nope }+`);+fs.writeFileSync(path.join(tmpDir, 'changelog'), 'a real static file');++afterAll(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++const app = require('../../services/app');++describe('Server-side alias redirect', () => {+ it.each(['/jelly', '/JELLY'])('redirects %s straight to the item URL', async (url) => {+ const res = await request(app).get(url);+ expect(res.status).toBe(302);+ expect(res.headers.location).toBe('https://jelly.lab.local');+ });++ it.each([+ ['an unknown alias', '/nothing-here'],+ ['a reserved word an item claims', '/login'],+ ['a path-shaped alias an item claims', '/jelly/extra'],+ ['a URL that is not http(s)', '/mail'],+ ['an item carrying visibility rules', '/secret'],+ ['an item inside a restricted section', '/nope'],+ ])('leaves %s to the client', async (_label, url) => {+ expect((await request(app).get(url)).headers.location).toBeUndefined();+ });++ it('ignores requests that are not a GET', async () => {+ expect((await request(app).post('/jelly')).headers.location).toBeUndefined();+ });++ it.each([+ ['the same host', { Host: 'dash.lab.local' }, undefined],+ ['the same host in mixed case', { Host: 'Dash.Lab.Local' }, undefined],+ ['the same host via a proxy', { Host: 'dashy:8080', 'X-Forwarded-Host': 'dash.lab.local' }, undefined],+ ['a different host', { Host: 'other.lab.local' }, 'http://dash.lab.local/loopy'],+ ])('asked via %s, redirects to %s', async (_label, headers, location) => {+ const res = await request(app).get('/loopy').set(headers);+ expect(res.headers.location).toBe(location);+ });++ it('lets a real static file win over an item claiming that alias', async () => {+ const res = await request(app).get('/changelog');+ expect(res.status).toBe(200);+ expect(res.headers.location).toBeUndefined();+ });+});