From 816e0779802b1bdb198bed01057e45c36e0827f0 Mon Sep 17 00:00:00 2001 From: Olly Stedall Date: Wed, 2 Dec 2026 01:38:41 +0000 Subject: [PATCH 1/2] App Viewer: Add to Tronbyt - Add Tronbyt Server: enter your server's address and select Continue. The server opens in a new tab, you sign in if asked, and it comes straight back, confirming the address is a Tronbyt Server. The address is kept in this browser only. - Add to Tronbyt on each app (on the home page once a server is saved) opens the server's install page for that app, /apps//install, where you pick the device. Nothing is sent to the server except that link. - install/ pages: shareable install links that go straight to the app on the visitor's own server, or ask for the server first. Copy install link in the Add to Tronbyt button's menu (the share sheet on phones). - Server addresses are checked before opening: local addresses get http and port 8000 when none is given (19191 for umbrel.local). --- .gitignore | 1 + app-viewer/app.html | 45 ++- app-viewer/author.html | 45 ++- app-viewer/generate-apps-json.js | 20 + app-viewer/generate-apps-json.test.js | 8 + app-viewer/index.html | 45 ++- app-viewer/main-navigation.test.js | 16 + app-viewer/main.js | 514 +++++++++++++++++++++++++- app-viewer/server-url.js | 181 +++++++++ app-viewer/server-url.test.js | 196 ++++++++++ app-viewer/style.css | 232 ++++++++++++ 11 files changed, 1295 insertions(+), 8 deletions(-) create mode 100644 app-viewer/server-url.js create mode 100644 app-viewer/server-url.test.js diff --git a/.gitignore b/.gitignore index 4bf08fff5e..d4264d9fb3 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,7 @@ app-viewer/apps.json .claude/settings.local.json /app-viewer/details/ /app-viewer/authors/ +/app-viewer/install/ /app-viewer/cards/ /app-viewer/sitemap.xml /app-viewer/robots.txt diff --git a/app-viewer/app.html b/app-viewer/app.html index 14f3af3361..4b757addf5 100644 --- a/app-viewer/app.html +++ b/app-viewer/app.html @@ -12,7 +12,7 @@
- + diff --git a/app-viewer/author.html b/app-viewer/author.html index c4b945ca77..462e6e0100 100644 --- a/app-viewer/author.html +++ b/app-viewer/author.html @@ -12,7 +12,7 @@
-
+

@@ -20,6 +20,14 @@

App Viewer

+

← Back to Apps @@ -35,6 +43,41 @@

+ diff --git a/app-viewer/generate-apps-json.js b/app-viewer/generate-apps-json.js index e44a276674..3614bc42b0 100644 --- a/app-viewer/generate-apps-json.js +++ b/app-viewer/generate-apps-json.js @@ -155,6 +155,20 @@ export function appPageUrl(app) { return `${SITE_URL}details/${encodeURIComponent(app.name)}`; } +// "Add to my Tronbyt" link for an app: apps.tronbyt.com/install/. Anyone can share it. It is the app's details +// page, marked so the page carries on to adding the app: straight to the visitor's own Tronbyt Server's install page +// if one is verified in this browser (which only shows the app and asks which device), otherwise it asks for the +// server address first. Search engines are pointed at the details page. +export function installPageUrl(app) { + return `${SITE_URL}install/${encodeURIComponent(app.name)}`; +} + +export function markAsInstallPage(detailsHtml) { + return detailsHtml.replace('', ` + + `); +} + export function buildAppMetaTags(app, cardPath = SITE_CARD) { const name = app.displayName || app.name; const title = `${name} - Tronbyt App`; @@ -541,6 +555,12 @@ function generateHtmlFiles(apps, cards) {
`); writeFileSync(join(detailsDir, `${app.name}.html`), appHtml); } + + const installDir = join(outputDir, 'install'); + mkdirSync(installDir, { recursive: true }); + for (const app of apps) { + writeFileSync(join(installDir, `${app.name}.html`), markAsInstallPage(readFileSync(join(detailsDir, `${app.name}.html`), 'utf8'))); + } } function generateAuthorHtmlFiles(profiles, authorCards) { diff --git a/app-viewer/generate-apps-json.test.js b/app-viewer/generate-apps-json.test.js index 88f0143257..c55dcb87c6 100644 --- a/app-viewer/generate-apps-json.test.js +++ b/app-viewer/generate-apps-json.test.js @@ -7,6 +7,7 @@ import { buildAppMetaTags, buildAppPrerender, buildAuthorPrerender, + markAsInstallPage, buildSitemap, escapeHtmlAttribute, buildRobotsTxt, @@ -129,3 +130,10 @@ test('repoints a home page card tag from the old site address', () => { assert.equal(pointHomePageAtCard(html, 'cards/tronbyt-app-viewer-0123456789.png'), ''); }); + +test('install/ pages are the details page, marked to carry on to adding the app and kept out of search', () => { + const page = markAsInstallPage('Clock'); + assert.match(page, //); + assert.match(page, /\s*<\/head>/); + assert.match(page, /Clock<\/title>/); +}); diff --git a/app-viewer/index.html b/app-viewer/index.html index 60f427fca2..9b6b803542 100644 --- a/app-viewer/index.html +++ b/app-viewer/index.html @@ -29,7 +29,7 @@ <body> <div class="container py-4"> - <div class="viewer-header mb-4"> + <div class="viewer-header d-flex justify-content-between align-items-center mb-4"> <h1 class="main-title mb-0"> <a href="index.html" class="home-link" title="Tronbyt App Viewer home"> <img src="https://avatars.githubusercontent.com/u/200508996?s=48&v=4" alt=""> @@ -37,6 +37,14 @@ <h1 class="main-title mb-0"> <span class="title-short">App Viewer</span> </a> </h1> + <button type="button" + class="btn btn-secondary server-settings-button" + data-bs-toggle="modal" + data-bs-target="#tronbyt-server-modal" + title="Tronbyt Server settings"> + <span class="connection-icon" aria-hidden="true"></span> + <span id="tronbyt-settings-label">Add Tronbyt Server</span> + </button> </div> <div class="viewer-filters mb-4"> @@ -91,6 +99,41 @@ <h1 class="main-title mb-0"> <div id="apps-list" class="row g-4"></div> </div> + <div class="modal fade" id="tronbyt-server-modal" tabindex="-1" aria-labelledby="tronbyt-server-modal-title" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <form id="tronbyt-server-form"> + <div class="modal-header"> + <h2 class="modal-title fs-5" id="tronbyt-server-modal-title">Tronbyt Server</h2> + <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> + </div> + <div class="modal-body"> + <p class="server-intro">Install apps directly to your Tronbyt devices.</p> + <p class="server-requirement">Requires <a href="https://github.com/tronbyt/server/releases/" target="_blank" rel="noopener">Tronbyt Server v2.x.x</a> or later.</p> + <label for="tronbyt-server-url" class="form-label">Server address</label> + <input type="text" + inputmode="url" + class="form-control" + id="tronbyt-server-url" + autocomplete="url" + placeholder="e.g. 192.168.1.20:8000"> + <p class="server-help mt-3 mb-2">Enter your Tronbyt Server address above and select Continue. Your server opens in a new tab: sign in if asked, and it comes straight back to the App Viewer.</p> + <div class="connection-primary-actions"> + <div> + <button type="button" class="btn btn-secondary" id="clear-tronbyt-server">Clear</button> + <a class="btn btn-secondary" id="open-tronbyt-server" target="_blank" rel="noopener" hidden>Open Server</a> + </div> + <button type="submit" class="btn btn-success">Continue</button> + </div> + <div id="tronbyt-server-error" role="alert" aria-live="polite"></div> + <div id="connection-troubleshooting" class="connection-troubleshooting mt-3" hidden> + <p>Your Tronbyt Server hasn’t come back yet. Check the address is right and that you can sign in. If it showed its home page after you signed in, it needs updating to v2.x.x or later (if you’re not its admin, ask them).</p> + </div> + </div> + </form> + </div> + </div> + </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script type="module" src="main.js"></script> </body> diff --git a/app-viewer/main-navigation.test.js b/app-viewer/main-navigation.test.js index b0722b799d..1373bda238 100644 --- a/app-viewer/main-navigation.test.js +++ b/app-viewer/main-navigation.test.js @@ -35,6 +35,7 @@ globalThis.requestAnimationFrame = callback => { const { buildAppSourceUrl, filterAndSortApps, + installLinkUrl, normalizeCatalogueMetadata, rememberViewerScroll, restoreViewerScroll, @@ -184,3 +185,18 @@ test('the shared link is the page alone', () => { 'https://apps.tronbyt.com/authors/robert-ison' ); }); + +test('builds the install link from an app page address', () => { + assert.equal( + installLinkUrl('https://apps.tronbyt.com/details/uptime_kuma.html?display=wide&scroll=2109#readme'), + 'https://apps.tronbyt.com/install/uptime_kuma' + ); + assert.equal( + installLinkUrl('https://saltedlolly.github.io/tronbyt-apps/details/birthdays'), + 'https://saltedlolly.github.io/tronbyt-apps/install/birthdays' + ); + assert.equal( + installLinkUrl('https://apps.tronbyt.com/install/birthdays?add=1'), + 'https://apps.tronbyt.com/install/birthdays' + ); +}); diff --git a/app-viewer/main.js b/app-viewer/main.js index 4d024b38dd..5b612aa8e7 100644 --- a/app-viewer/main.js +++ b/app-viewer/main.js @@ -1,8 +1,19 @@ +import { + CONNECTION_MAX_AGE_MS, + TRONBYT_SERVER_STORAGE_KEY, + buildCommunityInstallUrl, + buildServerConnectionUrl, + connectionHelpDelay, + normalizeServerUrl, + parseStoredConnection, + serializeStoredConnection, + validateConnectionCallback +} from './server-url.js'; import { classifyReadmeImage, normalizeReadmeImageUrl } from './readme-images.js'; // --- CONFIG --- // Use GitHub Pages structure for both local and production -const isDetailsPage = window.location.pathname.includes('/details/'); +const isDetailsPage = window.location.pathname.includes('/details/') || window.location.pathname.includes('/install/'); const isAuthorPage = window.location.pathname.includes('/authors/'); const isNestedPage = isDetailsPage || isAuthorPage; const BASE_PATH = isNestedPage ? '../' : ''; @@ -14,6 +25,12 @@ const MD_FILES = ['README.md', 'readme.md', 'index.md']; const DEFAULT_SORT_ORDER = 'updated'; const APP_BATCH_SIZE = 60; const SEARCH_DEBOUNCE_MS = 150; +const PENDING_CONNECTION_STORAGE_KEY = 'tronbyt.apps.pendingConnection'; +// The app someone asked to add before a Tronbyt Server was verified; adding carries on once it is +let pendingAddApp = null; +// The one-off state of a Verify started in this tab: only that tab carries on to adding an app +let ownConnectionState = null; +let currentDetailApp = null; const VIEWER_STATE_PARAMS = ['q', 'category', 'display', 'sort', 'tag', 'hideBroken', 'count', 'scroll']; let appListObserver = null; @@ -67,7 +84,7 @@ export function tidyPageAddress() { const url = new URL(window.location.href); const viewerState = currentViewerState().toString(); VIEWER_STATE_PARAMS.forEach(name => url.searchParams.delete(name)); - url.pathname = url.pathname.replace(/\.html$/, ''); + url.pathname = url.pathname.replace(/\.html$/, '').replace(/\/open\/([^/]+)$/, '/details/$1'); if (url.href !== window.location.href || viewerState !== (window.history.state?.viewerState || '')) { window.history.replaceState({ ...(window.history.state || {}), viewerState }, '', url); } @@ -82,6 +99,67 @@ export function shareablePageUrl(href = window.location.href) { return url.href; } +// The app's install link (install/<app>), from its details page address: it carries on to installing the app on the +// visitor's own Tronbyt Server, or asks for the server first +export function installLinkUrl(href = window.location.href) { + const url = new URL(shareablePageUrl(href)); + url.pathname = url.pathname.replace(/\/(details|install)\/([^/]+)$/, '/install/$2'); + return url.href; +} + +// Add to Tronbyt on an app's page, with a ▾ that opens "Copy install link" (the share sheet on phones and tablets) +function createAddToTronbytSplitButton(app, isBroken) { + const addButton = createAddToTronbytButton(app, isBroken); + if (isBroken) return addButton; + + const group = document.createElement('div'); + group.className = 'btn-group add-to-tronbyt-group'; + + const toggle = document.createElement('button'); + toggle.type = 'button'; + toggle.className = 'btn btn-success dropdown-toggle dropdown-toggle-split add-to-tronbyt-more'; + toggle.dataset.bsToggle = 'dropdown'; + toggle.setAttribute('aria-expanded', 'false'); + toggle.title = 'More options: copy install link'; + const hiddenLabel = document.createElement('span'); + hiddenLabel.className = 'visually-hidden'; + hiddenLabel.textContent = 'More Add to Tronbyt options'; + toggle.appendChild(hiddenLabel); + + const useShareSheet = Boolean(navigator.share) && window.matchMedia('(pointer: coarse)').matches; + const menu = document.createElement('ul'); + menu.className = 'dropdown-menu dropdown-menu-dark dropdown-menu-end add-to-tronbyt-menu'; + const item = document.createElement('li'); + const linkButton = document.createElement('button'); + linkButton.type = 'button'; + linkButton.className = 'dropdown-item install-link-item'; + linkButton.title = 'A link that opens this app on anyone\'s own Tronbyt server, ready to install'; + setButtonContent(linkButton, '🔗', useShareSheet ? 'Share install link' : 'Copy install link'); + linkButton.addEventListener('click', async () => { + const url = installLinkUrl(); + if (useShareSheet) { + try { + await navigator.share({ title: `Install ${app.displayName || app.name} on your Tronbyt`, url }); + } catch { + // Cancelled + } + return; + } + try { + await navigator.clipboard.writeText(url); + setButtonContent(addButton, '✓', 'Install link copied'); + setTimeout(() => setButtonContent(addButton, '+', 'Add to Tronbyt'), 2000); + } catch { + window.prompt('Copy this install link:', url); + } + }); + item.appendChild(linkButton); + menu.appendChild(item); + + group.append(addButton, toggle, menu); + return group; +} + // Share goes on the same row as the Back to Apps button at the top of the page, on the right function placeShareButton(title) { const backToApps = document.querySelector('body > .container > a.btn-secondary'); @@ -138,6 +216,407 @@ export function restoreViewerScroll(scrollY) { // --- CACHE MANAGEMENT --- // Simple in-memory cache to avoid redundant network requests // Data persists only for this page lifetime; each page load revalidates it. +function getSavedTronbytConnection() { + try { + return parseStoredConnection(localStorage.getItem(TRONBYT_SERVER_STORAGE_KEY)); + } catch { + return null; + } +} + +function getSavedTronbytServer() { + return getSavedTronbytConnection()?.serverUrl || null; +} + +function setSavedTronbytServer(serverUrl) { + localStorage.setItem(TRONBYT_SERVER_STORAGE_KEY, serializeStoredConnection(serverUrl)); +} + +function clearSavedTronbytServer() { + localStorage.removeItem(TRONBYT_SERVER_STORAGE_KEY); +} + +function getPendingConnection() { + try { + const value = localStorage.getItem(PENDING_CONNECTION_STORAGE_KEY); + return value ? JSON.parse(value) : null; + } catch { + return null; + } +} + +function clearPendingConnection() { + localStorage.removeItem(PENDING_CONNECTION_STORAGE_KEY); +} + +function tronbytInstallUrl(app) { + const serverUrl = getSavedTronbytServer(); + return serverUrl ? buildCommunityInstallUrl(serverUrl, app.name, app.updated) : null; +} + +// Without a verified server, ask for one first; adding carries on in this tab once it's verified +function askForTronbytServer(app) { + pendingAddApp = app; + bootstrap.Modal.getOrCreateInstance(document.getElementById('tronbyt-server-modal')).show(); +} + +function openTronbytInstall(app) { + const installUrl = tronbytInstallUrl(app); + if (!installUrl) { + askForTronbytServer(app); + return; + } + + window.open(installUrl, '_blank', 'noopener'); +} + +// From an "Add to my Tronbyt" link (install/<app> sends people without a saved server here with ?add=1) +function addToTronbytFromLink(app) { + const url = new URL(window.location.href); + url.searchParams.delete('add'); + window.history.replaceState(window.history.state, '', url); + + const installUrl = tronbytInstallUrl(app); + if (installUrl) { + showOpeningOnTronbyt(app, installUrl); + } else { + askForTronbytServer(app); + } +} + +// Show the app's page for a moment, then carry on to the server (Back returns here) +function showOpeningOnTronbyt(app, installUrl) { + const notice = document.createElement('div'); + notice.className = 'alert alert-info opening-on-tronbyt'; + notice.setAttribute('role', 'status'); + const text = document.createElement('span'); + text.textContent = `Opening ${app.displayName || app.name} on your Tronbyt (${new URL(installUrl).host})…`; + const stay = document.createElement('button'); + stay.type = 'button'; + stay.className = 'btn btn-link btn-sm'; + stay.textContent = 'Stay here'; + notice.append(text, stay); + document.getElementById('app-content')?.prepend(notice); + + const timer = window.setTimeout(() => window.location.assign(installUrl), 1500); + stay.addEventListener('click', () => { + window.clearTimeout(timer); + notice.remove(); + }); +} + +function setButtonContent(button, icon, label) { + const iconElement = document.createElement('span'); + iconElement.className = 'button-icon'; + if (icon === '+') iconElement.classList.add('button-icon-text'); + iconElement.setAttribute('aria-hidden', 'true'); + iconElement.textContent = icon; + + const labelElement = document.createElement('span'); + labelElement.textContent = label; + button.replaceChildren(iconElement, labelElement); +} + +function setupResponsiveViewerTitle() { + const header = document.querySelector('.viewer-header'); + const title = header?.querySelector('.main-title'); + const serverButton = header?.querySelector('.server-settings-button'); + if (!header || !title || !serverButton || !title.querySelector('.title-full')) return; + + const titleMeasurer = title.cloneNode(true); + titleMeasurer.classList.add('title-measure'); + titleMeasurer.setAttribute('aria-hidden', 'true'); + header.appendChild(titleMeasurer); + + const updateTitle = () => { + const styles = window.getComputedStyle(header); + const gap = parseFloat(styles.columnGap || styles.gap) || 0; + const fullTitleWidth = titleMeasurer.getBoundingClientRect().width; + // The server button shrinks (a long address is cut short with "…"), so use its full width, but no more than + // 16rem: the full title is kept while the button still gets that much room. + const label = serverButton.querySelector('#tronbyt-settings-label'); + const fullButtonWidth = serverButton.getBoundingClientRect().width + + (label ? label.scrollWidth - label.clientWidth : 0); + const rem = parseFloat(window.getComputedStyle(document.documentElement).fontSize) || 16; + const serverButtonWidth = Math.min(fullButtonWidth, 16 * rem); + const needsShortTitle = fullTitleWidth + serverButtonWidth + gap > header.clientWidth; + header.classList.toggle('use-short-title', needsShortTitle); + }; + + const resizeObserver = new ResizeObserver(updateTitle); + resizeObserver.observe(header); + resizeObserver.observe(serverButton); + + const serverLabel = serverButton.querySelector('#tronbyt-settings-label'); + if (serverLabel) { + new MutationObserver(updateTitle).observe(serverLabel, { + childList: true, + characterData: true, + subtree: true + }); + } + + document.fonts?.ready?.then(updateTitle); + updateTitle(); +} + +function createAddToTronbytButton(app, isBroken) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'btn btn-success add-to-tronbyt-button tronbyt-install-action'; + setButtonContent(button, '+', 'Add to Tronbyt'); + button.disabled = isBroken; + if (isBroken) { + button.title = 'This app is currently marked as broken'; + } else { + button.addEventListener('click', () => openTronbytInstall(app)); + } + return button; +} + +function createConnectionState() { + const bytes = crypto.getRandomValues(new Uint8Array(18)); + return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); +} + +// Selecting Verify again for the same address reopens the server with the same one-time code, so a tab that's +// already open still works; a new address (or an expired check) starts a new one. +function beginTronbytConnection(serverUrl) { + let pending = getPendingConnection(); + const reusable = pending && pending.serverUrl === serverUrl && + typeof pending.createdAt === 'number' && Date.now() - pending.createdAt <= CONNECTION_MAX_AGE_MS; + if (!reusable) { + pending = { + state: createConnectionState(), + serverUrl, + returnPath: `${window.location.pathname}${window.location.search}${window.location.hash}`, + createdAt: Date.now() + }; + localStorage.setItem(PENDING_CONNECTION_STORAGE_KEY, JSON.stringify(pending)); + } + + window.open(buildServerConnectionUrl(serverUrl, pending.state), '_blank', 'noopener'); + return pending; +} + +function consumeTronbytConnectionCallback() { + const params = new URLSearchParams(window.location.search); + if (params.get('tronbyt_connection') !== 'confirmed') return null; + + const pending = getPendingConnection(); + const returnedState = params.get('state'); + const validation = validateConnectionCallback(pending, returnedState); + + if (!validation.valid) { + if (validation.clearPending) clearPendingConnection(); + return { error: 'This connection confirmation is invalid or has expired. Please select Continue again.' }; + } + + setSavedTronbytServer(pending.serverUrl); + clearPendingConnection(); + + const returnUrl = new URL(pending.returnPath || '/', window.location.origin); + if (returnUrl.origin !== window.location.origin) { + returnUrl.pathname = '/'; + returnUrl.search = ''; + returnUrl.hash = ''; + } + return { returnUrl: returnUrl.href }; +} + +function showConnectionComplete(returnUrl) { + const main = document.createElement('main'); + main.className = 'connection-complete'; + + const card = document.createElement('section'); + card.className = 'connection-complete-card'; + + const heading = document.createElement('h1'); + heading.textContent = 'Tronbyt Server verified'; + + const message = document.createElement('p'); + message.textContent = 'Your Tronbyt Server has been verified. You can now return to the Tronbyt App Viewer website.'; + + const link = document.createElement('a'); + link.className = 'btn btn-success'; + link.href = returnUrl; + link.textContent = 'Return to App Viewer'; + + card.append(heading, message, link); + main.append(card); + document.body.replaceChildren(main); +} + +function setupTronbytServerSettings() { + const modalElement = document.getElementById('tronbyt-server-modal'); + const form = document.getElementById('tronbyt-server-form'); + if (!modalElement || !form) return; + + const modal = bootstrap.Modal.getOrCreateInstance(modalElement); + const input = document.getElementById('tronbyt-server-url'); + const error = document.getElementById('tronbyt-server-error'); + const clearButton = document.getElementById('clear-tronbyt-server'); + const openButton = document.getElementById('open-tronbyt-server'); + const settingsLabel = document.getElementById('tronbyt-settings-label'); + const settingsButton = document.querySelector('.server-settings-button'); + const troubleshooting = document.getElementById('connection-troubleshooting'); + let troubleshootingTimer = null; + let waiting = false; + + const requiredElements = [ + input, + error, + clearButton, + openButton, + settingsLabel, + troubleshooting + ]; + if (requiredElements.some(element => !element)) { + console.warn('Tronbyt Server settings are unavailable because the page markup is incomplete.'); + return; + } + + function resetConnectionProgress() { + if (troubleshootingTimer) window.clearTimeout(troubleshootingTimer); + troubleshootingTimer = null; + troubleshooting.hidden = true; + waiting = false; + } + + function showPendingConnection(pending) { + resetConnectionProgress(); + waiting = true; + error.className = 'connection-status-pending'; + error.textContent = 'Waiting for your server. Sign in on the new tab if asked, and it comes straight back here. Closed the tab? Select Continue again.'; + + troubleshootingTimer = window.setTimeout(() => { + troubleshooting.hidden = false; + troubleshootingTimer = null; + }, connectionHelpDelay(pending.createdAt)); + } + + // Coming back to this tab with no confirmation usually means the server didn't return here (for example, an older + // server that shows its home page after sign-in), so explain at once rather than after the delay. A short wait lets + // a confirmation that is just arriving close the dialog first. + // Listen for both: a new tab hides this one; a new window (or a phone switching apps) may only take the focus. + function explainIfStillWaiting() { + if (document.visibilityState !== 'visible' || !waiting) return; + window.setTimeout(() => { + if (waiting && getPendingConnection()) { + if (troubleshootingTimer) window.clearTimeout(troubleshootingTimer); + troubleshootingTimer = null; + troubleshooting.hidden = false; + } + }, 750); + } + document.addEventListener('visibilitychange', explainIfStillWaiting); + window.addEventListener('focus', explainIfStillWaiting); + + function refreshSettings() { + const saved = getSavedTronbytServer(); + // App cards on the home page show Add to Tronbyt only once a server is verified (app pages always show it) + document.documentElement.classList.toggle('has-tronbyt-server', Boolean(saved)); + const pending = getPendingConnection(); + input.value = pending?.serverUrl || saved || ''; + openButton.hidden = !saved; + if (saved) { + openButton.href = saved; + const serverHost = new URL(saved).host; + settingsLabel.textContent = serverHost; + settingsButton?.setAttribute('aria-label', `Verified Tronbyt Server: ${serverHost}`); + settingsButton?.setAttribute('title', `Verified Tronbyt Server: ${serverHost}`); + settingsButton?.classList.add('connected'); + } else { + openButton.removeAttribute('href'); + settingsLabel.textContent = 'Add Tronbyt Server'; + settingsButton?.setAttribute('aria-label', 'Add Tronbyt Server'); + settingsButton?.setAttribute('title', 'Add Tronbyt Server'); + settingsButton?.classList.remove('connected'); + } + } + + // Opened to add an app (from an install link, or Add to Tronbyt with no server saved yet): the same dialog, with + // only the first line saying why it's asking + const intro = modalElement.querySelector('.server-intro'); + const defaultIntro = intro?.textContent; + + function showAddingCopy(app) { + const name = app ? app.displayName || app.name : null; + if (intro) { + intro.textContent = name + ? `To add ${name}, first add your Tronbyt Server. You only need to do this once in this browser.` + : defaultIntro; + } + } + + modalElement.addEventListener('show.bs.modal', () => { + showAddingCopy(pendingAddApp); + error.textContent = ''; + error.className = ''; + resetConnectionProgress(); + refreshSettings(); + + const pending = getPendingConnection(); + if (pending && typeof pending.createdAt === 'number' && + Date.now() - pending.createdAt <= CONNECTION_MAX_AGE_MS) { + showPendingConnection(pending); + } else if (pending) { + clearPendingConnection(); + } + }); + + form.addEventListener('submit', event => { + event.preventDefault(); + try { + const normalized = normalizeServerUrl(input.value); + input.value = normalized; + const pending = beginTronbytConnection(normalized); + ownConnectionState = pending.state; + showPendingConnection(pending); + } catch (validationError) { + resetConnectionProgress(); + error.className = 'connection-status-error'; + error.textContent = validationError.message; + } + }); + + clearButton.addEventListener('click', () => { + clearSavedTronbytServer(); + clearPendingConnection(); + resetConnectionProgress(); + error.textContent = ''; + error.className = ''; + refreshSettings(); + }); + + window.addEventListener('storage', event => { + if (event.key !== TRONBYT_SERVER_STORAGE_KEY || !event.newValue) return; + resetConnectionProgress(); + refreshSettings(); + modal.hide(); + // Carry on to adding an app only in the tab that asked for it and started this Verify + const installUrl = pendingAddApp && ownConnectionState && tronbytInstallUrl(pendingAddApp); + pendingAddApp = null; + ownConnectionState = null; + if (installUrl) window.location.assign(installUrl); + }); + + // The header button only manages the server: it never carries on to adding an app + settingsButton?.addEventListener('click', () => { + pendingAddApp = null; + }); + + modalElement.addEventListener('hidden.bs.modal', () => { + if (!getPendingConnection()) pendingAddApp = null; + }); + + refreshSettings(); +} + +// --- CACHE MANAGEMENT --- +// Simple in-memory cache to avoid redundant network requests +// Data persists for the duration of the browser session + const appCache = { appsList: null, brokenApps: null, @@ -403,11 +882,15 @@ function renderAppsList( // Create button - all apps should have details from manifest const button = document.createElement('a'); button.href = detailUrl; - button.className = 'btn btn-primary mt-auto'; - button.textContent = '📄 View Details'; + button.className = 'btn btn-primary'; + setButtonContent(button, '📄', 'View Details'); button.addEventListener('click', rememberViewerScroll); - cardBody.appendChild(button); + const actions = document.createElement('div'); + actions.className = 'card-actions mt-auto d-grid gap-2'; + actions.appendChild(button); + actions.appendChild(createAddToTronbytButton(app, isBroken)); + cardBody.appendChild(actions); // Assemble the card cardDiv.appendChild(imageContainer); @@ -751,6 +1234,7 @@ async function renderAppDetail() { // Get app data and check if app is broken const apps = await fetchAppsList(); const app = apps.find(a => a.name === appName); + currentDetailApp = app || null; if (!app) { const notFoundAlert = document.createElement('div'); @@ -1132,6 +1616,7 @@ async function renderAppDetail() { } reportContainer.appendChild(backButton); + rightActions.appendChild(createAddToTronbytSplitButton(app, isBroken)); rightActions.appendChild(reportControl); if (sourceLink) rightActions.appendChild(sourceLink); reportContainer.appendChild(rightActions); @@ -1394,6 +1879,20 @@ function createFilterSelect(id, label, options, selected) { // --- INIT --- document.addEventListener('DOMContentLoaded', async () => { + const connectionResult = consumeTronbytConnectionCallback(); + if (connectionResult?.returnUrl) { + window.close(); + window.setTimeout(() => showConnectionComplete(connectionResult.returnUrl), 150); + return; + } + setupTronbytServerSettings(); + setupResponsiveViewerTitle(); + if (connectionResult?.error) { + bootstrap.Modal.getOrCreateInstance(document.getElementById('tronbyt-server-modal')).show(); + const error = document.getElementById('tronbyt-server-error'); + error.className = 'connection-status-error'; + error.textContent = connectionResult.error; + } if (document.getElementById('author-content')) { // Author profile page tidyPageAddress(); @@ -1406,9 +1905,14 @@ document.addEventListener('DOMContentLoaded', async () => { setupDotMatrixToggle(); } else if (document.getElementById('app-content')) { // App detail page + const addRequested = new URLSearchParams(window.location.search).get('add') === '1' || + Boolean(document.querySelector('meta[name="tronbyt-install"]')); tidyPageAddress(); setupDotMatrixToggle(); await renderAppDetail(); + if (addRequested && currentDetailApp && !isAppBroken(currentDetailApp, appCache.brokenApps || [])) { + addToTronbytFromLink(currentDetailApp); + } } renderSiteFooter(); }); diff --git a/app-viewer/server-url.js b/app-viewer/server-url.js new file mode 100644 index 0000000000..e72b4aab20 --- /dev/null +++ b/app-viewer/server-url.js @@ -0,0 +1,181 @@ +export const TRONBYT_SERVER_STORAGE_KEY = 'tronbyt.apps.verifiedServerUrl'; +export const CONNECTION_MAX_AGE_MS = 10 * 60 * 1000; +export const CONNECTION_HELP_DELAY_MS = 20 * 1000; +export const DEFAULT_SERVER_PORT = '8000'; +// The Tronbyt app for Umbrel home servers (saltedlolly-tronbyt) serves on this port at umbrel.local +export const UMBREL_SERVER_PORT = '19191'; + +function defaultPortFor(hostname) { + const name = hostname.toLowerCase(); + return name === 'umbrel.local' || name === 'umbrel' ? UMBREL_SERVER_PORT : DEFAULT_SERVER_PORT; +} + +export function isLocalNetworkHostname(hostname) { + const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, ''); + if (normalized === 'localhost' || normalized.endsWith('.localhost') || + normalized.endsWith('.local') || normalized.endsWith('.home.arpa') || + !normalized.includes('.')) { + return true; + } + + const ipv4 = normalized.split('.').map(part => Number(part)); + if (ipv4.length === 4 && ipv4.every(part => Number.isInteger(part) && part >= 0 && part <= 255)) { + return ipv4[0] === 10 || + ipv4[0] === 127 || + (ipv4[0] === 169 && ipv4[1] === 254) || + (ipv4[0] === 172 && ipv4[1] >= 16 && ipv4[1] <= 31) || + (ipv4[0] === 192 && ipv4[1] === 168); + } + + return normalized === '::1' || + normalized.startsWith('fc') || + normalized.startsWith('fd') || + /^fe[89ab]/.test(normalized); +} + +// The port as typed ("" when none), checked before the browser rejects it with a vaguer message. +function typedPort(value) { + const hostAndPort = value.replace(/^https?:\/\//i, '').split(/[/?#]/)[0].split('@').pop(); + const match = hostAndPort.match(/(?:\]|^[^:\[]*):(.*)$/); + return match ? match[1] : ''; +} + +// The host as typed, before the browser tidies it up (it would turn "192.168.1" into "192.168.0.1"). +function typedHost(value) { + const host = value.replace(/^https?:\/\//i, '').split(/[/?#]/)[0].split('@').pop(); + if (host.startsWith('[')) return host.slice(0, host.indexOf(']') + 1); + return host.replace(/:\d*$/, ''); +} + +// A full IPv4 address, an IPv6 address in brackets, or a host name made of proper labels (letters, digits and +// hyphens (and underscores, which some local names use), not starting or ending with a hyphen). Names with dots need a top-level part that isn't only digits. +function isValidHost(host) { + if (!host) return false; + if (/^\[[a-f\d:.]+\]$/i.test(host)) return true; + if (/^[\d.]+$/.test(host)) { + const parts = host.split('.'); + return parts.length === 4 && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255); + } + const labels = host.split('.'); + if (labels.length > 1 && /^\d+$/.test(labels[labels.length - 1])) return false; + if (labels.length > 1 && labels[labels.length - 1].length < 2) return false; + return host.length <= 253 && + labels.every(label => /^[a-z\d_](?:[a-z\d_-]{0,61}[a-z\d_])?$/i.test(label)); +} + +export function normalizeServerUrl(value) { + const trimmed = value.trim(); + if (!trimmed) { + throw new Error('Enter your Tronbyt Server address.'); + } + + if (/^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) && !/^https?:\/\//i.test(trimmed)) { + throw new Error('The server address must use http:// or https://.'); + } + + // With no http:// or https:// typed, guess: a local-network address gets http and, if no port was given, Tronbyt + // Server's default port 8000 (as a plain local install runs), or 19191 for umbrel.local (the Umbrel app); + // anything else gets https. What was typed in full is + // kept as it is, and the guessed address is shown in the box, so it can be corrected. + const port = typedPort(trimmed); + // Only a numeric port gets this message: "javascript:alert(1)" also looks like a host and port. + if (/^\d+$/.test(port) && !(Number(port) >= 1 && Number(port) <= 65535)) { + throw new Error('The port must be a number from 1 to 65535, for example 192.168.1.20:8000.'); + } + + const typedScheme = /^https?:\/\//i.test(trimmed); + let url; + try { + url = new URL(typedScheme ? trimmed : `https://${trimmed}`); + if (!typedScheme && isLocalNetworkHostname(url.hostname)) { + url = new URL(`http://${trimmed}`); + if (!url.port) url.port = defaultPortFor(url.hostname); + } + } catch { + throw new Error('Enter a valid server address.'); + } + + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new Error('The server address must use http:// or https://.'); + } + if (!isValidHost(typedHost(trimmed)) || !isValidHost(url.hostname)) { + throw new Error('Enter a valid server address, such as 192.168.1.20, tronbyt.local or tronbyt.example.com.'); + } + if (url.username || url.password) { + throw new Error('Enter a server address without credentials.'); + } + if (url.protocol === 'http:' && !isLocalNetworkHostname(url.hostname)) { + throw new Error('Public Tronbyt Server addresses must use https://.'); + } + // Only the origin identifies a Tronbyt Server. This also lets someone paste + // a page they already have open, such as /auth/login, without correcting it. + return url.origin; +} + +// The server's install page for an app. `updated` (the app's last update, from its manifest) lets the server say +// when its own copy of the app store is older than the App Viewer's; it's only a hint, so a bad date is left out. +export function buildCommunityInstallUrl(serverUrl, appSlug, updated = null) { + if (!appSlug) { + throw new Error('An app identifier is required.'); + } + + const baseUrl = normalizeServerUrl(serverUrl); + const installUrl = new URL(`/apps/${encodeURIComponent(appSlug)}/install`, baseUrl); + const updatedMs = updated ? Date.parse(updated) : NaN; + if (Number.isFinite(updatedMs) && updatedMs > 0) { + installUrl.searchParams.set('updated', String(Math.floor(updatedMs / 1000))); + } + return installUrl.href; +} + +export function buildServerConnectionUrl(serverUrl, state) { + const baseUrl = normalizeServerUrl(serverUrl); + const connectionUrl = new URL('/integrations/apps-viewer/connect', baseUrl); + connectionUrl.searchParams.set('state', state); + return connectionUrl.href; +} + +// The saved server: its address and when it was checked. Anything else (unreadable, unsafe, never checked) is +// ignored, so the App Viewer simply asks for the server again. +export function parseStoredConnection(value) { + if (!value) return null; + try { + const parsed = JSON.parse(value); + if (!parsed || typeof parsed.serverUrl !== 'string' || typeof parsed.verifiedAt !== 'string' || + Number.isNaN(Date.parse(parsed.verifiedAt))) { + return null; + } + return { serverUrl: normalizeServerUrl(parsed.serverUrl), verifiedAt: parsed.verifiedAt }; + } catch { + return null; + } +} + +export function serializeStoredConnection(serverUrl, verifiedAt = new Date().toISOString()) { + return JSON.stringify({ serverUrl: normalizeServerUrl(serverUrl), verifiedAt }); +} + +export function validateConnectionCallback(pending, returnedState, now = Date.now()) { + if (!pending || typeof pending !== 'object' || typeof pending.state !== 'string') { + return { valid: false, clearPending: false, reason: 'missing' }; + } + if (pending.state !== returnedState) { + return { valid: false, clearPending: false, reason: 'state' }; + } + if (typeof pending.createdAt !== 'number' || now - pending.createdAt > CONNECTION_MAX_AGE_MS) { + return { valid: false, clearPending: true, reason: 'expired' }; + } + if (typeof pending.serverUrl !== 'string') { + return { valid: false, clearPending: true, reason: 'server' }; + } + try { + normalizeServerUrl(pending.serverUrl); + } catch { + return { valid: false, clearPending: true, reason: 'server' }; + } + return { valid: true, clearPending: true, reason: null }; +} + +export function connectionHelpDelay(createdAt, now = Date.now()) { + return Math.max(0, CONNECTION_HELP_DELAY_MS - (now - createdAt)); +} diff --git a/app-viewer/server-url.test.js b/app-viewer/server-url.test.js new file mode 100644 index 0000000000..15fa06a74e --- /dev/null +++ b/app-viewer/server-url.test.js @@ -0,0 +1,196 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + CONNECTION_HELP_DELAY_MS, + CONNECTION_MAX_AGE_MS, + buildCommunityInstallUrl, + buildServerConnectionUrl, + connectionHelpDelay, + isLocalNetworkHostname, + normalizeServerUrl, + parseStoredConnection, + serializeStoredConnection, + validateConnectionCallback +} from './server-url.js'; + +test('normalizes Tronbyt server addresses', () => { + assert.equal(normalizeServerUrl('https://umbrel.local:19191/'), 'https://umbrel.local:19191'); + assert.equal(normalizeServerUrl('http://192.168.1.20:8000'), 'http://192.168.1.20:8000'); +}); + +test('guesses http and the default port for a bare local address', () => { + assert.equal(normalizeServerUrl('192.168.1.20'), 'http://192.168.1.20:8000'); + assert.equal(normalizeServerUrl('tronbyt.local'), 'http://tronbyt.local:8000'); + assert.equal(normalizeServerUrl('localhost/auth/login'), 'http://localhost:8000'); + assert.equal(normalizeServerUrl('umbrel.local:19191'), 'http://umbrel.local:19191'); + // The Umbrel app's port + assert.equal(normalizeServerUrl('umbrel.local'), 'http://umbrel.local:19191'); + assert.equal(normalizeServerUrl('Umbrel.local/'), 'http://umbrel.local:19191'); + assert.equal(normalizeServerUrl('umbrel.local:8000'), 'http://umbrel.local:8000'); + // Typed in full: kept as it is + assert.equal(normalizeServerUrl('http://192.168.1.20'), 'http://192.168.1.20'); + assert.equal(normalizeServerUrl('https://tronbyt.local'), 'https://tronbyt.local'); + // Not local: https, no port added + assert.equal(normalizeServerUrl('tronbyt.example.com'), 'https://tronbyt.example.com'); +}); + +test('keeps full addresses', () => { + assert.equal( + normalizeServerUrl('http://192.168.1.20:19192/auth/login'), + 'http://192.168.1.20:19192' + ); + assert.equal( + normalizeServerUrl('https://umbrel.local:19191/devices/example?tab=apps#community'), + 'https://umbrel.local:19191' + ); +}); + +test('allows HTTP only for local-network server names and addresses', () => { + for (const hostname of [ + 'localhost', + 'tronbyt', + 'tronbyt.local', + 'tronbyt.home.arpa', + '127.0.0.1', + '10.0.0.5', + '172.16.0.5', + '172.31.255.254', + '192.168.1.20', + '169.254.1.2', + '[::1]', + '[fd00::20]', + '[fe80::20]' + ]) { + assert.equal(isLocalNetworkHostname(hostname), true, hostname); + assert.doesNotThrow(() => normalizeServerUrl(`http://${hostname}:19192`)); + } + + for (const hostname of ['example.com', '8.8.8.8', '172.32.0.1']) { + assert.equal(isLocalNetworkHostname(hostname), false, hostname); + assert.throws( + () => normalizeServerUrl(`http://${hostname}:19192`), + /must use https/ + ); + assert.doesNotThrow(() => normalizeServerUrl(`https://${hostname}:19192`)); + } +}); + +test('rejects unsafe addresses', () => { + assert.throws(() => normalizeServerUrl('javascript:alert(1)'), /valid server address|http:\/\/ or https:\/\//); + assert.throws(() => normalizeServerUrl('https://user:password@example.test'), /without credentials/); +}); + +test('asks for an address when the box is empty', () => { + assert.throws(() => normalizeServerUrl(''), /Enter your Tronbyt Server address/); + assert.throws(() => normalizeServerUrl(' '), /Enter your Tronbyt Server address/); +}); + +test('rejects malformed addresses instead of letting the browser guess', () => { + // The browser would turn these into 192.168.0.1 and 1.0.0.2 + for (const value of ['192.168.1', '1.2', '192.168.1.256', 'a..b', '-x.com', 'x-.local', 'x.c', 'host.123', 'foo bar']) { + assert.throws(() => normalizeServerUrl(value), /valid server address/, value); + } +}); + +test('rejects ports outside 1 to 65535', () => { + for (const value of ['192.168.1.20:0', '192.168.1.20:99999', 'https://tronbyt.example.com:70000']) { + assert.throws(() => normalizeServerUrl(value), /port must be a number from 1 to 65535/, value); + } + assert.throws(() => normalizeServerUrl('tronbyt.local:abc'), /valid server address/); +}); + +test('accepts usual server addresses, with or without a port', () => { + assert.equal(normalizeServerUrl('192.168.1.20'), 'http://192.168.1.20:8000'); + assert.equal(normalizeServerUrl('192.168.1.20:8080'), 'http://192.168.1.20:8080'); + assert.equal(normalizeServerUrl('tronbyt'), 'http://tronbyt:8000'); + assert.equal(normalizeServerUrl('My_Server.local'), 'http://my_server.local:8000'); + assert.equal(normalizeServerUrl('[fd00::1]:8000'), 'http://[fd00::1]:8000'); + assert.equal(normalizeServerUrl('tronbyt.example.com'), 'https://tronbyt.example.com'); + assert.equal(normalizeServerUrl('https://tronbyt.example.com:8443/'), 'https://tronbyt.example.com:8443'); +}); + +test('builds an encoded community install URL', () => { + assert.equal( + buildCommunityInstallUrl('https://umbrel.local:19191', 'solar beams'), + 'https://umbrel.local:19191/apps/solar%20beams/install' + ); +}); + +test("adds the app's last update to the install URL as Unix seconds, if it's a real date", () => { + assert.equal( + buildCommunityInstallUrl('https://umbrel.local:19191', 'clock', '2026-11-20T12:00:00Z'), + 'https://umbrel.local:19191/apps/clock/install?updated=1795176000' + ); + for (const updated of [null, '', 'soon', undefined]) { + assert.equal( + buildCommunityInstallUrl('https://umbrel.local:19191', 'clock', updated), + 'https://umbrel.local:19191/apps/clock/install' + ); + } +}); + +test('builds a server connection URL with one-time state', () => { + assert.equal( + buildServerConnectionUrl('http://umbrel.local:19192', 'test-state'), + 'http://umbrel.local:19192/integrations/apps-viewer/connect?state=test-state' + ); +}); + +test('stores the verification time with the address', () => { + const verifiedAt = '2026-10-02T12:00:00.000Z'; + const stored = serializeStoredConnection('http://umbrel.local:19192', verifiedAt); + assert.deepEqual(parseStoredConnection(stored), { serverUrl: 'http://umbrel.local:19192', verifiedAt }); +}); + +test('ignores malformed, unsafe or unchecked stored connections', () => { + assert.equal(parseStoredConnection('{not-json'), null); + assert.equal(parseStoredConnection('http://umbrel.local:19192'), null); + assert.equal(parseStoredConnection(JSON.stringify({ serverUrl: 'javascript:alert(1)', verifiedAt: '2026-10-02T12:00:00Z' })), null); + assert.equal(parseStoredConnection(JSON.stringify({ serverUrl: 'https://example.test' })), null); + assert.equal(parseStoredConnection(JSON.stringify({ serverUrl: 'https://example.test', verifiedAt: 'not-a-date' })), null); + // Saved by the demo before the protocol field was dropped: still fine + assert.equal( + parseStoredConnection(JSON.stringify({ serverUrl: 'https://example.test', protocol: 1, verifiedAt: '2026-10-02T12:00:00Z' })).serverUrl, + 'https://example.test' + ); +}); + +test('accepts a matching, current callback', () => { + const now = 1_000_000; + const pending = { + state: 'matching-state', + serverUrl: 'http://umbrel.local:19192', + createdAt: now - 1000 + }; + assert.deepEqual(validateConnectionCallback(pending, 'matching-state', now), { + valid: true, + clearPending: true, + reason: null + }); +}); + +test('rejects mismatched and expired callbacks', () => { + const now = 1_000_000; + const pending = { + state: 'expected-state', + serverUrl: 'http://umbrel.local:19192', + createdAt: now - 1000 + }; + + assert.equal(validateConnectionCallback(pending, 'other-state', now).reason, 'state'); + assert.equal(validateConnectionCallback(null, 'expected-state', now).reason, 'missing'); + assert.equal( + validateConnectionCallback({ ...pending, createdAt: now - CONNECTION_MAX_AGE_MS - 1 }, 'expected-state', now).reason, + 'expired' + ); + assert.equal(validateConnectionCallback({ ...pending, serverUrl: 'not a {host}' }, 'expected-state', now).reason, 'server'); +}); + +test('shows connection troubleshooting after the waiting period', () => { + const now = 1_000_000; + assert.equal(connectionHelpDelay(now, now), CONNECTION_HELP_DELAY_MS); + assert.equal(connectionHelpDelay(now - 5000, now), CONNECTION_HELP_DELAY_MS - 5000); + assert.equal(connectionHelpDelay(now - CONNECTION_HELP_DELAY_MS, now), 0); + assert.equal(connectionHelpDelay(now - CONNECTION_HELP_DELAY_MS - 5000, now), 0); +}); diff --git a/app-viewer/style.css b/app-viewer/style.css index 6aa33c6a45..0c864ba14c 100644 --- a/app-viewer/style.css +++ b/app-viewer/style.css @@ -8,7 +8,9 @@ body { .main-title { color: #ffd700; + flex: 0 0 auto; text-shadow: 2px 2px 0 #000; + white-space: nowrap; } .title-short { @@ -1167,9 +1169,20 @@ body.dot-matrix-enabled .app-readme img.readme-device-square { gap: 1rem; } + .detail-actions { + flex-wrap: wrap; + } + + .detail-actions > .add-to-tronbyt-button, + .detail-actions .add-to-tronbyt-group, + .detail-actions .add-to-tronbyt-group .add-to-tronbyt-button, .detail-actions .report-button { flex: 1 1 auto; } + + .detail-actions .add-to-tronbyt-group .add-to-tronbyt-more { + flex: 0 0 auto; + } } @media (max-width: 419px) { @@ -1215,6 +1228,30 @@ body.dot-matrix-enabled .app-readme img.readme-device-square { font-family: 'Press Start 2P', monospace; } +/* On the home page, app cards show Add to Tronbyt only once a Tronbyt Server is verified in this browser */ +html:not(.has-tronbyt-server) .card-actions .add-to-tronbyt-button { + display: none; +} + +/* Add to Tronbyt's ▾ (a full-height segment, easy to tap) and its menu */ +.add-to-tronbyt-group .add-to-tronbyt-button { + white-space: nowrap; +} + +.add-to-tronbyt-group .add-to-tronbyt-more { + border-left: 1px solid rgba(0, 0, 0, 0.35); + min-width: 2.75rem; +} + +.add-to-tronbyt-menu .dropdown-item { + align-items: center; + display: flex; + font-family: 'Press Start 2P', monospace; + font-size: 0.75rem; + gap: 0.65rem; + padding: 0.75rem 1rem; +} + .form-check-label { font-family: 'Press Start 2P', monospace; font-size: 0.8rem; @@ -1234,3 +1271,198 @@ body.dot-matrix-enabled .app-readme img.readme-device-square { .form-check-input:focus { box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25); } + +/* --- Add to Tronbyt: server connection --- */ +.modal-content { + background: #222; + border: 2px solid #444; + color: #e0e0e0; +} + +.modal-header, +.modal-footer { + border-color: #444; +} + +.modal .btn-close { + filter: invert(1); +} + +.viewer-header.use-short-title .title-full { + display: none; +} +.viewer-header.use-short-title .title-short { + display: inline; +} +.title-measure { + left: 0; + position: absolute; + top: 0; + visibility: hidden; + width: max-content; +} +.title-measure .title-full { + display: inline !important; +} +.title-measure .title-short { + display: none !important; +} +.server-settings-button { + align-items: center; + display: inline-flex; + gap: 0.65rem; + justify-content: center; + flex: 0 1 auto; + max-width: 28rem; + min-width: 0; + white-space: nowrap; +} +/* A long server address is cut short with "…" rather than running out of the button; the button's tooltip has it in full */ +#tronbyt-settings-label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} +.connection-icon { + display: inline-block; + flex: 0 0 21px; + height: 15px; + position: relative; + width: 21px; +} +.connection-icon::before { + background: currentColor; + box-shadow: + 3px 0 currentColor, + 6px 0 currentColor, + 9px 0 currentColor, + 12px 0 currentColor, + 15px 0 currentColor, + 9px -6px currentColor, + 12px -3px currentColor, + 12px 3px currentColor, + 9px 6px currentColor; + content: ''; + height: 3px; + left: 0; + position: absolute; + top: 6px; + width: 3px; +} +.server-settings-button.connected { + border-color: #00a950; + color: #8ff0b5; +} +.server-settings-button.connected .connection-icon::before { + box-shadow: + 3px 3px currentColor, + 6px 6px currentColor, + 9px 3px currentColor, + 12px 0 currentColor, + 15px -3px currentColor, + 18px -6px currentColor; +} +.server-intro { + color: #e0e0e0; + font-size: 0.75rem; + line-height: 1.6; + margin-bottom: 1.25rem; +} +.tronbyt-install-action[hidden] { + display: none !important; +} +.server-help { + color: #aaa; + font-size: 0.65rem; + line-height: 1.6; +} +.server-requirement { + color: #ffd761; + font-size: 0.65rem; + line-height: 1.6; + margin: -0.5rem 0 1.25rem; +} +.server-requirement a { + color: inherit; +} +#tronbyt-server-error { + font-size: 0.65rem; + line-height: 1.5; + margin-top: 1rem; +} +#tronbyt-server-error:empty { + display: none; +} +.connection-primary-actions { + align-items: center; + border-top: 1px solid #444; + display: flex; + gap: 1rem; + justify-content: space-between; + margin-top: 1.25rem; + padding-top: 1rem; +} +.connection-status-pending { + color: #ffd761; +} +.connection-status-error { + color: #ff6b6b; +} +.connection-status-success { + color: #8ff0b5; +} +.connection-troubleshooting { + border-top: 1px solid #444; + color: #aaa; + font-size: 0.65rem; + line-height: 1.5; + padding-top: 1rem; +} +.connection-complete { + align-items: center; + display: flex; + justify-content: center; + min-height: 100vh; + padding: 1.5rem; +} +.connection-complete-card { + background: #222; + border: 1px solid #444; + border-radius: 0.5rem; + box-shadow: 0 0.5rem 1.5rem rgb(0 0 0 / 30%); + max-width: 34rem; + padding: 1.5rem; + width: 100%; +} +.connection-complete-card p { + color: #ccc; + font-size: 0.75rem; + line-height: 1.6; +} +@container viewer-header (max-width: 52rem) { + .server-settings-button { + flex: 0 0 3.25rem; + height: 3.25rem; + padding: 0; + width: 3.25rem; + } + + #tronbyt-settings-label { + display: none; + } +} + +.opening-on-tronbyt { + align-items: center; + background: #1d2b1d; + border: 2px solid #3c6e3c; + color: #cfe8cf; + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + justify-content: space-between; +} + +.opening-on-tronbyt .btn-link { + color: #ffd866; +} From 5dbbd72f059d75565299e1e4965537aa24835b1d Mon Sep 17 00:00:00 2001 From: Olly Stedall <github-commits@saltedlolly.com> Date: Wed, 2 Dec 2026 03:02:33 +0000 Subject: [PATCH 2/2] Review fix: check IP addresses before local names (a public IPv6 address has no dots) --- app-viewer/server-url.js | 16 ++++++++-------- app-viewer/server-url.test.js | 3 ++- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/app-viewer/server-url.js b/app-viewer/server-url.js index e72b4aab20..02eef86a87 100644 --- a/app-viewer/server-url.js +++ b/app-viewer/server-url.js @@ -10,12 +10,13 @@ function defaultPortFor(hostname) { return name === 'umbrel.local' || name === 'umbrel' ? UMBREL_SERVER_PORT : DEFAULT_SERVER_PORT; } +// A loopback, private or link-local IP address, or a local name (localhost, .local, .home.arpa, or a single word). +// IP addresses are checked first, as a public IPv6 address has no dots either. export function isLocalNetworkHostname(hostname) { const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, ''); - if (normalized === 'localhost' || normalized.endsWith('.localhost') || - normalized.endsWith('.local') || normalized.endsWith('.home.arpa') || - !normalized.includes('.')) { - return true; + + if (normalized.includes(':')) { + return normalized === '::1' || /^f[cd]/.test(normalized) || /^fe[89ab]/.test(normalized); } const ipv4 = normalized.split('.').map(part => Number(part)); @@ -27,10 +28,9 @@ export function isLocalNetworkHostname(hostname) { (ipv4[0] === 192 && ipv4[1] === 168); } - return normalized === '::1' || - normalized.startsWith('fc') || - normalized.startsWith('fd') || - /^fe[89ab]/.test(normalized); + return normalized === 'localhost' || normalized.endsWith('.localhost') || + normalized.endsWith('.local') || normalized.endsWith('.home.arpa') || + !normalized.includes('.'); } // The port as typed ("" when none), checked before the browser rejects it with a vaguer message. diff --git a/app-viewer/server-url.test.js b/app-viewer/server-url.test.js index 15fa06a74e..3e1bba4f5a 100644 --- a/app-viewer/server-url.test.js +++ b/app-viewer/server-url.test.js @@ -66,7 +66,8 @@ test('allows HTTP only for local-network server names and addresses', () => { assert.doesNotThrow(() => normalizeServerUrl(`http://${hostname}:19192`)); } - for (const hostname of ['example.com', '8.8.8.8', '172.32.0.1']) { + // A public IPv6 address has no dots, but it isn't a local name + for (const hostname of ['example.com', '8.8.8.8', '172.32.0.1', '[2001:4860:4860::8888]']) { assert.equal(isLocalNetworkHostname(hostname), false, hostname); assert.throws( () => normalizeServerUrl(`http://${hostname}:19192`),