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.

Improve plugin loading, API client & marketplace UI

Juan Denis9f7bd23f3c15
diff --git a/backend/app/api/marketplace.py b/backend/app/api/marketplace.py
index c24ac91c..b237bacc 100644
--- a/backend/app/api/marketplace.py
+++ b/backend/app/api/marketplace.py
@@ -13,6 +13,7 @@ def get_current_user():
return User.query.get(get_jwt_identity())
+@marketplace_bp.route('', methods=['GET'])
@marketplace_bp.route('/', methods=['GET'])
@jwt_required()
def list_extensions():
@@ -37,6 +38,7 @@ def get_extension(ext_id):
return jsonify(ext.to_dict())
+@marketplace_bp.route('', methods=['POST'])
@marketplace_bp.route('/', methods=['POST'])
@jwt_required()
def create_extension():
diff --git a/backend/app/api/plugins.py b/backend/app/api/plugins.py
index 25dc6574..7e99ded4 100644
--- a/backend/app/api/plugins.py
+++ b/backend/app/api/plugins.py
@@ -20,6 +20,7 @@ def get_current_user():
return User.query.get(get_jwt_identity())
+@plugins_bp.route('', methods=['GET'])
@plugins_bp.route('/', methods=['GET'])
@jwt_required()
def list_plugins():
diff --git a/builtin-extensions/serverkit-git/frontend/index.jsx b/builtin-extensions/serverkit-git/frontend/index.jsx
index dc44d152..7820887a 100644
--- a/builtin-extensions/serverkit-git/frontend/index.jsx
+++ b/builtin-extensions/serverkit-git/frontend/index.jsx
@@ -9,4 +9,6 @@
// so the relative import resolves against the host's pages directory.
import GitPage from '../../pages/Git';
-export const GitExtPage = GitPage;
+export function GitExtPage() {
+ return <GitPage basePath="/git-ext" />;
+}
diff --git a/frontend/src/contexts/AuthContext.jsx b/frontend/src/contexts/AuthContext.jsx
index 9df7814f..4e088a9e 100644
--- a/frontend/src/contexts/AuthContext.jsx
+++ b/frontend/src/contexts/AuthContext.jsx
@@ -20,6 +20,12 @@ export function AuthProvider({ children }) {
checkSetupStatus();
}, []);
+ useEffect(() => {
+ const handleAuthExpired = () => setUser(null);
+ window.addEventListener('serverkit:auth-expired', handleAuthExpired);
+ return () => window.removeEventListener('serverkit:auth-expired', handleAuthExpired);
+ }, []);
+
async function checkSetupStatus(retries = 3) {
try {
const status = await api.getSetupStatus();
@@ -60,7 +66,9 @@ export function AuthProvider({ children }) {
const data = await api.getCurrentUser();
setUser(data.user);
} catch (error) {
- console.error('Auth check failed:', error);
+ if (error.status !== 401) {
+ console.error('Auth check failed:', error);
+ }
api.clearTokens();
}
}
diff --git a/frontend/src/pages/Git.jsx b/frontend/src/pages/Git.jsx
index 9a1063a9..f24de2b8 100644
--- a/frontend/src/pages/Git.jsx
+++ b/frontend/src/pages/Git.jsx
@@ -12,10 +12,10 @@ import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
const VALID_TABS = ['overview', 'repositories', 'access', 'webhooks', 'deployments', 'settings'];
-function Git() {
+function Git({ basePath = '/git' }) {
const [status, setStatus] = useState(null);
const [loading, setLoading] = useState(true);
- const [activeTab, setActiveTab] = useTabParam('/git', VALID_TABS);
+ const [activeTab, setActiveTab] = useTabParam(basePath, VALID_TABS);
const [showInstallModal, setShowInstallModal] = useState(false);
const [actionLoading, setActionLoading] = useState(false);
const [confirmDialog, setConfirmDialog] = useState(null);
diff --git a/frontend/src/pages/Marketplace.jsx b/frontend/src/pages/Marketplace.jsx
index e7032f79..278d9fe7 100644
--- a/frontend/src/pages/Marketplace.jsx
+++ b/frontend/src/pages/Marketplace.jsx
@@ -19,28 +19,17 @@ import {
Sparkles,
Star,
UploadCloud,
- X,
} from 'lucide-react';
import api from '../services/api';
import { useToast } from '../contexts/ToastContext';
import Spinner from '../components/Spinner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
-import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
const CATEGORIES = ['monitoring', 'security', 'deployment', 'integration', 'ui', 'utility'];
-const INITIAL_EXTENSION_FORM = {
- name: '',
- display_name: '',
- description: '',
- category: 'utility',
- version: '1.0.0',
- author: '',
-};
-
const CATEGORY_ICONS = {
monitoring: Activity,
security: ShieldCheck,
@@ -142,13 +131,12 @@ const Marketplace = () => {
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState('');
const [category, setCategory] = useState('');
- const [showSubmit, setShowSubmit] = useState(false);
+ const [activeTab, setActiveTab] = useState('browse');
const [pluginUrl, setPluginUrl] = useState('');
const [pluginPath, setPluginPath] = useState('');
const [pluginFile, setPluginFile] = useState(null);
const [installSource, setInstallSource] = useState('url');
const [installing, setInstalling] = useState(false);
- const [form, setForm] = useState(INITIAL_EXTENSION_FORM);
const loadExtensions = useCallback(async () => {
try {
@@ -251,21 +239,16 @@ const Marketplace = () => {
} catch (err) { toast.error(err.message); }
};
- const handleSubmit = async () => {
- try {
- await api.createMarketplaceExtension(form);
- toast.success('Extension submitted');
- setShowSubmit(false);
- setForm(INITIAL_EXTENSION_FORM);
- loadExtensions();
- } catch (err) { toast.error(err.message); }
- };
-
const resetFilters = () => {
setSearch('');
setCategory('');
};
+ const openZipInstaller = () => {
+ setInstallSource('upload');
+ setActiveTab('plugins');
+ };
+
const pluginStatusVariant = (status) => {
if (status === 'active') return 'success';
if (status === 'error') return 'destructive';
@@ -309,9 +292,9 @@ const Marketplace = () => {
</div>
</div>
<div className="marketplace-hero__actions">
- <Button variant="outline" onClick={() => setShowSubmit(true)}>
+ <Button variant="outline" onClick={openZipInstaller}>
<UploadCloud aria-hidden="true" />
- Submit Extension
+ Import ZIP
</Button>
</div>
</section>
@@ -323,7 +306,7 @@ const Marketplace = () => {
<StatTile icon={PlugZap} label="Active Plugins" value={`${activePluginCount}/${plugins.length}`} tone={pluginIssueCount > 0 ? 'red' : 'violet'} />
</div>
- <Tabs defaultValue="browse" className="marketplace-tabs">
+ <Tabs value={activeTab} onValueChange={setActiveTab} className="marketplace-tabs">
<TabsList className="marketplace-tabs__list">
<TabsTrigger value="browse">
<LayoutGrid aria-hidden="true" />
@@ -604,54 +587,6 @@ const Marketplace = () => {
</TabsContent>
</Tabs>
- {showSubmit && (
- <div className="modal-overlay" onClick={() => setShowSubmit(false)}>
- <div className="modal marketplace-submit-modal" onClick={(event) => event.stopPropagation()}>
- <div className="modal-header">
- <div>
- <h2>Submit Extension</h2>
- <p className="text-muted">Publish a package listing to the local marketplace index.</p>
- </div>
- <button
- className="modal-close"
- type="button"
- aria-label="Close submit extension dialog"
- onClick={() => setShowSubmit(false)}
- >
- <X aria-hidden="true" />
- </button>
- </div>
- <div className="modal-body marketplace-submit-grid">
- <div className="form-group">
- <label>Name</label>
- <Input value={form.name} onChange={(event) => setForm({ ...form, name: event.target.value })} />
- </div>
- <div className="form-group">
- <label>Display Name</label>
- <Input value={form.display_name} onChange={(event) => setForm({ ...form, display_name: event.target.value })} />
- </div>
- <div className="form-group form-group--full">
- <label>Description</label>
- <Textarea value={form.description} onChange={(event) => setForm({ ...form, description: event.target.value })} rows={3} />
- </div>
- <div className="form-group">
- <label>Category</label>
- <select className="form-select" value={form.category} onChange={(event) => setForm({ ...form, category: event.target.value })}>
- {CATEGORIES.map((item) => <option key={item} value={item}>{titleCase(item)}</option>)}
- </select>
- </div>
- <div className="form-group">
- <label>Author</label>
- <Input value={form.author} onChange={(event) => setForm({ ...form, author: event.target.value })} />
- </div>
- </div>
- <div className="modal-footer">
- <Button variant="outline" onClick={() => setShowSubmit(false)}>Cancel</Button>
- <Button onClick={handleSubmit} disabled={!form.name}>Submit</Button>
- </div>
- </div>
- </div>
- )}
</div>
);
};
diff --git a/frontend/src/plugins/PluginLoader.jsx b/frontend/src/plugins/PluginLoader.jsx
index 1c154322..a8a6a4c5 100644
--- a/frontend/src/plugins/PluginLoader.jsx
+++ b/frontend/src/plugins/PluginLoader.jsx
@@ -22,7 +22,7 @@ import { useContributions, resolveComponent, getPluginModule } from './contribut
const pluginModules = import.meta.glob('./*/index.{js,jsx}', { eager: true });
-export function getInstalledPlugins() {
+function getInstalledPlugins() {
const plugins = [];
for (const [path, mod] of Object.entries(pluginModules)) {
const match = path.match(/^\.\/([^/]+)\/index\.(?:js|jsx)$/);
diff --git a/frontend/src/plugins/contributions.js b/frontend/src/plugins/contributions.js
index 07faae60..6f592ce5 100644
--- a/frontend/src/plugins/contributions.js
+++ b/frontend/src/plugins/contributions.js
@@ -20,17 +20,34 @@
*/
import { useEffect, useState } from 'react';
import api from '../services/api';
+import pluginsManifest from './plugins-manifest.json';
// Discover every plugin module at build time. Each plugin is expected to
// expose its components from src/plugins/<slug>/index.{js,jsx}.
const pluginModules = import.meta.glob('../plugins/*/index.{js,jsx}', { eager: true });
+const pluginManifestModules = import.meta.glob('../plugins/*/plugin.json', { eager: true });
+
+function slugFromPluginPath(path, filenamePattern) {
+ const m = path.match(new RegExp(`(?:^\\./|/plugins/)([^/]+)/${filenamePattern}$`));
+ return m ? m[1] : null;
+}
const moduleBySlug = (() => {
const out = {};
for (const [path, mod] of Object.entries(pluginModules)) {
- const m = path.match(/\/plugins\/([^/]+)\/index\.(?:js|jsx)$/);
- if (!m) continue;
- out[m[1]] = mod;
+ const slug = slugFromPluginPath(path, 'index\\.(?:js|jsx)');
+ if (!slug || slug === 'sdk') continue;
+ out[slug] = mod;
+ }
+ return out;
+})();
+
+const localManifestBySlug = (() => {
+ const out = {};
+ for (const [path, mod] of Object.entries(pluginManifestModules)) {
+ const slug = slugFromPluginPath(path, 'plugin\\.json');
+ if (!slug) continue;
+ out[slug] = mod.default || mod;
}
return out;
})();
@@ -60,6 +77,53 @@ const EMPTY = {
layouts: [],
};
+function tagItems(items, slug) {
+ return (items || [])
+ .filter((item) => item && typeof item === 'object')
+ .map((item) => ({ ...item, plugin: slug }));
+}
+
+function getBuildTimeContributions() {
+ const installed = Array.isArray(pluginsManifest?.plugins)
+ ? pluginsManifest.plugins
+ : [];
+
+ const nav = [];
+ const routes = [];
+ const page_titles = {};
+ const command_palette = [];
+ const widgets = [];
+ const layouts = [];
+
+ for (const entry of installed) {
+ const slug = entry?.slug || entry?.name;
+ if (!slug) continue;
+
+ const manifest = localManifestBySlug[slug];
+ const contrib = manifest?.contributions;
+ if (!contrib || typeof contrib !== 'object') continue;
+
+ nav.push(...tagItems(contrib.nav, slug));
+ routes.push(...tagItems(contrib.routes, slug));
+ command_palette.push(...tagItems(contrib.command_palette, slug));
+ widgets.push(...tagItems(contrib.widgets, slug));
+ layouts.push(...tagItems(contrib.layouts, slug));
+
+ if (contrib.page_titles && typeof contrib.page_titles === 'object') {
+ Object.assign(page_titles, contrib.page_titles);
+ }
+ }
+
+ return {
+ nav,
+ routes,
+ page_titles,
+ command_palette,
+ widgets,
+ layouts,
+ };
+}
+
// Built-in layout ids. These are reserved — a plugin can't redefine them.
// padded → routes go inside DashboardLayout, normal padding (default)
// full → routes go inside DashboardLayout, no padding (FULL_PAGE_ROUTES)
@@ -103,10 +167,13 @@ export function refreshContributions() {
return merged;
})
.catch(() => {
- // No active plugins / endpoint missing / unauthenticated —
- // fall back to an empty envelope so the host renders normally.
- notify(EMPTY);
- return EMPTY;
+ // If the backend contribution endpoint is unavailable (common
+ // while running only the Vite dev server), use the active plugin
+ // manifest baked into this frontend build instead of leaving
+ // contributed routes blank.
+ const fallback = getBuildTimeContributions();
+ notify(fallback);
+ return fallback;
});
return cachedPromise;
}
diff --git a/frontend/src/plugins/serverkit-git/index.jsx b/frontend/src/plugins/serverkit-git/index.jsx
index dc44d152..7820887a 100644
--- a/frontend/src/plugins/serverkit-git/index.jsx
+++ b/frontend/src/plugins/serverkit-git/index.jsx
@@ -9,4 +9,6 @@
// so the relative import resolves against the host's pages directory.
import GitPage from '../../pages/Git';
-export const GitExtPage = GitPage;
+export function GitExtPage() {
+ return <GitPage basePath="/git-ext" />;
+}
diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.js
index a76ba8bd..6cc117fb 100644
--- a/frontend/src/services/api/client.js
+++ b/frontend/src/services/api/client.js
@@ -1,6 +1,18 @@
-// Base HTTP client — constructor, token management, core request methods
-const API_BASE_URL = import.meta.env.VITE_API_URL ||
- (import.meta.env.PROD ? '/api/v1' : '/api/v1');
+// Base HTTP client - constructor, token management, core request methods
+const AUTH_EXPIRED_EVENT = 'serverkit:auth-expired';
+
+const normalizeApiBaseUrl = (url) => {
+ if (!url) return '/api/v1';
+ const trimmed = url.replace(/\/+$/, '');
+ return trimmed.endsWith('/api/v1') ? trimmed : `${trimmed}/api/v1`;
+};
+
+// In dev, keep browser requests same-origin so Vite can proxy /api to the
+// configured backend target. Calling VITE_API_URL directly bypasses that
+// proxy and exposes CORS/preflight redirects in the browser.
+const API_BASE_URL = import.meta.env.DEV
+ ? '/api/v1'
+ : normalizeApiBaseUrl(import.meta.env.VITE_API_URL);
class ApiClient {
constructor() {
@@ -47,41 +59,36 @@ class ApiClient {
config.body = JSON.stringify(options.body);
}
- try {
- const response = await fetch(url, config);
-
- if (response.status === 401) {
- // flask-jwt-extended returns 401 with `{"msg": "..."}` when
- // the token is the problem; domain endpoints (e.g. wrong
- // pair-code passphrase) return `{"error": "..."}`. Only the
- // former should trigger a token refresh — refreshing on a
- // domain 401 wastes a backend round-trip and burns through
- // rate limits twice as fast.
- const probe = await response.clone().json().catch(() => ({}));
- const isJwtIssue = probe && probe.msg && !probe.error;
-
- if (isJwtIssue) {
- const refreshed = await this.refreshToken();
- if (refreshed) {
- config.headers.Authorization = `Bearer ${this.getToken()}`;
- const retryResponse = await fetch(url, config);
- return this.handleResponse(retryResponse);
- }
- this.clearTokens();
- window.location.href = '/login';
- const err = new Error('Session expired');
- err.status = 401;
- throw err;
+ const response = await fetch(url, config);
+
+ if (response.status === 401) {
+ // flask-jwt-extended returns 401 with `{"msg": "..."}` when
+ // the token is the problem; domain endpoints (e.g. wrong
+ // pair-code passphrase) return `{"error": "..."}`. Only the
+ // former should trigger a token refresh — refreshing on a
+ // domain 401 wastes a backend round-trip and burns through
+ // rate limits twice as fast.
+ const probe = await response.clone().json().catch(() => ({}));
+ const isJwtIssue = probe && probe.msg && !probe.error;
+
+ if (isJwtIssue) {
+ const refreshed = await this.refreshToken();
+ if (refreshed) {
+ config.headers.Authorization = `Bearer ${this.getToken()}`;
+ const retryResponse = await fetch(url, config);
+ return this.handleResponse(retryResponse);
}
- // Domain 401 — fall through so handleResponse throws the
- // server's error message verbatim, with status attached.
+ this.clearTokens();
+ window.dispatchEvent(new Event(AUTH_EXPIRED_EVENT));
+ const err = new Error('Session expired');
+ err.status = 401;
+ throw err;
}
-
- return this.handleResponse(response);
- } catch (error) {
- console.error('API Error:', error);
- throw error;
+ // Domain 401 — fall through so handleResponse throws the
+ // server's error message verbatim, with status attached.
}
+
+ return this.handleResponse(response);
}
async handleResponse(response) {
diff --git a/frontend/src/services/api/plugins.js b/frontend/src/services/api/plugins.js
index 4f67fea6..c406caa2 100644
--- a/frontend/src/services/api/plugins.js
+++ b/frontend/src/services/api/plugins.js
@@ -1,8 +1,8 @@
// Plugin management API methods
export async function getInstalledPlugins(status) {
- const params = status ? `?status=${status}` : '';
- return this.request(`/plugins${params}`);
+ const params = status ? `?status=${encodeURIComponent(status)}` : '';
+ return this.request(`/plugins/${params}`);
}
export async function getPlugin(pluginId) {
diff --git a/frontend/src/services/socket.js b/frontend/src/services/socket.js
index b5d340d0..c4121af1 100644
--- a/frontend/src/services/socket.js
+++ b/frontend/src/services/socket.js
@@ -1,6 +1,11 @@
import { io } from 'socket.io-client';
-const SOCKET_URL = import.meta.env.VITE_API_URL?.replace('/api/v1', '') || window.location.origin;
+const getSocketUrl = () => {
+ if (import.meta.env.DEV) return window.location.origin;
+ return import.meta.env.VITE_API_URL?.replace(/\/api\/v1\/?$/, '') || window.location.origin;
+};
+
+const SOCKET_URL = getSocketUrl();
class SocketService {
constructor() {
diff --git a/frontend/src/styles/pages/_marketplace.scss b/frontend/src/styles/pages/_marketplace.scss
index 61cb69d1..b67423dc 100644
--- a/frontend/src/styles/pages/_marketplace.scss
+++ b/frontend/src/styles/pages/_marketplace.scss
@@ -714,44 +714,6 @@
}
}
- .marketplace-submit-modal {
- max-width: 680px;
-
- .modal-header {
- align-items: flex-start;
-
- h2 {
- margin-bottom: $space-1;
- }
-
- p {
- margin: 0;
- font-size: $font-size-sm;
- }
- }
-
- .modal-close {
- display: inline-flex;
- align-items: center;
- justify-content: center;
-
- svg {
- width: 18px;
- height: 18px;
- }
- }
- }
-
- .marketplace-submit-grid {
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: $space-4;
-
- .form-group--full {
- grid-column: 1 / -1;
- }
- }
-
@media (max-width: 1180px) {
.marketplace-browse-grid {
grid-template-columns: 1fr;
@@ -821,8 +783,7 @@
}
.marketplace-stats,
- .marketplace-side-panel,
- .marketplace-submit-grid {
+ .marketplace-side-panel {
grid-template-columns: 1fr;
}