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!

✨ Implements OpenSearch protocol for browser address bar

Alicia Sykes0af537c5d41a
diff --git a/docs/searching.md b/docs/searching.md
index f055c437..ad565efa 100644
--- a/docs/searching.md
+++ b/docs/searching.md
@@ -87,6 +87,17 @@ Some limitations to be aware of:
- It's not possible to create aliases for pages Dashy already uses, including: 'home', 'minimal', 'workspace', 'login', 'download' and '404'
- If two items share an alias, the first one in the config wins
+
+## Searching From The Address Bar
+
+Dashy publishes an [OpenSearch](https://developer.mozilla.org/en-US/docs/Web/XML/Guides/OpenSearch) descriptor (at `/opensearch.xml`), so your browser can offer it as a search keyword. Once added, typing `dashy jelly` into the address bar jumps straight to Jellyfin if you've setup an `alias` for this.
+
+Most browsers pick this up after you've visited your dashboard, then need the keyword assigning by hand:
+- **Chrome / Edge**: Settings β†’ Search engines β†’ Site search, find your dashboard and set a shortcut
+- **Firefox**: Settings β†’ Search β†’ Search Shortcuts, or right-click the address bar and choose "Add search engine"
+
+You can also skip OpenSearch and add the engine manually, using `https://dashy.lab.local/%s` as the URL.
+
## Web Search
It's possible to launch a web search directly from Dashy, which might be useful if you're using Dashy as your start page. This can be done by typing your query as normal, and then pressing <kbd>⏎</kbd>/Enter. Web search options are configured under `appConfig.webSearch`.
diff --git a/index.html b/index.html
index 5d737153..71a7903a 100644
--- a/index.html
+++ b/index.html
@@ -13,6 +13,8 @@
<link rel="icon" type="image/png" href="/favicon.ico" />
<link rel="stylesheet" type="text/css" href="/loading-screen.css" />
<link rel="stylesheet" type="text/css" href="/theme-fonts.css" media="print" onload="this.media='all'" />
+ <!-- Lets the browser offer Dashy as a keyword search engine, for jumping to apps by alias -->
+ <link rel="search" type="application/opensearchdescription+xml" title="Dashy" href="/opensearch.xml" />
<!-- Default Page Title -->
<title>Dashy</title>
</head>
diff --git a/services/app.js b/services/app.js
index edbf9d06..787b72f3 100644
--- a/services/app.js
+++ b/services/app.js
@@ -34,6 +34,7 @@ const systemInfo = require('./endpoints/system-info'); // Basic system info, for
const sslServer = require('./utils/ssl-server'); // TLS-enabled web server
const corsProxy = require('./endpoints/cors-proxy'); // Enables API requests to CORS-blocked services
const getUser = require('./endpoints/get-user'); // Enables server side user lookup
+const openSearch = require('./endpoints/opensearch'); // Descriptor for browser keyword search
const { apiEnabledGate, apiErrorHandler, createApiRouter } = require('./endpoints/api'); // Opt-in REST API
const { loadOidcSettings, createOidcMiddleware, maybeBootstrapConfig } = require('./utils/auth-oidc');
@@ -49,6 +50,7 @@ const ENDPOINTS = {
corsProxy: '/cors-proxy',
getUser: '/get-user',
configSchema: '/schema.json',
+ openSearch: '/opensearch.xml',
api: '/api',
};
@@ -329,6 +331,16 @@ const app = express()
.use(ENDPOINTS.api, apiErrorHandler)
// Serves the config schema, for use by external editors and validators
.get(ENDPOINTS.configSchema, (req, res) => res.json(configSchema))
+ // OpenSearch descriptor, so browsers can offer Dashy as a keyword search engine
+ // Not cached, since the search template is built from the requesting host
+ .get(ENDPOINTS.openSearch, (req, res) => {
+ try {
+ res.set('Cache-Control', 'no-store')
+ .type('application/opensearchdescription+xml').send(openSearch(config, req));
+ } catch (e) {
+ safeEnd(res, errBody(e), 500);
+ }
+ })
// Middleware to serve any .yml/.yaml files in USER_DATA_DIR with optional protection
// Note: returns stripped version if auth configured but not yet authenticated
.get(/\.ya?ml$/i, bootstrapAuth, (req, res) => {
diff --git a/services/endpoints/opensearch.js b/services/endpoints/opensearch.js
new file mode 100644
index 00000000..fff65f71
--- /dev/null
+++ b/services/endpoints/opensearch.js
@@ -0,0 +1,35 @@
+/**
+ * Builds the OpenSearch descriptor document, which lets browsers offer
+ * Dashy as a keyword search engine, for jumping to items by their alias
+ */
+
+/* Must match the title on index.html's <link rel="search">, which browsers check on discovery */
+const SHORT_NAME = 'Dashy';
+
+/* Escape a value for safe inclusion in XML text or an attribute */
+const xmlEscape = (input) => String(input ?? '').replace(
+ /[<>&'"]/g,
+ (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', "'": '&apos;', '"': '&quot;' }[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);
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
+ <ShortName>${SHORT_NAME}</ShortName>
+ <Description>Jump to an app on ${title} by its alias</Description>
+ <InputEncoding>UTF-8</InputEncoding>
+ <Image width="16" height="16" type="image/x-icon">${origin}/favicon.ico</Image>
+ <Url type="text/html" method="get" template="${origin}/{searchTerms}"/>
+</OpenSearchDescription>
+`;
+};
diff --git a/src/components/LinkItems/Item.vue b/src/components/LinkItems/Item.vue
index b8cd2805..7b46d2a0 100644
--- a/src/components/LinkItems/Item.vue
+++ b/src/components/LinkItems/Item.vue
@@ -175,14 +175,16 @@ export default {
/* Returns configuration object for the tooltip */
getTooltipOptions() {
const {
- title, description, provider, hotkey,
+ title, description, provider, hotkey, alias,
} = this.item;
- if (!description && !provider && !this.titleTruncated) return {}; // Nothing to show
+ const hasShortcut = hotkey || alias;
+ if (!description && !provider && !hasShortcut && !this.titleTruncated) return {}; // Nothing to show
const 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`);
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.js
index b61360e8..3872fb99 100644
--- a/src/main.js
+++ b/src/main.js
@@ -72,8 +72,10 @@ const handleAuthFailure = (provider, err) => {
const needsOidcLoginPage = () => isOidcLoginPageEnabled() && !isLoggedIn()
&& router.currentRoute.value.name !== 'login';
-/* A guard can abort the first navigation (like an item alias redirect), leaving no route to render */
-const skipMount = () => {};
+/* 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);
+};
router.isReady().then(() => {
if (isOidcEnabled()) {
diff --git a/src/router.js b/src/router.js
index a71a9ae3..70246ae8 100644
--- a/src/router.js
+++ b/src/router.js
@@ -51,6 +51,16 @@ const resolveStartingView = () => {
return VIEW_META[view] ? view : 'home';
};
+/* True when a URL points back at the page we're already on, which would redirect forever */
+const isSelfReferential = (url) => {
+ try {
+ const target = new URL(url, window.location.href);
+ const path = (p) => p.replace(/\/+$/, '');
+ return target.origin === window.location.origin
+ && path(target.pathname) === path(window.location.pathname);
+ } catch { return false; }
+};
+
/* Build the canonical /<view>/:page?/:section? routes for a given view + component.
* withSection=false for workspace (no single-section view yet). Page meta is
* owned by App.vue's watcher via PageMeta.js β€” routes don't carry titles. */
@@ -129,9 +139,10 @@ const router = createRouter({
component: () => import('./views/404.vue'),
beforeEnter: (to, from, next) => {
const url = getUrlForAlias(store.state.rootConfig?.sections, to.params.alias);
- if (!url) { next('/404'); return; }
+ const loops = !!url && isSelfReferential(url);
+ if (loops) ErrorHandler(`Alias '${to.params.alias}' points back at itself, not redirecting`);
+ if (!url || loops) { next('/404'); return; }
window.location.replace(url);
- progress.end();
next(false);
},
},
diff --git a/tests/server/opensearch.test.js b/tests/server/opensearch.test.js
new file mode 100644
index 00000000..6e889ce3
--- /dev/null
+++ b/tests/server/opensearch.test.js
@@ -0,0 +1,63 @@
+// @vitest-environment node
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import { describe, it, expect } from 'vitest';
+import request from 'supertest';
+
+const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-opensearch-test-'));
+fs.writeFileSync(path.join(tmpDir, 'conf.yml'), "pageInfo:\n title: Alicia & Co's Very Long Dashboard\nsections: []\n");
+process.env.USER_DATA_DIR = tmpDir;
+
+const app = require('../../services/app');
+
+describe('OpenSearch descriptor', () => {
+ it('is served as an OpenSearch document', async () => {
+ const res = await request(app).get('/opensearch.xml');
+ expect(res.status).toBe(200);
+ expect(res.headers['content-type']).toMatch(/application\/opensearchdescription\+xml/);
+ });
+
+ it('builds the search template from the requesting host', async () => {
+ const res = await request(app).get('/opensearch.xml').set('Host', 'dash.lab.local');
+ expect(res.text).toContain('template="http://dash.lab.local/{searchTerms}"');
+ });
+
+ it('honours a reverse proxy\'s forwarded protocol and host', async () => {
+ const res = await request(app).get('/opensearch.xml')
+ .set('X-Forwarded-Proto', 'https').set('X-Forwarded-Host', 'dash.example.com');
+ expect(res.text).toContain('template="https://dash.example.com/{searchTerms}"');
+ });
+
+ it('takes the first value when a proxy chain sends a list', async () => {
+ const res = await request(app).get('/opensearch.xml')
+ .set('X-Forwarded-Proto', 'https, http').set('X-Forwarded-Host', 'outer.example.com, inner.local');
+ expect(res.text).toContain('template="https://outer.example.com/{searchTerms}"');
+ });
+
+ it('uses a ShortName matching the <link> title, so browsers accept the descriptor', async () => {
+ const res = await request(app).get('/opensearch.xml');
+ const indexHtml = fs.readFileSync(path.join(__dirname, '../../index.html'), 'utf8');
+ const linkTitle = indexHtml.match(/<link rel="search"[^>]*title="([^"]+)"/)[1];
+ expect(res.text).toContain(`<ShortName>${linkTitle}</ShortName>`);
+ });
+
+ it('escapes the configured title in the description', async () => {
+ const res = await request(app).get('/opensearch.xml');
+ expect(res.text).toContain('Alicia &amp; Co&apos;s Very Long Dashboard by its alias');
+ });
+
+ it.each([[2024, '2024'], [true, 'true'], [3.14, '3.14']])(
+ 'renders a title YAML coerced to the non-string %s', (title, expected) => {
+ const openSearch = require('../../services/endpoints/opensearch');
+ const xml = openSearch({ pageInfo: { title } }, { headers: { host: 'x.local' }, socket: {} });
+ expect(xml).toContain(`Jump to an app on ${expected} by its alias`);
+ },
+ );
+
+ it('escapes a hostile Host header rather than emitting raw XML', async () => {
+ const res = await request(app).get('/opensearch.xml').set('Host', 'evil"><script>x</script>');
+ expect(res.text).not.toContain('<script>');
+ expect(res.text).toContain('&quot;&gt;&lt;script&gt;');
+ });
+});
diff --git a/vite.config.mjs b/vite.config.mjs
index f24ec739..0ccceaee 100644
--- a/vite.config.mjs
+++ b/vite.config.mjs
@@ -74,7 +74,7 @@ export default defineConfig({
skipWaiting: false,
navigateFallback: '/index.html',
navigateFallbackDenylist: [
- /^\/(status-check|ping-check|system-info|cors-proxy|get-user|config-manager|schema)\b/,
+ /^\/(status-check|ping-check|system-info|cors-proxy|get-user|config-manager|schema|opensearch)\b/,
],
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,
globIgnores: [