Compare commits
4
Commits
0d6f48ca24
...
b5e5bed7dd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5e5bed7dd | ||
|
|
74bd3c2e98 | ||
|
|
60c3bbcedb | ||
|
|
d07005bde3 |
@@ -153,10 +153,13 @@ Access your macros from outside your local network using a relay server:
|
|||||||
|
|
||||||
Once connected, a relay URL will appear in the toolbar. Use this URL from any device with internet access. The relay provides:
|
Once connected, a relay URL will appear in the toolbar. Use this URL from any device with internet access. The relay provides:
|
||||||
- Secure HTTPS connection
|
- Secure HTTPS connection
|
||||||
- Full macro execution and management
|
- Macro browsing and execution
|
||||||
- PWA installation support
|
- PWA installation support
|
||||||
- Wake lock and fullscreen mode
|
- Wake lock and fullscreen mode
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> The relay web client is **execute-only**: remote devices can browse and trigger macros, but macro creation/editing is intentionally limited to the local network (the desktop app and the local web interface). This keeps macro authoring — which defines what runs on your computer — off the public internet.
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> The relay password is stored in your OS keyring when one is available, falling back to the settings file (written with restricted `0600` permissions) otherwise.
|
> The relay password is stored in your OS keyring when one is available, falling back to the settings file (written with restricted `0600` permissions) otherwise.
|
||||||
|
|
||||||
|
|||||||
@@ -80,6 +80,19 @@ Set these in your container configuration:
|
|||||||
- `DATA_DIR` - Data storage path (default: ./data)
|
- `DATA_DIR` - Data storage path (default: ./data)
|
||||||
- `NODE_ENV` - production or development
|
- `NODE_ENV` - production or development
|
||||||
- `LOG_LEVEL` - info, debug, error
|
- `LOG_LEVEL` - info, debug, error
|
||||||
|
- `ALLOWED_ORIGINS` - Comma-separated list of allowed browser origins for the
|
||||||
|
WebSocket Origin check (e.g. `https://macropad.example.com`). **Set this to
|
||||||
|
your public origin(s) when running behind a reverse proxy** (see note below).
|
||||||
|
|
||||||
|
> **Reverse proxy note (`ALLOWED_ORIGINS`):** When `ALLOWED_ORIGINS` is unset,
|
||||||
|
> the WebSocket upgrade Origin check falls back to comparing the browser's
|
||||||
|
> `Origin` host against the raw `Host` header seen by the app. Behind a reverse
|
||||||
|
> proxy the internal `Host` (e.g. `localhost:3000`) often differs from the
|
||||||
|
> public origin the browser sends (e.g. `https://macropad.example.com`), so
|
||||||
|
> legitimate browser WebSocket upgrades get **rejected**. Set `ALLOWED_ORIGINS`
|
||||||
|
> to your public origin(s) to fix this. (Forwarding the public host via
|
||||||
|
> `proxy_set_header Host $host;`, as in the Nginx example below, also helps, but
|
||||||
|
> setting `ALLOWED_ORIGINS` explicitly is the reliable fix.)
|
||||||
|
|
||||||
## Test It Works
|
## Test It Works
|
||||||
|
|
||||||
|
|||||||
@@ -264,8 +264,8 @@
|
|||||||
<div class="wake-lock-status" id="wake-lock-status" title="Screen wake lock">
|
<div class="wake-lock-status" id="wake-lock-status" title="Screen wake lock">
|
||||||
<span class="wake-icon">☀</span>
|
<span class="wake-icon">☀</span>
|
||||||
</div>
|
</div>
|
||||||
<button class="header-btn icon-btn" onclick="app.toggleFullscreen()" title="Toggle fullscreen">⛶</button>
|
<button class="header-btn icon-btn" id="fullscreen-btn" title="Toggle fullscreen">⛶</button>
|
||||||
<button class="header-btn" onclick="app.refresh()">Refresh</button>
|
<button class="header-btn" id="refresh-btn">Refresh</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -277,372 +277,6 @@
|
|||||||
|
|
||||||
<div class="toast-container" id="toast-container"></div>
|
<div class="toast-container" id="toast-container"></div>
|
||||||
|
|
||||||
<script>
|
<script src="/static/app.js"></script>
|
||||||
// Inline MacroPad App for Relay Mode
|
|
||||||
class MacroPadApp {
|
|
||||||
constructor() {
|
|
||||||
this.macros = {};
|
|
||||||
this.tabs = [];
|
|
||||||
this.currentTab = 'All';
|
|
||||||
this.ws = null;
|
|
||||||
this.desktopConnected = false;
|
|
||||||
this.wsAuthenticated = false;
|
|
||||||
|
|
||||||
// Get session ID from URL
|
|
||||||
const pathMatch = window.location.pathname.match(/^\/([a-zA-Z0-9]+)/);
|
|
||||||
this.sessionId = pathMatch ? pathMatch[1] : null;
|
|
||||||
|
|
||||||
// Get password from storage (never from the URL).
|
|
||||||
this.password = sessionStorage.getItem(`macropad_${this.sessionId}`)
|
|
||||||
|| localStorage.getItem(`macropad_${this.sessionId}`);
|
|
||||||
|
|
||||||
if (this.password) {
|
|
||||||
sessionStorage.setItem(`macropad_${this.sessionId}`, this.password);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.init();
|
|
||||||
}
|
|
||||||
|
|
||||||
async init() {
|
|
||||||
this.wakeLock = null;
|
|
||||||
this.wakeLockEnabled = false;
|
|
||||||
|
|
||||||
this.setupPWA();
|
|
||||||
this.setupWebSocket();
|
|
||||||
this.setupEventListeners();
|
|
||||||
this.setupWakeLock();
|
|
||||||
}
|
|
||||||
|
|
||||||
getApiHeaders() {
|
|
||||||
return {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-MacroPad-Password': this.password || ''
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async loadTabs() {
|
|
||||||
try {
|
|
||||||
const response = await fetch(`/${this.sessionId}/api/tabs`, {
|
|
||||||
headers: this.getApiHeaders()
|
|
||||||
});
|
|
||||||
if (response.status === 401) return this.handleAuthError();
|
|
||||||
if (response.status === 503) return this.handleDesktopOffline();
|
|
||||||
const data = await response.json();
|
|
||||||
this.tabs = data.tabs || [];
|
|
||||||
this.renderTabs();
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error loading tabs:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async loadMacros() {
|
|
||||||
try {
|
|
||||||
const path = this.currentTab === 'All' ? '/api/macros' : `/api/macros/${encodeURIComponent(this.currentTab)}`;
|
|
||||||
const response = await fetch(`/${this.sessionId}${path}`, {
|
|
||||||
headers: this.getApiHeaders()
|
|
||||||
});
|
|
||||||
if (response.status === 401) return this.handleAuthError();
|
|
||||||
if (response.status === 503) return this.handleDesktopOffline();
|
|
||||||
const data = await response.json();
|
|
||||||
this.macros = data.macros || {};
|
|
||||||
this.renderMacros();
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error loading macros:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async executeMacro(macroId) {
|
|
||||||
const card = document.querySelector(`[data-macro-id="${macroId}"]`);
|
|
||||||
if (card) card.classList.add('executing');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch(`/${this.sessionId}/api/execute`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: this.getApiHeaders(),
|
|
||||||
body: JSON.stringify({ macro_id: macroId })
|
|
||||||
});
|
|
||||||
if (!response.ok) throw new Error('Failed');
|
|
||||||
} catch (error) {
|
|
||||||
this.showToast('Execution failed', 'error');
|
|
||||||
}
|
|
||||||
|
|
||||||
setTimeout(() => card?.classList.remove('executing'), 300);
|
|
||||||
}
|
|
||||||
|
|
||||||
handleAuthError() {
|
|
||||||
sessionStorage.removeItem(`macropad_${this.sessionId}`);
|
|
||||||
localStorage.removeItem(`macropad_${this.sessionId}`);
|
|
||||||
window.location.href = `/${this.sessionId}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
handleDesktopOffline() {
|
|
||||||
this.desktopConnected = false;
|
|
||||||
this.updateConnectionStatus(false);
|
|
||||||
document.getElementById('offline-banner').classList.add('visible');
|
|
||||||
}
|
|
||||||
|
|
||||||
setupWebSocket() {
|
|
||||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
||||||
const wsUrl = `${protocol}//${window.location.host}/${this.sessionId}/ws`;
|
|
||||||
|
|
||||||
this.ws = new WebSocket(wsUrl);
|
|
||||||
|
|
||||||
this.ws.onmessage = (event) => {
|
|
||||||
const data = JSON.parse(event.data);
|
|
||||||
this.handleMessage(data);
|
|
||||||
};
|
|
||||||
|
|
||||||
this.ws.onclose = () => {
|
|
||||||
this.wsAuthenticated = false;
|
|
||||||
this.updateConnectionStatus(false);
|
|
||||||
setTimeout(() => this.setupWebSocket(), 3000);
|
|
||||||
};
|
|
||||||
|
|
||||||
this.ws.onerror = () => this.updateConnectionStatus(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
handleMessage(data) {
|
|
||||||
switch (data.type) {
|
|
||||||
case 'auth_required':
|
|
||||||
if (this.password) {
|
|
||||||
this.ws.send(JSON.stringify({ type: 'auth', password: this.password }));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 'auth_response':
|
|
||||||
if (data.success) {
|
|
||||||
this.wsAuthenticated = true;
|
|
||||||
this.updateConnectionStatus(this.desktopConnected);
|
|
||||||
} else {
|
|
||||||
this.handleAuthError();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 'desktop_status':
|
|
||||||
this.desktopConnected = data.status === 'connected';
|
|
||||||
this.updateConnectionStatus(this.desktopConnected);
|
|
||||||
document.getElementById('offline-banner').classList.toggle('visible', !this.desktopConnected);
|
|
||||||
if (this.desktopConnected) {
|
|
||||||
this.loadTabs();
|
|
||||||
this.loadMacros();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 'macro_created':
|
|
||||||
case 'macro_updated':
|
|
||||||
case 'macro_deleted':
|
|
||||||
this.loadTabs();
|
|
||||||
this.loadMacros();
|
|
||||||
break;
|
|
||||||
case 'executed':
|
|
||||||
const card = document.querySelector(`[data-macro-id="${data.macro_id}"]`);
|
|
||||||
if (card) {
|
|
||||||
card.classList.add('executing');
|
|
||||||
setTimeout(() => card.classList.remove('executing'), 300);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
updateConnectionStatus(connected) {
|
|
||||||
const dot = document.querySelector('.status-dot');
|
|
||||||
const text = document.querySelector('.connection-status span');
|
|
||||||
if (dot) dot.classList.toggle('connected', connected);
|
|
||||||
if (text) text.textContent = connected ? 'Connected' : 'Disconnected';
|
|
||||||
}
|
|
||||||
|
|
||||||
renderTabs() {
|
|
||||||
const container = document.getElementById('tabs-container');
|
|
||||||
container.innerHTML = this.tabs.map(tab => `
|
|
||||||
<button class="tab ${tab === this.currentTab ? 'active' : ''}" data-tab="${tab}">${tab}</button>
|
|
||||||
`).join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
renderMacros() {
|
|
||||||
const container = document.getElementById('macro-grid');
|
|
||||||
const entries = Object.entries(this.macros);
|
|
||||||
|
|
||||||
if (entries.length === 0) {
|
|
||||||
container.innerHTML = '<div class="empty-state"><p>No macros found</p></div>';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
container.innerHTML = entries.map(([id, macro]) => {
|
|
||||||
const hasImage = !!macro.image_path;
|
|
||||||
const firstChar = macro.name.charAt(0).toUpperCase();
|
|
||||||
return `
|
|
||||||
<div class="macro-card" data-macro-id="${id}" onclick="app.executeMacro('${id}')">
|
|
||||||
${hasImage ? `<img class="macro-image" style="display:none">` : ''}
|
|
||||||
<div class="macro-image-placeholder">${firstChar}</div>
|
|
||||||
<span class="macro-name">${macro.name}</span>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
}).join('');
|
|
||||||
|
|
||||||
// Load macro images via authenticated fetch (header, not URL).
|
|
||||||
this.loadMacroImages();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch each macro image with the password header and display it
|
|
||||||
// as a blob object URL so the credential never appears in a URL.
|
|
||||||
async loadMacroImages() {
|
|
||||||
for (const [id, macro] of Object.entries(this.macros)) {
|
|
||||||
if (!macro.image_path) continue;
|
|
||||||
const card = document.querySelector(`[data-macro-id="${id}"]`);
|
|
||||||
if (!card) continue;
|
|
||||||
const img = card.querySelector('.macro-image');
|
|
||||||
if (!img) continue;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch(
|
|
||||||
`/${this.sessionId}/api/image/${macro.image_path}`,
|
|
||||||
{ headers: this.getApiHeaders() }
|
|
||||||
);
|
|
||||||
if (!response.ok) continue; // keep placeholder
|
|
||||||
const blob = await response.blob();
|
|
||||||
const objectUrl = URL.createObjectURL(blob);
|
|
||||||
img.onload = () => URL.revokeObjectURL(objectUrl);
|
|
||||||
img.src = objectUrl;
|
|
||||||
img.style.display = '';
|
|
||||||
const placeholder = img.nextElementSibling;
|
|
||||||
if (placeholder) placeholder.style.display = 'none';
|
|
||||||
} catch (error) {
|
|
||||||
// Leave the placeholder visible on failure.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setupEventListeners() {
|
|
||||||
document.getElementById('tabs-container').addEventListener('click', (e) => {
|
|
||||||
if (e.target.classList.contains('tab')) {
|
|
||||||
this.currentTab = e.target.dataset.tab;
|
|
||||||
this.renderTabs();
|
|
||||||
this.loadMacros();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
showToast(message, type = 'info') {
|
|
||||||
const container = document.getElementById('toast-container');
|
|
||||||
const toast = document.createElement('div');
|
|
||||||
toast.className = `toast ${type}`;
|
|
||||||
toast.textContent = message;
|
|
||||||
container.appendChild(toast);
|
|
||||||
setTimeout(() => toast.remove(), 3000);
|
|
||||||
}
|
|
||||||
|
|
||||||
refresh() {
|
|
||||||
this.loadTabs();
|
|
||||||
this.loadMacros();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fullscreen
|
|
||||||
toggleFullscreen() {
|
|
||||||
if (!document.fullscreenElement) {
|
|
||||||
document.documentElement.requestFullscreen().catch(err => {
|
|
||||||
console.log('Fullscreen error:', err);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
document.exitFullscreen();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wake Lock
|
|
||||||
async setupWakeLock() {
|
|
||||||
const status = document.getElementById('wake-lock-status');
|
|
||||||
|
|
||||||
if (!('wakeLock' in navigator)) {
|
|
||||||
console.log('Wake Lock API not supported');
|
|
||||||
if (status) {
|
|
||||||
status.classList.add('unsupported');
|
|
||||||
status.title = 'Wake lock not available (requires HTTPS)';
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status) {
|
|
||||||
status.style.cursor = 'pointer';
|
|
||||||
status.addEventListener('click', () => this.toggleWakeLock());
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.requestWakeLock();
|
|
||||||
|
|
||||||
document.addEventListener('visibilitychange', async () => {
|
|
||||||
if (document.visibilityState === 'visible' && this.wakeLockEnabled) {
|
|
||||||
await this.requestWakeLock();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async toggleWakeLock() {
|
|
||||||
if (this.wakeLock) {
|
|
||||||
await this.wakeLock.release();
|
|
||||||
this.wakeLock = null;
|
|
||||||
this.wakeLockEnabled = false;
|
|
||||||
this.updateWakeLockStatus(false);
|
|
||||||
this.showToast('Screen can now sleep', 'info');
|
|
||||||
} else {
|
|
||||||
this.wakeLockEnabled = true;
|
|
||||||
await this.requestWakeLock();
|
|
||||||
if (this.wakeLock) {
|
|
||||||
this.showToast('Screen will stay awake', 'success');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async requestWakeLock() {
|
|
||||||
try {
|
|
||||||
this.wakeLock = await navigator.wakeLock.request('screen');
|
|
||||||
this.wakeLockEnabled = true;
|
|
||||||
this.updateWakeLockStatus(true);
|
|
||||||
|
|
||||||
this.wakeLock.addEventListener('release', () => {
|
|
||||||
this.updateWakeLockStatus(false);
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.log('Wake Lock error:', err);
|
|
||||||
this.updateWakeLockStatus(false);
|
|
||||||
const status = document.getElementById('wake-lock-status');
|
|
||||||
if (status && !status.classList.contains('unsupported')) {
|
|
||||||
status.title = 'Wake lock failed: ' + err.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
updateWakeLockStatus(active) {
|
|
||||||
const status = document.getElementById('wake-lock-status');
|
|
||||||
if (status) {
|
|
||||||
status.classList.toggle('active', active);
|
|
||||||
if (!status.classList.contains('unsupported')) {
|
|
||||||
status.title = active ? 'Screen will stay on (click to toggle)' : 'Screen may sleep (click to enable)';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PWA manifest setup
|
|
||||||
setupPWA() {
|
|
||||||
// Create dynamic manifest for this session
|
|
||||||
const manifest = {
|
|
||||||
name: 'MacroPad',
|
|
||||||
short_name: 'MacroPad',
|
|
||||||
description: 'Remote macro control',
|
|
||||||
start_url: `/${this.sessionId}/app`,
|
|
||||||
display: 'standalone',
|
|
||||||
background_color: '#2e2e2e',
|
|
||||||
theme_color: '#007acc',
|
|
||||||
icons: [
|
|
||||||
{ src: '/static/icons/icon-192.png', sizes: '192x192', type: 'image/png' },
|
|
||||||
{ src: '/static/icons/icon-512.png', sizes: '512x512', type: 'image/png' }
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const blob = new Blob([JSON.stringify(manifest)], { type: 'application/json' });
|
|
||||||
const manifestUrl = URL.createObjectURL(blob);
|
|
||||||
document.getElementById('manifest-link').setAttribute('href', manifestUrl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let app;
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
|
||||||
app = new MacroPadApp();
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,420 @@
|
|||||||
|
// MacroPad App for Relay Mode (externalized so the CSP can drop
|
||||||
|
// 'unsafe-inline' for scripts). All macro/tab/id/name values are rendered
|
||||||
|
// with safe DOM APIs (createElement/textContent) and never via innerHTML.
|
||||||
|
class MacroPadApp {
|
||||||
|
constructor() {
|
||||||
|
this.macros = {};
|
||||||
|
this.tabs = [];
|
||||||
|
this.currentTab = 'All';
|
||||||
|
this.ws = null;
|
||||||
|
this.desktopConnected = false;
|
||||||
|
this.wsAuthenticated = false;
|
||||||
|
|
||||||
|
// Reconnect backoff. Reset only after a successful AUTH (not on
|
||||||
|
// socket open): a server that accepts the socket and then closes it
|
||||||
|
// would otherwise reset the backoff on every open and defeat it.
|
||||||
|
this.baseReconnectDelay = 3000;
|
||||||
|
this.maxReconnectDelay = 30000;
|
||||||
|
this.reconnectDelay = this.baseReconnectDelay;
|
||||||
|
|
||||||
|
// Get session ID from URL
|
||||||
|
const pathMatch = window.location.pathname.match(/^\/([a-zA-Z0-9]+)/);
|
||||||
|
this.sessionId = pathMatch ? pathMatch[1] : null;
|
||||||
|
|
||||||
|
// Get password from storage (never from the URL).
|
||||||
|
this.password = sessionStorage.getItem(`macropad_${this.sessionId}`)
|
||||||
|
|| localStorage.getItem(`macropad_${this.sessionId}`);
|
||||||
|
|
||||||
|
if (this.password) {
|
||||||
|
sessionStorage.setItem(`macropad_${this.sessionId}`, this.password);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
async init() {
|
||||||
|
this.wakeLock = null;
|
||||||
|
this.wakeLockEnabled = false;
|
||||||
|
|
||||||
|
this.setupPWA();
|
||||||
|
this.setupWebSocket();
|
||||||
|
this.setupEventListeners();
|
||||||
|
this.setupWakeLock();
|
||||||
|
}
|
||||||
|
|
||||||
|
getApiHeaders() {
|
||||||
|
return {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-MacroPad-Password': this.password || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadTabs() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/${this.sessionId}/api/tabs`, {
|
||||||
|
headers: this.getApiHeaders()
|
||||||
|
});
|
||||||
|
if (response.status === 401) return this.handleAuthError();
|
||||||
|
if (response.status === 503) return this.handleDesktopOffline();
|
||||||
|
const data = await response.json();
|
||||||
|
this.tabs = data.tabs || [];
|
||||||
|
this.renderTabs();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading tabs:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadMacros() {
|
||||||
|
try {
|
||||||
|
const path = this.currentTab === 'All' ? '/api/macros' : `/api/macros/${encodeURIComponent(this.currentTab)}`;
|
||||||
|
const response = await fetch(`/${this.sessionId}${path}`, {
|
||||||
|
headers: this.getApiHeaders()
|
||||||
|
});
|
||||||
|
if (response.status === 401) return this.handleAuthError();
|
||||||
|
if (response.status === 503) return this.handleDesktopOffline();
|
||||||
|
const data = await response.json();
|
||||||
|
this.macros = data.macros || {};
|
||||||
|
this.renderMacros();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading macros:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async executeMacro(macroId) {
|
||||||
|
const card = document.querySelector(`[data-macro-id="${macroId}"]`);
|
||||||
|
if (card) card.classList.add('executing');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/${this.sessionId}/api/execute`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: this.getApiHeaders(),
|
||||||
|
body: JSON.stringify({ macro_id: macroId })
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('Failed');
|
||||||
|
} catch (error) {
|
||||||
|
this.showToast('Execution failed', 'error');
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => card?.classList.remove('executing'), 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleAuthError() {
|
||||||
|
sessionStorage.removeItem(`macropad_${this.sessionId}`);
|
||||||
|
localStorage.removeItem(`macropad_${this.sessionId}`);
|
||||||
|
window.location.href = `/${this.sessionId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleDesktopOffline() {
|
||||||
|
this.desktopConnected = false;
|
||||||
|
this.updateConnectionStatus(false);
|
||||||
|
document.getElementById('offline-banner').classList.add('visible');
|
||||||
|
}
|
||||||
|
|
||||||
|
setupWebSocket() {
|
||||||
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
|
const wsUrl = `${protocol}//${window.location.host}/${this.sessionId}/ws`;
|
||||||
|
|
||||||
|
this.ws = new WebSocket(wsUrl);
|
||||||
|
|
||||||
|
this.ws.onmessage = (event) => {
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
this.handleMessage(data);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onclose = () => {
|
||||||
|
this.wsAuthenticated = false;
|
||||||
|
this.updateConnectionStatus(false);
|
||||||
|
// Reconnect using the current backoff, then grow it (capped) for
|
||||||
|
// the next attempt. The backoff is only reset on a successful
|
||||||
|
// auth response, so accept-then-close cycles keep backing off.
|
||||||
|
const delay = this.reconnectDelay;
|
||||||
|
this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay);
|
||||||
|
setTimeout(() => this.setupWebSocket(), delay);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onerror = () => this.updateConnectionStatus(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleMessage(data) {
|
||||||
|
switch (data.type) {
|
||||||
|
case 'auth_required':
|
||||||
|
if (this.password) {
|
||||||
|
this.ws.send(JSON.stringify({ type: 'auth', password: this.password }));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'auth_response':
|
||||||
|
if (data.success) {
|
||||||
|
this.wsAuthenticated = true;
|
||||||
|
// Reset the reconnect backoff only after a confirmed,
|
||||||
|
// successful auth (not merely on socket open).
|
||||||
|
this.reconnectDelay = this.baseReconnectDelay;
|
||||||
|
this.updateConnectionStatus(this.desktopConnected);
|
||||||
|
} else {
|
||||||
|
this.handleAuthError();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'desktop_status':
|
||||||
|
this.desktopConnected = data.status === 'connected';
|
||||||
|
this.updateConnectionStatus(this.desktopConnected);
|
||||||
|
document.getElementById('offline-banner').classList.toggle('visible', !this.desktopConnected);
|
||||||
|
if (this.desktopConnected) {
|
||||||
|
this.loadTabs();
|
||||||
|
this.loadMacros();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'macro_created':
|
||||||
|
case 'macro_updated':
|
||||||
|
case 'macro_deleted':
|
||||||
|
this.loadTabs();
|
||||||
|
this.loadMacros();
|
||||||
|
break;
|
||||||
|
case 'executed': {
|
||||||
|
const card = document.querySelector(`[data-macro-id="${data.macro_id}"]`);
|
||||||
|
if (card) {
|
||||||
|
card.classList.add('executing');
|
||||||
|
setTimeout(() => card.classList.remove('executing'), 300);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updateConnectionStatus(connected) {
|
||||||
|
const dot = document.querySelector('.status-dot');
|
||||||
|
const text = document.querySelector('.connection-status span');
|
||||||
|
if (dot) dot.classList.toggle('connected', connected);
|
||||||
|
if (text) text.textContent = connected ? 'Connected' : 'Disconnected';
|
||||||
|
}
|
||||||
|
|
||||||
|
renderTabs() {
|
||||||
|
const container = document.getElementById('tabs-container');
|
||||||
|
container.replaceChildren();
|
||||||
|
for (const tab of this.tabs) {
|
||||||
|
const name = typeof tab === 'string' ? tab : String(tab);
|
||||||
|
const btn = document.createElement('button');
|
||||||
|
btn.className = name === this.currentTab ? 'tab active' : 'tab';
|
||||||
|
btn.setAttribute('data-tab', name);
|
||||||
|
btn.textContent = name;
|
||||||
|
container.appendChild(btn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderMacros() {
|
||||||
|
const container = document.getElementById('macro-grid');
|
||||||
|
const entries = Object.entries(this.macros);
|
||||||
|
|
||||||
|
container.replaceChildren();
|
||||||
|
|
||||||
|
if (entries.length === 0) {
|
||||||
|
const empty = document.createElement('div');
|
||||||
|
empty.className = 'empty-state';
|
||||||
|
const p = document.createElement('p');
|
||||||
|
p.textContent = 'No macros found';
|
||||||
|
empty.appendChild(p);
|
||||||
|
container.appendChild(empty);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [id, macro] of entries) {
|
||||||
|
const name = macro && typeof macro.name === 'string' ? macro.name : '';
|
||||||
|
const hasImage = !!(macro && macro.image_path);
|
||||||
|
const firstChar = name.charAt(0).toUpperCase();
|
||||||
|
|
||||||
|
const card = document.createElement('div');
|
||||||
|
card.className = 'macro-card';
|
||||||
|
card.setAttribute('data-macro-id', id);
|
||||||
|
card.addEventListener('click', () => this.executeMacro(id));
|
||||||
|
|
||||||
|
if (hasImage) {
|
||||||
|
const img = document.createElement('img');
|
||||||
|
img.className = 'macro-image';
|
||||||
|
img.style.display = 'none';
|
||||||
|
card.appendChild(img);
|
||||||
|
}
|
||||||
|
|
||||||
|
const placeholder = document.createElement('div');
|
||||||
|
placeholder.className = 'macro-image-placeholder';
|
||||||
|
placeholder.textContent = firstChar;
|
||||||
|
card.appendChild(placeholder);
|
||||||
|
|
||||||
|
const nameSpan = document.createElement('span');
|
||||||
|
nameSpan.className = 'macro-name';
|
||||||
|
nameSpan.textContent = name;
|
||||||
|
card.appendChild(nameSpan);
|
||||||
|
|
||||||
|
container.appendChild(card);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load macro images via authenticated fetch (header, not URL).
|
||||||
|
this.loadMacroImages();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch each macro image with the password header and display it
|
||||||
|
// as a blob object URL so the credential never appears in a URL.
|
||||||
|
async loadMacroImages() {
|
||||||
|
for (const [id, macro] of Object.entries(this.macros)) {
|
||||||
|
if (!macro.image_path) continue;
|
||||||
|
const card = document.querySelector(`[data-macro-id="${id}"]`);
|
||||||
|
if (!card) continue;
|
||||||
|
const img = card.querySelector('.macro-image');
|
||||||
|
if (!img) continue;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`/${this.sessionId}/api/image/${macro.image_path}`,
|
||||||
|
{ headers: this.getApiHeaders() }
|
||||||
|
);
|
||||||
|
if (!response.ok) continue; // keep placeholder
|
||||||
|
const blob = await response.blob();
|
||||||
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
|
img.onload = () => URL.revokeObjectURL(objectUrl);
|
||||||
|
img.src = objectUrl;
|
||||||
|
img.style.display = '';
|
||||||
|
const placeholder = img.nextElementSibling;
|
||||||
|
if (placeholder) placeholder.style.display = 'none';
|
||||||
|
} catch (error) {
|
||||||
|
// Leave the placeholder visible on failure.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setupEventListeners() {
|
||||||
|
document.getElementById('tabs-container').addEventListener('click', (e) => {
|
||||||
|
if (e.target.classList.contains('tab')) {
|
||||||
|
this.currentTab = e.target.dataset.tab;
|
||||||
|
this.renderTabs();
|
||||||
|
this.loadMacros();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const fullscreenBtn = document.getElementById('fullscreen-btn');
|
||||||
|
if (fullscreenBtn) fullscreenBtn.addEventListener('click', () => this.toggleFullscreen());
|
||||||
|
|
||||||
|
const refreshBtn = document.getElementById('refresh-btn');
|
||||||
|
if (refreshBtn) refreshBtn.addEventListener('click', () => this.refresh());
|
||||||
|
}
|
||||||
|
|
||||||
|
showToast(message, type = 'info') {
|
||||||
|
const container = document.getElementById('toast-container');
|
||||||
|
const toast = document.createElement('div');
|
||||||
|
toast.className = `toast ${type}`;
|
||||||
|
toast.textContent = message;
|
||||||
|
container.appendChild(toast);
|
||||||
|
setTimeout(() => toast.remove(), 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
refresh() {
|
||||||
|
this.loadTabs();
|
||||||
|
this.loadMacros();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fullscreen
|
||||||
|
toggleFullscreen() {
|
||||||
|
if (!document.fullscreenElement) {
|
||||||
|
document.documentElement.requestFullscreen().catch(err => {
|
||||||
|
console.log('Fullscreen error:', err);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
document.exitFullscreen();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wake Lock
|
||||||
|
async setupWakeLock() {
|
||||||
|
const status = document.getElementById('wake-lock-status');
|
||||||
|
|
||||||
|
if (!('wakeLock' in navigator)) {
|
||||||
|
console.log('Wake Lock API not supported');
|
||||||
|
if (status) {
|
||||||
|
status.classList.add('unsupported');
|
||||||
|
status.title = 'Wake lock not available (requires HTTPS)';
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status) {
|
||||||
|
status.style.cursor = 'pointer';
|
||||||
|
status.addEventListener('click', () => this.toggleWakeLock());
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.requestWakeLock();
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', async () => {
|
||||||
|
if (document.visibilityState === 'visible' && this.wakeLockEnabled) {
|
||||||
|
await this.requestWakeLock();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async toggleWakeLock() {
|
||||||
|
if (this.wakeLock) {
|
||||||
|
await this.wakeLock.release();
|
||||||
|
this.wakeLock = null;
|
||||||
|
this.wakeLockEnabled = false;
|
||||||
|
this.updateWakeLockStatus(false);
|
||||||
|
this.showToast('Screen can now sleep', 'info');
|
||||||
|
} else {
|
||||||
|
this.wakeLockEnabled = true;
|
||||||
|
await this.requestWakeLock();
|
||||||
|
if (this.wakeLock) {
|
||||||
|
this.showToast('Screen will stay awake', 'success');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async requestWakeLock() {
|
||||||
|
try {
|
||||||
|
this.wakeLock = await navigator.wakeLock.request('screen');
|
||||||
|
this.wakeLockEnabled = true;
|
||||||
|
this.updateWakeLockStatus(true);
|
||||||
|
|
||||||
|
this.wakeLock.addEventListener('release', () => {
|
||||||
|
this.updateWakeLockStatus(false);
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.log('Wake Lock error:', err);
|
||||||
|
this.updateWakeLockStatus(false);
|
||||||
|
const status = document.getElementById('wake-lock-status');
|
||||||
|
if (status && !status.classList.contains('unsupported')) {
|
||||||
|
status.title = 'Wake lock failed: ' + err.message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updateWakeLockStatus(active) {
|
||||||
|
const status = document.getElementById('wake-lock-status');
|
||||||
|
if (status) {
|
||||||
|
status.classList.toggle('active', active);
|
||||||
|
if (!status.classList.contains('unsupported')) {
|
||||||
|
status.title = active ? 'Screen will stay on (click to toggle)' : 'Screen may sleep (click to enable)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PWA manifest setup
|
||||||
|
setupPWA() {
|
||||||
|
// Create dynamic manifest for this session
|
||||||
|
const manifest = {
|
||||||
|
name: 'MacroPad',
|
||||||
|
short_name: 'MacroPad',
|
||||||
|
description: 'Remote macro control',
|
||||||
|
start_url: `/${this.sessionId}/app`,
|
||||||
|
display: 'standalone',
|
||||||
|
background_color: '#2e2e2e',
|
||||||
|
theme_color: '#007acc',
|
||||||
|
icons: [
|
||||||
|
{ src: '/static/icons/icon-192.png', sizes: '192x192', type: 'image/png' },
|
||||||
|
{ src: '/static/icons/icon-512.png', sizes: '512x512', type: 'image/png' }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
const blob = new Blob([JSON.stringify(manifest)], { type: 'application/json' });
|
||||||
|
const manifestUrl = URL.createObjectURL(blob);
|
||||||
|
document.getElementById('manifest-link').setAttribute('href', manifestUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let app;
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
app = new MacroPadApp();
|
||||||
|
});
|
||||||
@@ -158,96 +158,6 @@
|
|||||||
<p class="status" id="status">Checking connection...</p>
|
<p class="status" id="status">Checking connection...</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script src="/static/login.js"></script>
|
||||||
const sessionId = window.location.pathname.split('/')[1];
|
|
||||||
const form = document.getElementById('loginForm');
|
|
||||||
const passwordInput = document.getElementById('password');
|
|
||||||
const rememberCheckbox = document.getElementById('remember');
|
|
||||||
const submitBtn = document.getElementById('submitBtn');
|
|
||||||
const errorDiv = document.getElementById('error');
|
|
||||||
const statusDiv = document.getElementById('status');
|
|
||||||
|
|
||||||
let desktopConnected = false;
|
|
||||||
|
|
||||||
// Check for saved password (session first, then "remembered" store)
|
|
||||||
const savedPassword = sessionStorage.getItem(`macropad_${sessionId}`)
|
|
||||||
|| localStorage.getItem(`macropad_${sessionId}`);
|
|
||||||
if (savedPassword) {
|
|
||||||
passwordInput.value = savedPassword;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Connect to WebSocket to check desktop status
|
|
||||||
function checkStatus() {
|
|
||||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
||||||
const ws = new WebSocket(`${protocol}//${window.location.host}/${sessionId}/ws`);
|
|
||||||
|
|
||||||
ws.onmessage = (event) => {
|
|
||||||
const data = JSON.parse(event.data);
|
|
||||||
if (data.type === 'desktop_status') {
|
|
||||||
desktopConnected = data.status === 'connected';
|
|
||||||
updateStatus();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
ws.onerror = () => {
|
|
||||||
statusDiv.textContent = 'Connection error';
|
|
||||||
statusDiv.className = 'status disconnected';
|
|
||||||
};
|
|
||||||
|
|
||||||
ws.onclose = () => {
|
|
||||||
setTimeout(checkStatus, 5000);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateStatus() {
|
|
||||||
if (desktopConnected) {
|
|
||||||
statusDiv.textContent = 'Desktop connected';
|
|
||||||
statusDiv.className = 'status connected';
|
|
||||||
submitBtn.disabled = false;
|
|
||||||
} else {
|
|
||||||
statusDiv.textContent = 'Desktop not connected';
|
|
||||||
statusDiv.className = 'status disconnected';
|
|
||||||
submitBtn.disabled = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
form.addEventListener('submit', async (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
errorDiv.style.display = 'none';
|
|
||||||
|
|
||||||
const password = passwordInput.value;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Test password with a simple API call
|
|
||||||
const response = await fetch(`/${sessionId}/api/tabs`, {
|
|
||||||
headers: {
|
|
||||||
'X-MacroPad-Password': password
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
// Hand the credential to the app via storage (never the URL).
|
|
||||||
sessionStorage.setItem(`macropad_${sessionId}`, password);
|
|
||||||
if (rememberCheckbox.checked) {
|
|
||||||
localStorage.setItem(`macropad_${sessionId}`, password);
|
|
||||||
} else {
|
|
||||||
localStorage.removeItem(`macropad_${sessionId}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redirect to the PWA (credential is read from storage).
|
|
||||||
window.location.href = `/${sessionId}/app`;
|
|
||||||
} else {
|
|
||||||
const data = await response.json();
|
|
||||||
errorDiv.textContent = data.error || 'Invalid password';
|
|
||||||
errorDiv.style.display = 'block';
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
errorDiv.textContent = 'Connection failed';
|
|
||||||
errorDiv.style.display = 'block';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
checkStatus();
|
|
||||||
</script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
// MacroPad login page logic (externalized so the CSP can drop 'unsafe-inline'
|
||||||
|
// for scripts).
|
||||||
|
const sessionId = window.location.pathname.split('/')[1];
|
||||||
|
const form = document.getElementById('loginForm');
|
||||||
|
const passwordInput = document.getElementById('password');
|
||||||
|
const rememberCheckbox = document.getElementById('remember');
|
||||||
|
const submitBtn = document.getElementById('submitBtn');
|
||||||
|
const errorDiv = document.getElementById('error');
|
||||||
|
const statusDiv = document.getElementById('status');
|
||||||
|
|
||||||
|
let desktopConnected = false;
|
||||||
|
|
||||||
|
// Check for saved password (session first, then "remembered" store)
|
||||||
|
const savedPassword = sessionStorage.getItem(`macropad_${sessionId}`)
|
||||||
|
|| localStorage.getItem(`macropad_${sessionId}`);
|
||||||
|
if (savedPassword) {
|
||||||
|
passwordInput.value = savedPassword;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect to WebSocket to check desktop status
|
||||||
|
function checkStatus() {
|
||||||
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
|
const ws = new WebSocket(`${protocol}//${window.location.host}/${sessionId}/ws`);
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
if (data.type === 'desktop_status') {
|
||||||
|
desktopConnected = data.status === 'connected';
|
||||||
|
updateStatus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onerror = () => {
|
||||||
|
statusDiv.textContent = 'Connection error';
|
||||||
|
statusDiv.className = 'status disconnected';
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onclose = () => {
|
||||||
|
setTimeout(checkStatus, 5000);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateStatus() {
|
||||||
|
if (desktopConnected) {
|
||||||
|
statusDiv.textContent = 'Desktop connected';
|
||||||
|
statusDiv.className = 'status connected';
|
||||||
|
submitBtn.disabled = false;
|
||||||
|
} else {
|
||||||
|
statusDiv.textContent = 'Desktop not connected';
|
||||||
|
statusDiv.className = 'status disconnected';
|
||||||
|
submitBtn.disabled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
form.addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
errorDiv.style.display = 'none';
|
||||||
|
|
||||||
|
const password = passwordInput.value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Test password with a simple API call
|
||||||
|
const response = await fetch(`/${sessionId}/api/tabs`, {
|
||||||
|
headers: {
|
||||||
|
'X-MacroPad-Password': password
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
// Hand the credential to the app via storage (never the URL).
|
||||||
|
sessionStorage.setItem(`macropad_${sessionId}`, password);
|
||||||
|
if (rememberCheckbox.checked) {
|
||||||
|
localStorage.setItem(`macropad_${sessionId}`, password);
|
||||||
|
} else {
|
||||||
|
localStorage.removeItem(`macropad_${sessionId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect to the PWA (credential is read from storage).
|
||||||
|
window.location.href = `/${sessionId}/app`;
|
||||||
|
} else {
|
||||||
|
const data = await response.json();
|
||||||
|
errorDiv.textContent = data.error || 'Invalid password';
|
||||||
|
errorDiv.style.display = 'block';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
errorDiv.textContent = 'Connection failed';
|
||||||
|
errorDiv.style.display = 'block';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
checkStatus();
|
||||||
@@ -12,26 +12,22 @@ export function createApiProxy(
|
|||||||
return async (req: Request, res: Response, next: NextFunction) => {
|
return async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const sessionId = req.params.sessionId;
|
const sessionId = req.params.sessionId;
|
||||||
|
|
||||||
// Check session exists
|
|
||||||
const session = sessionManager.getSession(sessionId);
|
|
||||||
if (!session) {
|
|
||||||
return res.status(404).json({ error: 'Session not found' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Credentials must be supplied via the header (never the URL/query,
|
// Credentials must be supplied via the header (never the URL/query,
|
||||||
// which leaks into logs, history and referrers).
|
// which leaks into logs, history and referrers).
|
||||||
const password = req.headers['x-macropad-password'] as string;
|
const password = req.headers['x-macropad-password'] as string;
|
||||||
|
|
||||||
if (!password) {
|
// Uniform auth failure. A missing session, a missing password, and a
|
||||||
return res.status(401).json({ error: 'Password required' });
|
// wrong password all return the SAME status + generic message so a
|
||||||
|
// caller cannot infer whether a given session id exists (no
|
||||||
|
// enumeration oracle). validatePassword() safely returns false for an
|
||||||
|
// unknown session id.
|
||||||
|
if (!password || !(await sessionManager.validatePassword(sessionId, password))) {
|
||||||
|
return res.status(401).json({ error: 'Authentication failed' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const valid = await sessionManager.validatePassword(sessionId, password);
|
// Only AFTER successful auth do we reveal desktop connectivity, so the
|
||||||
if (!valid) {
|
// 503 "not connected" signal cannot itself be used to probe which
|
||||||
return res.status(401).json({ error: 'Invalid password' });
|
// session ids exist.
|
||||||
}
|
|
||||||
|
|
||||||
// Check desktop is connected
|
|
||||||
const desktop = connectionManager.getDesktopBySessionId(sessionId);
|
const desktop = connectionManager.getDesktopBySessionId(sessionId);
|
||||||
if (!desktop) {
|
if (!desktop) {
|
||||||
return res.status(503).json({ error: 'Desktop not connected' });
|
return res.status(503).json({ error: 'Desktop not connected' });
|
||||||
|
|||||||
@@ -37,7 +37,8 @@ type DesktopMessage = AuthMessage | ApiResponseMessage | WsBroadcastMessage | Po
|
|||||||
export function handleDesktopConnection(
|
export function handleDesktopConnection(
|
||||||
socket: WebSocket,
|
socket: WebSocket,
|
||||||
connectionManager: ConnectionManager,
|
connectionManager: ConnectionManager,
|
||||||
sessionManager: SessionManager
|
sessionManager: SessionManager,
|
||||||
|
clientIp: string
|
||||||
): void {
|
): void {
|
||||||
let authenticatedSessionId: string | null = null;
|
let authenticatedSessionId: string | null = null;
|
||||||
// Track failed auth attempts on this individual socket.
|
// Track failed auth attempts on this individual socket.
|
||||||
@@ -49,7 +50,7 @@ export function handleDesktopConnection(
|
|||||||
|
|
||||||
switch (message.type) {
|
switch (message.type) {
|
||||||
case 'auth': {
|
case 'auth': {
|
||||||
const failed = await handleAuth(socket, message, sessionManager, connectionManager, (sessionId) => {
|
const failed = await handleAuth(socket, message, sessionManager, connectionManager, clientIp, (sessionId) => {
|
||||||
authenticatedSessionId = sessionId;
|
authenticatedSessionId = sessionId;
|
||||||
});
|
});
|
||||||
if (failed) {
|
if (failed) {
|
||||||
@@ -110,6 +111,7 @@ async function handleAuth(
|
|||||||
message: AuthMessage,
|
message: AuthMessage,
|
||||||
sessionManager: SessionManager,
|
sessionManager: SessionManager,
|
||||||
connectionManager: ConnectionManager,
|
connectionManager: ConnectionManager,
|
||||||
|
clientIp: string,
|
||||||
setSessionId: (id: string) => void
|
setSessionId: (id: string) => void
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
@@ -117,8 +119,14 @@ async function handleAuth(
|
|||||||
let session;
|
let session;
|
||||||
|
|
||||||
if (sessionId) {
|
if (sessionId) {
|
||||||
// Reject early if this session id is currently locked out.
|
// Namespace the brute-force lockout key to the desktop keyspace and
|
||||||
const lockRemaining = getLockoutRemaining(sessionId);
|
// include the client IP. This keeps the desktop's lockout state entirely
|
||||||
|
// separate from the web-client keyspace, so a web-auth flood can never
|
||||||
|
// lock the desktop out of (re)authenticating.
|
||||||
|
const throttleKey = `desktop:${sessionId}:${clientIp}`;
|
||||||
|
|
||||||
|
// Reject early if this key is currently locked out.
|
||||||
|
const lockRemaining = getLockoutRemaining(throttleKey);
|
||||||
if (lockRemaining > 0) {
|
if (lockRemaining > 0) {
|
||||||
socket.send(JSON.stringify({
|
socket.send(JSON.stringify({
|
||||||
type: 'auth_response',
|
type: 'auth_response',
|
||||||
@@ -132,7 +140,7 @@ async function handleAuth(
|
|||||||
// Validate existing session
|
// Validate existing session
|
||||||
const valid = await sessionManager.validatePassword(sessionId, message.password);
|
const valid = await sessionManager.validatePassword(sessionId, message.password);
|
||||||
if (!valid) {
|
if (!valid) {
|
||||||
recordFailure(sessionId);
|
recordFailure(throttleKey);
|
||||||
socket.send(JSON.stringify({
|
socket.send(JSON.stringify({
|
||||||
type: 'auth_response',
|
type: 'auth_response',
|
||||||
success: false,
|
success: false,
|
||||||
@@ -140,7 +148,7 @@ async function handleAuth(
|
|||||||
}));
|
}));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
recordSuccess(sessionId);
|
recordSuccess(throttleKey);
|
||||||
session = sessionManager.getSession(sessionId);
|
session = sessionManager.getSession(sessionId);
|
||||||
} else {
|
} else {
|
||||||
// Create new session (may throw on limit / short password)
|
// Create new session (may throw on limit / short password)
|
||||||
|
|||||||
@@ -25,33 +25,26 @@ export function handleWebClientConnection(
|
|||||||
socket: WebSocket,
|
socket: WebSocket,
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
connectionManager: ConnectionManager,
|
connectionManager: ConnectionManager,
|
||||||
sessionManager: SessionManager
|
sessionManager: SessionManager,
|
||||||
|
clientIp: string
|
||||||
): void {
|
): void {
|
||||||
// Check if session exists
|
// Namespace the brute-force lockout key to the web keyspace and include the
|
||||||
const session = sessionManager.getSession(sessionId);
|
// client IP. This prevents one abusive IP (which knows the shareable session
|
||||||
if (!session) {
|
// id) from locking out other web clients or the desktop for this session.
|
||||||
socket.send(JSON.stringify({
|
const throttleKey = `web:${sessionId}:${clientIp}`;
|
||||||
type: 'error',
|
|
||||||
error: 'Session not found'
|
|
||||||
}));
|
|
||||||
socket.close();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add client (not authenticated yet)
|
// Do NOT reveal whether the session exists. A non-existent session id and
|
||||||
|
// an existing one must be indistinguishable to an unauthenticated client so
|
||||||
|
// session ids cannot be enumerated: we always run the same handshake and let
|
||||||
|
// the (uniform) auth response be the only signal. validatePassword() safely
|
||||||
|
// returns false for an unknown session id, and desktop connectivity is only
|
||||||
|
// disclosed AFTER a successful auth (see the 'auth' case below).
|
||||||
const client = connectionManager.addWebClient(sessionId, socket, false);
|
const client = connectionManager.addWebClient(sessionId, socket, false);
|
||||||
|
|
||||||
// Track failed auth attempts on this individual socket.
|
// Track failed auth attempts on this individual socket.
|
||||||
let socketAuthFailures = 0;
|
let socketAuthFailures = 0;
|
||||||
|
|
||||||
// Check if desktop is connected
|
// Request authentication.
|
||||||
const desktop = connectionManager.getDesktopBySessionId(sessionId);
|
|
||||||
socket.send(JSON.stringify({
|
|
||||||
type: 'desktop_status',
|
|
||||||
status: desktop ? 'connected' : 'disconnected'
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Request authentication
|
|
||||||
socket.send(JSON.stringify({
|
socket.send(JSON.stringify({
|
||||||
type: 'auth_required'
|
type: 'auth_required'
|
||||||
}));
|
}));
|
||||||
@@ -62,7 +55,7 @@ export function handleWebClientConnection(
|
|||||||
|
|
||||||
switch (message.type) {
|
switch (message.type) {
|
||||||
case 'auth': {
|
case 'auth': {
|
||||||
const failed = await handleAuth(socket, client, message, sessionId, sessionManager);
|
const failed = await handleAuth(socket, client, message, sessionId, sessionManager, throttleKey);
|
||||||
if (failed) {
|
if (failed) {
|
||||||
socketAuthFailures++;
|
socketAuthFailures++;
|
||||||
if (socketAuthFailures >= config.authMaxSocketFailures) {
|
if (socketAuthFailures >= config.authMaxSocketFailures) {
|
||||||
@@ -71,6 +64,12 @@ export function handleWebClientConnection(
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
socketAuthFailures = 0;
|
socketAuthFailures = 0;
|
||||||
|
// Authenticated: only now do we disclose desktop connectivity.
|
||||||
|
const desktop = connectionManager.getDesktopBySessionId(sessionId);
|
||||||
|
socket.send(JSON.stringify({
|
||||||
|
type: 'desktop_status',
|
||||||
|
status: desktop ? 'connected' : 'disconnected'
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -106,10 +105,11 @@ async function handleAuth(
|
|||||||
client: WebClientConnection,
|
client: WebClientConnection,
|
||||||
message: AuthMessage,
|
message: AuthMessage,
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
sessionManager: SessionManager
|
sessionManager: SessionManager,
|
||||||
|
throttleKey: string
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
// Reject early if this session id is currently locked out.
|
// Reject early if this key is currently locked out.
|
||||||
const lockRemaining = getLockoutRemaining(sessionId);
|
const lockRemaining = getLockoutRemaining(throttleKey);
|
||||||
if (lockRemaining > 0) {
|
if (lockRemaining > 0) {
|
||||||
socket.send(JSON.stringify({
|
socket.send(JSON.stringify({
|
||||||
type: 'auth_response',
|
type: 'auth_response',
|
||||||
@@ -123,7 +123,7 @@ async function handleAuth(
|
|||||||
const valid = await sessionManager.validatePassword(sessionId, message.password);
|
const valid = await sessionManager.validatePassword(sessionId, message.password);
|
||||||
|
|
||||||
if (valid) {
|
if (valid) {
|
||||||
recordSuccess(sessionId);
|
recordSuccess(throttleKey);
|
||||||
client.authenticated = true;
|
client.authenticated = true;
|
||||||
socket.send(JSON.stringify({
|
socket.send(JSON.stringify({
|
||||||
type: 'auth_response',
|
type: 'auth_response',
|
||||||
@@ -132,11 +132,11 @@ async function handleAuth(
|
|||||||
logger.debug(`Web client authenticated for session: ${sessionId}`);
|
logger.debug(`Web client authenticated for session: ${sessionId}`);
|
||||||
return false;
|
return false;
|
||||||
} else {
|
} else {
|
||||||
recordFailure(sessionId);
|
recordFailure(throttleKey);
|
||||||
socket.send(JSON.stringify({
|
socket.send(JSON.stringify({
|
||||||
type: 'auth_response',
|
type: 'auth_response',
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Invalid password'
|
error: 'Authentication failed'
|
||||||
}));
|
}));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -89,12 +89,15 @@ export function createServer() {
|
|||||||
|
|
||||||
// Middleware
|
// Middleware
|
||||||
app.use(helmet({
|
app.use(helmet({
|
||||||
// The bundled login/app pages rely on inline <script> and inline event
|
// Page scripts are served as external files (/static/app.js,
|
||||||
// handlers, so script/style inline is permitted; images may be blobs.
|
// /static/login.js) with no inline handlers, so scripts are restricted to
|
||||||
|
// 'self' (no 'unsafe-inline'). The pages still use inline <style> blocks,
|
||||||
|
// so style-src keeps 'unsafe-inline'. Images may be data:/blob: (macro
|
||||||
|
// images are loaded as blob object URLs) and WS connections need ws:/wss:.
|
||||||
contentSecurityPolicy: {
|
contentSecurityPolicy: {
|
||||||
directives: {
|
directives: {
|
||||||
defaultSrc: ["'self'"],
|
defaultSrc: ["'self'"],
|
||||||
scriptSrc: ["'self'", "'unsafe-inline'"],
|
scriptSrc: ["'self'"],
|
||||||
styleSrc: ["'self'", "'unsafe-inline'"],
|
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||||
imgSrc: ["'self'", 'data:', 'blob:'],
|
imgSrc: ["'self'", 'data:', 'blob:'],
|
||||||
connectSrc: ["'self'", 'ws:', 'wss:'],
|
connectSrc: ["'self'", 'ws:', 'wss:'],
|
||||||
@@ -192,7 +195,7 @@ export function createServer() {
|
|||||||
// Desktop connection: /desktop
|
// Desktop connection: /desktop
|
||||||
if (pathname === '/desktop') {
|
if (pathname === '/desktop') {
|
||||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||||
handleDesktopConnection(ws, connectionManager, sessionManager);
|
handleDesktopConnection(ws, connectionManager, sessionManager, ip);
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -202,7 +205,7 @@ export function createServer() {
|
|||||||
if (webClientMatch) {
|
if (webClientMatch) {
|
||||||
const sessionId = webClientMatch[1];
|
const sessionId = webClientMatch[1];
|
||||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||||
handleWebClientConnection(ws, sessionId, connectionManager, sessionManager);
|
handleWebClientConnection(ws, sessionId, connectionManager, sessionManager, ip);
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -136,6 +136,21 @@ export class SessionManager {
|
|||||||
} while (this.sessions.has(id));
|
} while (this.sessions.has(id));
|
||||||
|
|
||||||
const passwordHash = await bcrypt.hash(password, config.bcryptRounds);
|
const passwordHash = await bcrypt.hash(password, config.bcryptRounds);
|
||||||
|
|
||||||
|
// Re-check the cap AFTER the (awaited) hash. bcrypt.hash is the only
|
||||||
|
// suspension point between the first cap check and the set() below, so
|
||||||
|
// concurrent createSession calls could each have passed the earlier check
|
||||||
|
// and then filled the map while we were hashing. Re-checking here — with
|
||||||
|
// no await between this check and the synchronous set() — makes the
|
||||||
|
// check-and-insert atomic under Node's single-threaded model, so the cap
|
||||||
|
// cannot be overshot.
|
||||||
|
if (this.sessions.size >= config.maxSessions) {
|
||||||
|
this.pruneExpired();
|
||||||
|
if (this.sessions.size >= config.maxSessions) {
|
||||||
|
throw new Error('Session limit reached');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
const session: Session = {
|
const session: Session = {
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
// Per-session-id auth brute-force lockout (in-memory).
|
// Auth brute-force lockout (in-memory).
|
||||||
//
|
//
|
||||||
// Tracks failed authentication attempts keyed by session id. After
|
// Tracks failed authentication attempts keyed by an opaque, namespaced key
|
||||||
// `authLockoutMaxAttempts` failures within `authLockoutWindowMs`, further
|
// (e.g. `web:${sessionId}:${clientIp}` or `desktop:${sessionId}:${clientIp}`).
|
||||||
// attempts are rejected until `authLockoutDurationMs` has elapsed.
|
// Namespacing by path and client IP keeps the web and desktop keyspaces
|
||||||
|
// separate so one abusive web client cannot lock out other users or the
|
||||||
|
// desktop for the same session. After `authLockoutMaxAttempts` failures within
|
||||||
|
// `authLockoutWindowMs`, further attempts are rejected until
|
||||||
|
// `authLockoutDurationMs` has elapsed.
|
||||||
|
|
||||||
import { config } from '../config';
|
import { config } from '../config';
|
||||||
|
|
||||||
@@ -29,10 +33,12 @@ export function getLockoutRemaining(key: string): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Record a failed auth attempt. Returns the lockout remaining (ms) after
|
* Record a failed auth attempt. Locks the key out for
|
||||||
* this failure is applied (0 if still not locked).
|
* `authLockoutDurationMs` once `authLockoutMaxAttempts` failures accumulate
|
||||||
|
* within `authLockoutWindowMs`. Callers query the resulting lockout via
|
||||||
|
* getLockoutRemaining(), so this returns nothing.
|
||||||
*/
|
*/
|
||||||
export function recordFailure(key: string): number {
|
export function recordFailure(key: string): void {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
let rec = records.get(key);
|
let rec = records.get(key);
|
||||||
|
|
||||||
@@ -47,8 +53,6 @@ export function recordFailure(key: string): number {
|
|||||||
if (rec.count >= config.authLockoutMaxAttempts) {
|
if (rec.count >= config.authLockoutMaxAttempts) {
|
||||||
rec.lockedUntil = now + config.authLockoutDurationMs;
|
rec.lockedUntil = now + config.authLockoutDurationMs;
|
||||||
}
|
}
|
||||||
|
|
||||||
return rec.lockedUntil > now ? rec.lockedUntil - now : 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -18,7 +18,11 @@ export function generateSessionId(length: number = 12): string {
|
|||||||
let result = '';
|
let result = '';
|
||||||
|
|
||||||
while (result.length < length) {
|
while (result.length < length) {
|
||||||
// Over-fetch a little to reduce the number of syscalls when rejecting.
|
// Fetch exactly `length` random bytes per pass. Bytes at or above the
|
||||||
|
// rejection threshold are skipped to avoid modulo bias, so a pass may
|
||||||
|
// yield fewer than `length` characters; the outer while then runs another
|
||||||
|
// pass until we have enough. (No over-fetching — each pass draws exactly
|
||||||
|
// `length` bytes.)
|
||||||
const bytes = randomBytes(length);
|
const bytes = randomBytes(length);
|
||||||
for (let i = 0; i < bytes.length && result.length < length; i++) {
|
for (let i = 0; i < bytes.length && result.length < length; i++) {
|
||||||
const byte = bytes[i];
|
const byte = bytes[i];
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'none'">
|
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'; object-src 'none'; base-uri 'none'">
|
||||||
<meta name="theme-color" content="#15161a" media="(prefers-color-scheme: dark)">
|
<meta name="theme-color" content="#15161a" media="(prefers-color-scheme: dark)">
|
||||||
<meta name="theme-color" content="#eceef4" media="(prefers-color-scheme: light)">
|
<meta name="theme-color" content="#eceef4" media="(prefers-color-scheme: light)">
|
||||||
<meta name="description" content="Remote macro control for your desktop">
|
<meta name="description" content="Remote macro control for your desktop">
|
||||||
|
|||||||
+78
-9
@@ -34,6 +34,13 @@ class MacroPadApp {
|
|||||||
// Guards against out-of-order macro fetches
|
// Guards against out-of-order macro fetches
|
||||||
this._macroReqId = 0;
|
this._macroReqId = 0;
|
||||||
|
|
||||||
|
// Blob object URLs created for macro images (revoked on re-render)
|
||||||
|
this._objectUrls = [];
|
||||||
|
|
||||||
|
// Set once a local-mode auth failure has been surfaced, to avoid
|
||||||
|
// reconnect loops and repeated toasts.
|
||||||
|
this.localAuthFailed = false;
|
||||||
|
|
||||||
// Macro editor state (null = create mode)
|
// Macro editor state (null = create mode)
|
||||||
this.editingMacroId = null;
|
this.editingMacroId = null;
|
||||||
|
|
||||||
@@ -204,12 +211,44 @@ class MacroPadApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleAuthError() {
|
handleAuthError() {
|
||||||
this.showToast('Authentication failed', 'error');
|
|
||||||
if (this.relayMode) {
|
if (this.relayMode) {
|
||||||
|
this.showToast('Authentication failed', 'error');
|
||||||
// Clear stored password and redirect to login
|
// Clear stored password and redirect to login
|
||||||
sessionStorage.removeItem(`macropad_${this.sessionId}`);
|
sessionStorage.removeItem(`macropad_${this.sessionId}`);
|
||||||
window.location.href = `/${this.sessionId}`;
|
window.location.href = `/${this.sessionId}`;
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Local (token) mode: a wrong/missing token makes every request 401 and
|
||||||
|
// the WebSocket close with 1008, which would otherwise reconnect forever
|
||||||
|
// and spam toasts. Surface a single, clear message and stop retrying.
|
||||||
|
if (this.localAuthFailed) return;
|
||||||
|
this.localAuthFailed = true;
|
||||||
|
|
||||||
|
this.shouldReconnect = false;
|
||||||
|
clearTimeout(this.reconnectTimer);
|
||||||
|
this.teardownSocket();
|
||||||
|
this.updateConnectionStatus(false, 'Access denied');
|
||||||
|
this.renderAuthRequired();
|
||||||
|
}
|
||||||
|
|
||||||
|
renderAuthRequired() {
|
||||||
|
const container = document.getElementById('macro-grid');
|
||||||
|
if (!container) return;
|
||||||
|
container.textContent = '';
|
||||||
|
|
||||||
|
const wrap = document.createElement('div');
|
||||||
|
wrap.className = 'empty-state';
|
||||||
|
|
||||||
|
const p1 = document.createElement('p');
|
||||||
|
p1.textContent = 'Access token required';
|
||||||
|
|
||||||
|
const p2 = document.createElement('p');
|
||||||
|
p2.className = 'hint';
|
||||||
|
p2.textContent = "Open the link from the desktop app's URL or QR code.";
|
||||||
|
|
||||||
|
wrap.append(p1, p2);
|
||||||
|
container.appendChild(wrap);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleDesktopDisconnected() {
|
handleDesktopDisconnected() {
|
||||||
@@ -396,15 +435,38 @@ class MacroPadApp {
|
|||||||
|
|
||||||
macroImageUrl(macro) {
|
macroImageUrl(macro) {
|
||||||
if (!macro.image_path) return null;
|
if (!macro.image_path) return null;
|
||||||
const basePath = this.getApiUrl(`/api/image/${macro.image_path}`);
|
// No credential ever goes on the URL; auth is via a header on a
|
||||||
// Credentials go as query params since <img> can't set headers.
|
// fetch() below, and the image is shown as a blob object URL.
|
||||||
|
return this.getApiUrl(`/api/image/${macro.image_path}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auth-only headers (no Content-Type) for GET fetches like images.
|
||||||
|
getAuthHeaders() {
|
||||||
|
const headers = {};
|
||||||
if (this.relayMode && this.password) {
|
if (this.relayMode && this.password) {
|
||||||
return `${basePath}?password=${encodeURIComponent(this.password)}`;
|
headers['X-MacroPad-Password'] = this.password;
|
||||||
|
} else if (!this.relayMode && this.localToken) {
|
||||||
|
headers['X-MacroPad-Token'] = this.localToken;
|
||||||
}
|
}
|
||||||
if (!this.relayMode && this.localToken) {
|
return headers;
|
||||||
return `${basePath}?token=${encodeURIComponent(this.localToken)}`;
|
}
|
||||||
|
|
||||||
|
// Fetch a macro image with the auth header and display it as a blob
|
||||||
|
// object URL, so no credential is ever placed on an <img> src.
|
||||||
|
async loadMacroImage(url, img, placeholder) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, { headers: this.getAuthHeaders() });
|
||||||
|
if (!res.ok) throw new Error('image request failed');
|
||||||
|
const blob = await res.blob();
|
||||||
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
|
// Track for best-effort revocation on the next render.
|
||||||
|
this._objectUrls.push(objectUrl);
|
||||||
|
img.src = objectUrl;
|
||||||
|
} catch (e) {
|
||||||
|
// Fall back to the placeholder if the image can't be loaded.
|
||||||
|
img.style.display = 'none';
|
||||||
|
placeholder.style.display = '';
|
||||||
}
|
}
|
||||||
return basePath;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rendering (safe DOM construction only - no user value reaches innerHTML)
|
// Rendering (safe DOM construction only - no user value reaches innerHTML)
|
||||||
@@ -430,6 +492,12 @@ class MacroPadApp {
|
|||||||
const container = document.getElementById('macro-grid');
|
const container = document.getElementById('macro-grid');
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
|
|
||||||
|
// Best-effort: revoke object URLs from the previous render to avoid leaks.
|
||||||
|
if (this._objectUrls && this._objectUrls.length) {
|
||||||
|
this._objectUrls.forEach((u) => URL.revokeObjectURL(u));
|
||||||
|
}
|
||||||
|
this._objectUrls = [];
|
||||||
|
|
||||||
container.textContent = '';
|
container.textContent = '';
|
||||||
|
|
||||||
const macroEntries = Object.entries(this.macros);
|
const macroEntries = Object.entries(this.macros);
|
||||||
@@ -464,14 +532,15 @@ class MacroPadApp {
|
|||||||
const img = document.createElement('img');
|
const img = document.createElement('img');
|
||||||
img.className = 'macro-image';
|
img.className = 'macro-image';
|
||||||
img.alt = '';
|
img.alt = '';
|
||||||
img.src = imageSrc;
|
|
||||||
placeholder.style.display = 'none';
|
placeholder.style.display = 'none';
|
||||||
// Fall back to the placeholder if the image fails to load.
|
// Fall back to the placeholder if the (blob) image fails to load.
|
||||||
img.addEventListener('error', () => {
|
img.addEventListener('error', () => {
|
||||||
img.style.display = 'none';
|
img.style.display = 'none';
|
||||||
placeholder.style.display = '';
|
placeholder.style.display = '';
|
||||||
});
|
});
|
||||||
card.appendChild(img);
|
card.appendChild(img);
|
||||||
|
// Header-authenticated fetch -> blob object URL (no credential on src).
|
||||||
|
this.loadMacroImage(imageSrc, img, placeholder);
|
||||||
}
|
}
|
||||||
card.appendChild(placeholder);
|
card.appendChild(placeholder);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user