Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Polish connections: domain-expiry alerts, S3 image preview, encryption-health banner

Juan Denisfd2313077ffe
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index d9c1acc7..5b7509f2 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -383,6 +383,9 @@ def create_app(config_name=None):
# Start hourly pruner for expired pending agent pairings
_start_pairing_pruner(app)
+ # Start daily registrar domain-expiry notifier
+ _start_registrar_expiry_scheduler(app)
+
# Request body size limit
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit
@@ -546,6 +549,41 @@ def _start_pairing_pruner(app):
_pairing_prune_thread = None
+_registrar_expiry_thread = None
+
+
+def _start_registrar_expiry_scheduler(app):
+ """Daily check that notifies when a registrar domain crosses an expiry
+ threshold (30/14/7/1 days, or expired). Single-worker only (module-global
+ guard), like the other in-process schedulers."""
+ global _registrar_expiry_thread
+ if _registrar_expiry_thread is not None:
+ return
+
+ import threading
+ import time
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def loop():
+ time.sleep(300) # let startup settle
+ while True:
+ try:
+ with app.app_context():
+ from app.services.registrar_service import RegistrarService
+ n = RegistrarService.notify_expiring()
+ if n:
+ logger.info(f'Registrar expiry: sent {n} notification(s)')
+ except Exception as e:
+ logger.error(f'Registrar expiry scheduler error: {e}')
+ time.sleep(86400) # daily
+
+ _registrar_expiry_thread = threading.Thread(
+ target=loop, daemon=True, name='registrar-expiry')
+ _registrar_expiry_thread.start()
+
+
_snapshot_retention_thread = None
diff --git a/backend/app/services/registrar_service.py b/backend/app/services/registrar_service.py
index 8aa7c04c..e42f38bf 100644
--- a/backend/app/services/registrar_service.py
+++ b/backend/app/services/registrar_service.py
@@ -33,6 +33,9 @@ class RegistrarService:
NAMECHEAP_BASE = 'https://api.namecheap.com/xml.response'
NAMECHEAP_NS = {'nc': 'http://api.namecheap.com/xml.response'}
+ # Days-before-expiry thresholds that trigger a (de-duped) notification.
+ EXPIRY_THRESHOLDS = [30, 14, 7, 1]
+
# --- Connections (CRUD) ---
@staticmethod
@@ -238,6 +241,88 @@ class RegistrarService:
db.session.commit()
return domains
+ # --- Expiry notifications ---
+
+ @classmethod
+ def _bucket(cls, days):
+ """Most-urgent threshold a domain has crossed → (rank, label). Higher rank
+ is more urgent; rank 0 means "outside every threshold" (no alert)."""
+ if days is None:
+ return 0, None
+ if days <= 0:
+ return len(cls.EXPIRY_THRESHOLDS) + 1, 'expired'
+ for i, t in enumerate(sorted(cls.EXPIRY_THRESHOLDS)): # ascending: [1,7,14,30]
+ if days <= t:
+ return len(cls.EXPIRY_THRESHOLDS) - i, str(t)
+ return 0, None
+
+ @classmethod
+ def _alert_state_path(cls):
+ import os
+ from app import paths
+ return os.path.join(paths.SERVERKIT_CONFIG_DIR, 'registrar_alerts.json')
+
+ @classmethod
+ def notify_expiring(cls):
+ """Send a notification when a domain crosses an expiry threshold
+ (30/14/7/1 days, or expired). De-duped via a small state file so each
+ crossing notifies once and only escalations re-fire. Returns the number
+ of alerts sent."""
+ import os
+ import json
+ from app import paths
+
+ domains = cls.list_all_domains()
+ if not domains:
+ return 0
+
+ state_path = cls._alert_state_path()
+ state = {}
+ if os.path.exists(state_path):
+ try:
+ with open(state_path) as f:
+ state = json.load(f)
+ except Exception:
+ state = {}
+
+ alerts = []
+ new_state = {}
+ for d in domains:
+ name = d.get('domain')
+ if not name:
+ continue
+ rank, label = cls._bucket(d.get('days_until_expiry'))
+ if rank == 0:
+ continue # outside every threshold — and dropped from state below
+ new_state[name] = rank
+ if rank > state.get(name, 0): # escalated into a new, more-urgent bucket
+ days = d.get('days_until_expiry')
+ who = d.get('registrar_name') or d.get('registrar')
+ if label == 'expired':
+ severity, message = 'critical', f'Domain {name} has EXPIRED ({who}).'
+ else:
+ severity = 'critical' if label in ('1', '7') else 'warning'
+ message = f"Domain {name} expires in {days} day{'' if days == 1 else 's'} ({who})."
+ alerts.append({'type': 'domain_expiry', 'severity': severity,
+ 'message': message, 'value': name, 'threshold': label})
+
+ # Persist only domains still within a threshold; a renewed domain drops out
+ # and will re-alert next time it approaches expiry.
+ try:
+ os.makedirs(paths.SERVERKIT_CONFIG_DIR, exist_ok=True)
+ with open(state_path, 'w') as f:
+ json.dump(new_state, f, indent=2)
+ except Exception:
+ pass
+
+ if alerts:
+ try:
+ from app.services.notification_service import NotificationService
+ NotificationService.send_all(alerts)
+ except Exception as e:
+ logger.warning(f'Registrar expiry notify failed: {e}')
+ return len(alerts)
+
# --- Helpers ---
@staticmethod
diff --git a/docs/CONNECTIONS_ROADMAP.md b/docs/CONNECTIONS_ROADMAP.md
index 1d65a724..94ae6d61 100644
--- a/docs/CONNECTIONS_ROADMAP.md
+++ b/docs/CONNECTIONS_ROADMAP.md
@@ -41,6 +41,8 @@ New backend: `models/registrar_connection.py`, `services/registrar_service.py`,
**Nothing open** — every task #1–#18 is done. Each external account type (source, infrastructure, DNS, registrar, email relay, storage) connects through the hub, secrets are encrypted at rest across all five stores, and `GET /api/v1/connections` lists them all in one normalized view.
+**Post-roadmap polish:** (1) **domain-expiry notifications** — a daily scheduler fires through the notification channels when a registrar domain crosses 30/14/7/1 days or expires, de-duped via a small state file so each crossing alerts once; (2) **S3 image preview** — File Manager thumbnails and the preview drawer load bucket objects via short-lived presigned URLs (`ImageThumb` is S3-aware); (3) **encryption-health banner** — the hub now consumes `GET /api/v1/connections` and warns if any connection's credentials aren't encrypted at rest (invisible in the happy path).
+
---
## How to read this document
diff --git a/frontend/src/components/file-manager/FileCard.jsx b/frontend/src/components/file-manager/FileCard.jsx
index c74ca0fa..4464d972 100644
--- a/frontend/src/components/file-manager/FileCard.jsx
+++ b/frontend/src/components/file-manager/FileCard.jsx
@@ -11,6 +11,7 @@ function FileCard({
onOpen,
onToggleSelect,
onContext,
+ isS3 = false,
}) {
const ext = getFileExt(entry);
const type = getFileType(entry);
@@ -47,7 +48,7 @@ function FileCard({
<div className="file-card-thumb">
{showThumb ? (
- <ImageThumb path={entry.path} fallback={<FileIcon entry={entry} size={36} />} />
+ <ImageThumb path={entry.path} isS3={isS3} fallback={<FileIcon entry={entry} size={36} />} />
) : (
<FileIcon entry={entry} size={36} />
)}
diff --git a/frontend/src/components/file-manager/ImageThumb.jsx b/frontend/src/components/file-manager/ImageThumb.jsx
index c9c108e6..4cbf7265 100644
--- a/frontend/src/components/file-manager/ImageThumb.jsx
+++ b/frontend/src/components/file-manager/ImageThumb.jsx
@@ -3,7 +3,7 @@ import { api } from '../../services/api';
// Auth-fetches a file via the download endpoint, converts to a blob URL, and
// renders it as an <img>. Falls back to whatever JSX is passed in `fallback`.
-export default function ImageThumb({ path, fallback, className = 'thumb-image', alt = '' }) {
+export default function ImageThumb({ path, fallback, className = 'thumb-image', alt = '', isS3 = false }) {
const [src, setSrc] = useState(null);
const [errored, setErrored] = useState(false);
@@ -12,6 +12,14 @@ export default function ImageThumb({ path, fallback, className = 'thumb-image',
let cancelled = false;
(async () => {
try {
+ // S3 objects load straight from a short-lived presigned URL — no
+ // auth header or blob needed.
+ if (isS3) {
+ const res = await api.getS3DownloadUrl(path);
+ if (!res || !res.url) throw new Error('no presigned url');
+ if (!cancelled) setSrc(res.url);
+ return;
+ }
const token = api.getToken();
const url = `${api.baseUrl}/files/download?path=${encodeURIComponent(path)}`;
const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
@@ -27,7 +35,7 @@ export default function ImageThumb({ path, fallback, className = 'thumb-image',
cancelled = true;
if (blobUrl) URL.revokeObjectURL(blobUrl);
};
- }, [path]);
+ }, [path, isS3]);
if (errored || !src) return fallback;
return <img src={src} alt={alt} className={className} loading="lazy" />;
diff --git a/frontend/src/components/file-manager/PreviewDrawer.jsx b/frontend/src/components/file-manager/PreviewDrawer.jsx
index 4e275b2b..8d467562 100644
--- a/frontend/src/components/file-manager/PreviewDrawer.jsx
+++ b/frontend/src/components/file-manager/PreviewDrawer.jsx
@@ -27,6 +27,7 @@ export default function PreviewDrawer({
// When true, render as a flush inline pane (file-manager 3rd column)
// instead of a fixed-position drawer-over-scrim.
inline = false,
+ isS3 = false,
}) {
// Lock body scroll only for the overlay drawer; the inline pane scrolls
// within its own column and must not freeze the page.
@@ -115,6 +116,7 @@ export default function PreviewDrawer({
<div className="preview-image-wrap">
<ImageThumb
path={file.path}
+ isS3={isS3}
fallback={
<div className="preview-unavailable">
<EyeOff size={48} strokeWidth={1.5} />
diff --git a/frontend/src/components/settings/connections/ConnectionsHub.jsx b/frontend/src/components/settings/connections/ConnectionsHub.jsx
index 91f6b547..dceefac0 100644
--- a/frontend/src/components/settings/connections/ConnectionsHub.jsx
+++ b/frontend/src/components/settings/connections/ConnectionsHub.jsx
@@ -10,6 +10,7 @@
// Each connected provider shows its status, access scope, and a cross-link to the
// in-app page it powers (Servers, Domains, Backups, New Service).
import { useCallback, useEffect, useMemo, useState } from 'react';
+import { ShieldAlert } from 'lucide-react';
import api from '../../../services/api';
import { useAuth } from '../../../contexts/AuthContext';
import { useToast } from '../../../contexts/ToastContext';
@@ -31,13 +32,14 @@ export default function ConnectionsHub() {
const [relayConfig, setRelayConfig] = useState(null);
const [registrarConnections, setRegistrarConnections] = useState([]);
const [registrarDomains, setRegistrarDomains] = useState([]);
+ const [allConnections, setAllConnections] = useState([]);
const [loading, setLoading] = useState(true);
const [modalProvider, setModalProvider] = useState(null);
const [modalOpen, setModalOpen] = useState(false);
const loadData = useCallback(async () => {
try {
- const [ghStatus, glStatus, dns, cloudP, storage, relay, regConns, regDomains] = await Promise.all([
+ const [ghStatus, glStatus, dns, cloudP, storage, relay, regConns, regDomains, allConns] = await Promise.all([
api.getGithubSourceStatus().catch(() => null),
api.getGitlabSourceStatus().catch(() => null),
api.getEmailDNSProviders().then((d) => d.providers || []).catch(() => []),
@@ -46,6 +48,7 @@ export default function ConnectionsHub() {
api.getEmailRelay().catch(() => null),
api.getRegistrarConnections().then((d) => d.connections || []).catch(() => []),
api.getRegistrarDomains().then((d) => d.domains || []).catch(() => []),
+ api.getAllConnections().then((d) => d.connections || []).catch(() => []),
]);
setSourceStatus({ github: ghStatus, gitlab: glStatus });
setDnsProviders(dns);
@@ -54,6 +57,7 @@ export default function ConnectionsHub() {
setRelayConfig(relay);
setRegistrarConnections(regConns);
setRegistrarDomains(regDomains);
+ setAllConnections(allConns);
if (isAdmin) {
const [ghCfg, glCfg] = await Promise.all([
api.getGithubSourceConfig().catch(() => null),
@@ -355,8 +359,19 @@ export default function ConnectionsHub() {
setModalOpen(true);
}
+ const unencryptedCount = allConnections.filter((c) => c && c.encrypted === false).length;
+
return (
<div className="connections-hub">
+ {!loading && unencryptedCount > 0 && (
+ <div className="connections-hub__warning">
+ <ShieldAlert size={16} />
+ <span>
+ {unencryptedCount} connected account{unencryptedCount === 1 ? '' : 's'} {unencryptedCount === 1 ? 'has' : 'have'} credentials not encrypted at rest.
+ Restart the panel to migrate them, or check that <code>SERVERKIT_ENCRYPTION_KEY</code> is set.
+ </span>
+ </div>
+ )}
{loading ? (
<div className="connections-hub__loading">Loading connections…</div>
) : (
diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx
index 57894025..534b2c48 100644
--- a/frontend/src/pages/FileManager.jsx
+++ b/frontend/src/pages/FileManager.jsx
@@ -1181,6 +1181,7 @@ function FileManager() {
onOpen={handleOpen}
onToggleSelect={handleToggleSelect}
onContext={openContextMenu}
+ isS3={isS3}
/>
))}
</div>
@@ -1232,6 +1233,7 @@ function FileManager() {
<PreviewDrawer
inline
+ isS3={isS3}
file={previewFile}
fileContent={fileContent}
setFileContent={setFileContent}
diff --git a/frontend/src/services/api/files.js b/frontend/src/services/api/files.js
index 579272d5..a282cfc8 100644
--- a/frontend/src/services/api/files.js
+++ b/frontend/src/services/api/files.js
@@ -148,8 +148,12 @@ export async function deleteS3(path) {
return this.request(`/files/s3/delete?path=${encodeURIComponent(path)}`, { method: 'DELETE' });
}
+export async function getS3DownloadUrl(path) {
+ return this.request(`/files/s3/download-url?path=${encodeURIComponent(path)}`);
+}
+
export async function downloadS3File(path) {
- const res = await this.request(`/files/s3/download-url?path=${encodeURIComponent(path)}`);
+ const res = await this.getS3DownloadUrl(path);
if (res && res.url) window.open(res.url, '_blank');
return res;
}
diff --git a/frontend/src/styles/pages/_connections.scss b/frontend/src/styles/pages/_connections.scss
index ac94a4cc..b596d302 100644
--- a/frontend/src/styles/pages/_connections.scss
+++ b/frontend/src/styles/pages/_connections.scss
@@ -18,6 +18,29 @@
font-size: $font-size-sm;
}
+ &__warning {
+ display: flex;
+ align-items: flex-start;
+ gap: $space-2;
+ padding: $space-3 $space-4;
+ background: fade($warning, 10%);
+ border: 1px solid fade($warning, 30%);
+ border-radius: $radius-md;
+ font-size: $font-size-sm;
+ color: $text-secondary;
+
+ svg {
+ color: $warning;
+ flex-shrink: 0;
+ margin-top: 1px;
+ }
+
+ code {
+ font-family: $font-mono;
+ color: $text-primary;
+ }
+ }
+
&__category {
display: flex;
flex-direction: column;