Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ A self-hosted dashboard for monitoring and controlling multiple TinyPilot device

## What you get

- One web UI that lists your TinyPilot devices, up to four per page, with a live screenshot of the connected system on each card.
- One-click device addition (friendly name + TinyPilot URL + Automation API key).
- One web UI that lists your TinyPilot devices, up to four per page, with a live preview of the connected system on each card (cached in the browser only).
- One-click device addition (friendly name + TinyPilot URL + Automation API key), plus Replace API key on an existing card.
- Per-device snapshot of TinyPilot status: connected display resolution, streaming mode (H.264 with bitrate, or MJPEG with framerate and quality), firmware version, network info, and more.
- Encrypted at-rest storage for Automation API keys.

Expand Down Expand Up @@ -131,9 +131,12 @@ If none of those apply to your environment, please **do not run this alpha**.
Everything persistent lives in `./data`:

- `dashboard.sqlite` — devices and encrypted credentials.
- `screenshots/` — latest screenshot per device.
- `secret.key` — the encryption key for the SQLite secrets.

Live previews are **not** stored on the server. The browser keeps the last image per device in Cache Storage (cache name `tinypilot-dashboard-previews-v1`). Clear it with `window.tinypilotPreviewCache.clearPreviewCache()` (for example on sign-out in a host that wraps this dashboard). Cache Storage requires a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS or `http://localhost` / `http://127.0.0.1`). On plain `http://<lan-host>:8080`, the API is unavailable: live refresh still works, but cached and offline-with-image states do not persist across reloads.

Schema migrations use SQLite `DROP COLUMN` (SQLite **3.35** or later). The Docker image is fine; bare-metal hosts on older SQLite need an upgrade before starting 0.4.0 against an existing DB.

**To back up: copy the entire `data/` directory.** `secret.key` must be backed up alongside `dashboard.sqlite` — without it the encrypted columns cannot be recovered.

## Troubleshooting
Expand All @@ -160,7 +163,7 @@ Source layout and conventions for anyone reading the code or auditing what the d
- `templates/index.html` — Jinja shell that loads the `<dashboard-app>` web component and static assets.
- `static/js/dashboard-app.js` — root custom element with shadow DOM: top bar, theme toggle, Add-a-device modal, paging (four devices per page), and a responsive device grid (1 → 2 → 4 columns).
- `static/js/components/device-card.js` — one custom element per TinyPilot target. Owns the screenshot controls and the collapsed/expanded TinyPilot snapshot panel.
- `static/js/lib/` — shared helpers (`strings.js`, `snapshot-view.js`).
- `static/js/lib/` — shared helpers (`strings.js`, `snapshot-view.js`, `preview-cache.js`).
- `static/js/api.js` — thin `fetch` wrappers attached to `window.dashboardApi`.

**Backend** (`app/`)
Expand All @@ -170,7 +173,6 @@ Source layout and conventions for anyone reading the code or auditing what the d
- `db.py` — SQLite connection helper and schema bootstrap.
- `tinypilot_client.py` — HTTP client for TinyPilot Automation API-key routes.
- `resolution.py` — normalizers for the various shapes TinyPilot uses to report "connected device resolution".
- `snapshot_service.py` — atomic latest-screenshot writer.
- `auth_store.py`, `crypto.py` — Fernet-encrypted at-rest secrets.

### TinyPilot APIs the dashboard uses
Expand Down
2 changes: 1 addition & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# 0.5.x -> beta
# 1.0.0 -> first stable release
# Bump this on every customer-visible release.
__version__ = '0.3.0'
__version__ = '0.4.0'


def create_app(test_config=None):
Expand Down
111 changes: 58 additions & 53 deletions app/api.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""HTTP API blueprint for the TinyPilot Dashboard.

All routes live under the ``/api`` prefix and return JSON (except
``/api/devices/<id>/latest-screenshot`` which streams an image). Database
``/api/devices/<id>/refresh-screenshot`` which returns a JPEG). Database
access goes through ``app.db.get_db``; secrets are read or written through
``app.auth_store`` so they are encrypted at rest.

Expand All @@ -16,10 +16,10 @@

import requests
from flask import Blueprint
from flask import Response
from flask import current_app
from flask import jsonify
from flask import request
from flask import send_file

from app.auth_store import decrypt_secret
from app.auth_store import encrypt_secret
Expand All @@ -28,7 +28,6 @@
from app.device_update import update_available
from app.resolution import connected_resolution_from_web_ui
from app.resolution import resolution_from_automation_state
from app.snapshot_service import write_latest_screenshot
from app.tinypilot_client import TinyPilotClient

api_blueprint = Blueprint('api', __name__, url_prefix='/api')
Expand Down Expand Up @@ -91,7 +90,6 @@ def list_devices():
devices.id,
devices.friendly_name,
devices.base_url,
device_runtime_state.latest_screenshot_captured_at,
device_runtime_state.screenshot_refresh_interval_minutes,
CASE
WHEN device_auth.encrypted_automation_token IS NOT NULL THEN 1
Expand All @@ -108,7 +106,6 @@ def list_devices():
'id': row['id'],
'friendly_name': row['friendly_name'],
'base_url': row['base_url'],
'latest_screenshot_captured_at': row['latest_screenshot_captured_at'],
'screenshot_refresh_interval_minutes': row['screenshot_refresh_interval_minutes'] or 0,
'api_key_configured': bool(row['api_key_configured']),
}
Expand Down Expand Up @@ -224,36 +221,73 @@ def refresh_screenshot(device_id: int):

try:
screenshot = client.get_screenshot()
except requests.RequestException as err:
# requests.*Error subclasses often also inherit ValueError; handle first.
return jsonify(
{'error': f'failed to refresh screenshot: {_customer_error(err)}'}
), 502
except ValueError as exc:
# TinyPilotClient raises ValueError only for HTTP 204 / empty body.
if 'no screenshot image' not in str(exc):
return jsonify(
{'error': f'failed to refresh screenshot: {_customer_error(exc)}'}
), 502
current_app.logger.warning('TinyPilot screenshot no signal: %s', exc)
return jsonify({
'error': 'No signal',
'code': 'no_signal',
}), 502
except Exception as err: # pylint: disable=broad-exception-caught
return jsonify(
{'error': f'failed to refresh screenshot: {_customer_error(err)}'}
), 502

db = get_db()
data_root = Path(current_app.config['DATABASE_PATH']).resolve().parent
screenshot_path = write_latest_screenshot(data_root / 'screenshots', device_id, screenshot)
captured_at = datetime.now(timezone.utc).isoformat()
db.execute(
response = Response(screenshot, mimetype='image/jpeg')
response.headers['X-Captured-At'] = captured_at
return response


@api_blueprint.put('/devices/<int:device_id>/api-key')
def replace_api_key(device_id: int):
payload = request.get_json(silent=True) or {}
raw_key = payload.get('api_key')
if not isinstance(raw_key, str):
return jsonify({'error': 'api_key is required'}), 400
api_key = raw_key.strip()
if not api_key:
return jsonify({'error': 'api_key is required'}), 400

db = get_db()
existing = db.execute(
"""
UPDATE device_runtime_state
SET latest_screenshot_path = ?, latest_screenshot_captured_at = ?, latest_screenshot_error = NULL
WHERE device_id = ?
SELECT id
FROM devices
WHERE id = ?
""",
(
str(screenshot_path),
captured_at,
(device_id,),
).fetchone()
if existing is None:
return jsonify({'error': 'device not found'}), 404

key_path = Path(current_app.config['SECRET_KEY_PATH'])
encrypted = encrypt_secret(key_path, api_key)
now = datetime.now(timezone.utc).isoformat()
db.execute(
"""
INSERT INTO device_auth (
device_id,
),
encrypted_automation_token,
automation_token_refreshed_at
) VALUES (?, ?, ?)
ON CONFLICT(device_id) DO UPDATE SET
encrypted_automation_token = excluded.encrypted_automation_token,
automation_token_refreshed_at = excluded.automation_token_refreshed_at
""",
(device_id, encrypted, now),
)
db.commit()
return jsonify(
{
'device_id': device_id,
'screenshot_refreshed': True,
'screenshot_path': str(screenshot_path),
'captured_at': captured_at,
}
)
return jsonify({'device_id': device_id, 'api_key_configured': True})


@api_blueprint.post('/devices/<int:device_id>/screenshot-refresh-config')
Expand Down Expand Up @@ -294,35 +328,6 @@ def set_screenshot_refresh_config(device_id: int):
)


@api_blueprint.get('/devices/<int:device_id>/latest-screenshot')
def get_latest_screenshot(device_id: int):
row = get_db().execute(
"""
SELECT latest_screenshot_path
FROM device_runtime_state
WHERE device_id = ?
""",
(device_id,),
).fetchone()
if row is None or not row['latest_screenshot_path']:
return jsonify({'error': 'screenshot not available'}), 404

screenshot_path = Path(row['latest_screenshot_path']).resolve()
screenshots_root = (
Path(current_app.config['DATABASE_PATH']).resolve().parent / 'screenshots'
).resolve()
# Defense-in-depth: the stored path is dashboard-controlled, but reject
# anything that resolves outside the screenshots directory so a tampered
# database row cannot expose arbitrary files via send_file.
try:
screenshot_path.relative_to(screenshots_root)
except ValueError:
return jsonify({'error': 'screenshot path is outside data directory'}), 404
if not screenshot_path.is_file():
return jsonify({'error': 'screenshot file missing'}), 404
return send_file(screenshot_path, mimetype='image/jpeg')


def _safe_fetch(fetcher):
try:
return fetcher(), None
Expand Down
60 changes: 46 additions & 14 deletions app/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@
from flask import current_app
from flask import g

# Columns removed in 0.4.0. Dropped on upgrade; omitted from CREATE for new DBs.
_DROPPED_COLUMNS = (
('devices', 'last_seen_at'),
('devices', 'last_status'),
('devices', 'role'),
('device_auth', 'encrypted_automation_license_key'),
('device_auth', 'encrypted_web_username'),
('device_auth', 'encrypted_web_password'),
('device_auth', 'encrypted_csrf_token'),
('device_auth', 'csrf_refreshed_at'),
('device_runtime_state', 'latest_screenshot_path'),
('device_runtime_state', 'latest_screenshot_captured_at'),
('device_runtime_state', 'latest_screenshot_error'),
('device_runtime_state', 'last_connection_check_at'),
('device_runtime_state', 'last_connection_check_error'),
)


def get_db() -> sqlite3.Connection:
"""Return the per-request SQLite connection, creating it on demand."""
Expand All @@ -38,32 +55,19 @@ def init_db() -> None:
id INTEGER PRIMARY KEY AUTOINCREMENT,
friendly_name TEXT NOT NULL,
base_url TEXT NOT NULL,
software_version TEXT,
role TEXT,
last_seen_at TEXT,
last_status TEXT
software_version TEXT
);

CREATE TABLE IF NOT EXISTS device_auth (
device_id INTEGER PRIMARY KEY,
encrypted_automation_license_key BLOB,
encrypted_automation_token BLOB,
automation_token_refreshed_at TEXT,
encrypted_web_username BLOB,
encrypted_web_password BLOB,
encrypted_csrf_token BLOB,
csrf_refreshed_at TEXT,
FOREIGN KEY(device_id) REFERENCES devices(id)
);

CREATE TABLE IF NOT EXISTS device_runtime_state (
device_id INTEGER PRIMARY KEY,
latest_screenshot_path TEXT,
latest_screenshot_captured_at TEXT,
latest_screenshot_error TEXT,
screenshot_refresh_interval_minutes INTEGER NOT NULL DEFAULT 0,
last_connection_check_at TEXT,
last_connection_check_error TEXT,
FOREIGN KEY(device_id) REFERENCES devices(id)
);
"""
Expand All @@ -74,6 +78,11 @@ def init_db() -> None:
column='screenshot_refresh_interval_minutes',
column_def='INTEGER NOT NULL DEFAULT 0',
)
for table, column in _DROPPED_COLUMNS:
_drop_column_if_exists(db, table, column)
_delete_screenshot_files(
Path(current_app.config['DATABASE_PATH']).resolve().parent
)
db.commit()


Expand Down Expand Up @@ -101,3 +110,26 @@ def _ensure_column(
if column in existing_names:
return
db.execute(f'ALTER TABLE {table} ADD COLUMN {column} {column_def}')


def _drop_column_if_exists(
db: sqlite3.Connection,
table: str,
column: str,
) -> None:
"""Drop ``column`` from ``table`` when present (SQLite 3.35+)."""
existing = db.execute(f'PRAGMA table_info({table})').fetchall()
existing_names = {row['name'] for row in existing}
if column not in existing_names:
return
db.execute(f'ALTER TABLE {table} DROP COLUMN {column}')


def _delete_screenshot_files(data_root: Path) -> None:
"""Remove leftover on-disk previews (plaintext or encrypted)."""
shots = data_root / 'screenshots'
if not shots.is_dir():
return
for path in shots.iterdir():
if path.is_file():
path.unlink()
22 changes: 0 additions & 22 deletions app/snapshot_service.py

This file was deleted.

Loading
Loading