mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-01 20:55:16 +09:00
Merge pull request #199 from jhd3197/feat/ui-security-polish
feat: UI bug fixes, full mobile pass, security hardening and a11y polish
This commit is contained in:
198 files changed
+4078
-4232
No files matched your search
+9
-2
@@ -7,8 +7,8 @@ release line and the `main` branch.
|
||||
|
||||
| Version | Supported |
|
||||
|---------|-----------|
|
||||
| 1.7.x | ✅ |
|
||||
| < 1.7 | ❌ (please upgrade) |
|
||||
| 1.11.x | ✅ |
|
||||
| < 1.11 | ❌ (please upgrade) |
|
||||
|
||||
The **agent** ships from its own repository, `jhd3197/serverkit-agent`, and is
|
||||
versioned independently (`vX.Y.Z` — it used `agent-vX.Y.Z` while it lived in this
|
||||
@@ -143,6 +143,13 @@ carry a `sink-safe: <sanitizer> — <why>` comment. `scripts/check-html-sinks.mj
|
||||
fails CI on any new unannotated sink, so a raw-HTML injection point can't land
|
||||
silently.
|
||||
|
||||
## Known Limitations
|
||||
|
||||
- **Tokens in `localStorage`.** The SPA keeps its JWT access/refresh tokens in
|
||||
`localStorage`, so an XSS bug would expose them. The production CSP now
|
||||
forbids inline and `eval` scripts (`script-src 'self'`) to reduce that risk;
|
||||
planned follow-up: move tokens to `httpOnly` `SameSite` cookies with CSRF protection.
|
||||
|
||||
## Extension Trust Model
|
||||
|
||||
Extensions are **in-process code**. An installed extension runs with the panel's
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required
|
||||
from app.services.advanced_ssl_service import AdvancedSSLService
|
||||
@@ -6,6 +7,8 @@ from app.models.audit_log import AuditLog
|
||||
from app.middleware.rbac import get_current_user
|
||||
from app.api._request import json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
advanced_ssl_bp = Blueprint('advanced_ssl', __name__)
|
||||
|
||||
|
||||
@@ -79,8 +82,9 @@ def upload_cert():
|
||||
try:
|
||||
result = AdvancedSSLService.upload_custom_cert(domain, cert, key, chain)
|
||||
return jsonify(result), 201
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
except Exception:
|
||||
logger.exception('Custom certificate upload failed')
|
||||
return jsonify({'error': 'Could not install the certificate'}), 400
|
||||
|
||||
|
||||
@advanced_ssl_bp.route('/health/<domain>', methods=['GET'])
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
import os
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required
|
||||
@@ -7,10 +8,21 @@ from app.services.backup_service import BackupService
|
||||
from app.services.backup_policy_service import BackupPolicyService, BackupPolicyError
|
||||
from app.services.storage_provider_service import StorageProviderService
|
||||
from app import db, paths
|
||||
from app.exceptions import field_required, not_found
|
||||
from app.exceptions import DependencyUnavailableError, field_required, not_found
|
||||
from app.api._request import json_object
|
||||
|
||||
backups_bp = Blueprint('backups', __name__)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_STORAGE_UNAVAILABLE = ('Backup storage is not accessible: the panel cannot create or read '
|
||||
'its backup directory. Check its ownership and permissions.')
|
||||
|
||||
|
||||
@backups_bp.errorhandler(PermissionError)
|
||||
def _backup_dir_unavailable(exc):
|
||||
logger.error('Backup directory is not writable: %s', exc)
|
||||
err = DependencyUnavailableError('Backup directory is not writable', code='backup_dir_unavailable')
|
||||
return jsonify(err.to_dict()), err.status_code
|
||||
|
||||
|
||||
# UI-facing metadata for the CORE target types. Extension kinds
|
||||
@@ -62,7 +74,12 @@ def list_target_types():
|
||||
def list_backups():
|
||||
"""List all backups."""
|
||||
backup_type = request.args.get('type')
|
||||
backups = BackupService.list_backups(backup_type)
|
||||
try:
|
||||
backups = BackupService.list_backups(backup_type)
|
||||
except OSError:
|
||||
# e.g. PermissionError creating /var/backups/serverkit: keep the page usable.
|
||||
logger.exception('Backup directory is not accessible')
|
||||
return jsonify({'backups': [], 'warning': _STORAGE_UNAVAILABLE}), 200
|
||||
return jsonify({'backups': backups}), 200
|
||||
|
||||
|
||||
@@ -70,7 +87,14 @@ def list_backups():
|
||||
@admin_required
|
||||
def get_stats():
|
||||
"""Get backup statistics."""
|
||||
stats = BackupService.get_backup_stats()
|
||||
try:
|
||||
stats = BackupService.get_backup_stats()
|
||||
except OSError:
|
||||
logger.exception('Backup directory is not accessible')
|
||||
stats = {'total_backups': 0, 'application_backups': 0, 'database_backups': 0,
|
||||
'file_backups': 0, 'total_size': 0, 'total_size_human': '0 B',
|
||||
'remote_count': 0, 'remote_size': 0, 'remote_size_human': '0 B',
|
||||
'warning': _STORAGE_UNAVAILABLE}
|
||||
return jsonify(stats), 200
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ Two endpoints:
|
||||
* POST /generate — pure: given a plan dict, return Dockerfile + compose.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
@@ -25,6 +26,8 @@ from app.services.source_connection_service import SourceConnectionService
|
||||
from app.middleware.rbac import developer_required, get_current_user
|
||||
from app.api._request import json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
buildpacks_bp = Blueprint('buildpacks', __name__)
|
||||
|
||||
|
||||
@@ -113,8 +116,9 @@ def detect():
|
||||
plan = BuildpackService.detect(clone_target)
|
||||
BuildpackService.cache_plan(cache_key_url, plan, commit or branch)
|
||||
return jsonify(_build_response(plan, app_name)), 200
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
return jsonify({'error': str(exc)}), 400
|
||||
except Exception: # pragma: no cover - defensive
|
||||
logger.exception('Buildpack detection failed')
|
||||
return jsonify({'error': 'Could not detect a build plan for this repository'}), 400
|
||||
finally:
|
||||
shutil.rmtree(workdir, ignore_errors=True)
|
||||
|
||||
|
||||
+25
-14
@@ -1,3 +1,5 @@
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||
from app.models import User, Application
|
||||
@@ -7,6 +9,8 @@ from app import db, paths
|
||||
from app.error_reporting import unexpected_response
|
||||
from app.api._request import json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
docker_bp = Blueprint('docker', __name__)
|
||||
|
||||
|
||||
@@ -505,8 +509,9 @@ def docker_cleanup():
|
||||
}
|
||||
else:
|
||||
results['containers'] = {'removed': 0, 'success': True}
|
||||
except Exception as e:
|
||||
results['containers'] = {'error': str(e)}
|
||||
except Exception:
|
||||
logger.exception('Docker cleanup step failed')
|
||||
results['containers'] = {'error': 'Cleanup step failed; see server log'}
|
||||
|
||||
# Remove dangling images
|
||||
try:
|
||||
@@ -515,8 +520,9 @@ def docker_cleanup():
|
||||
'success': result['success'],
|
||||
'output': result['output'].strip()
|
||||
}
|
||||
except Exception as e:
|
||||
results['images'] = {'error': str(e)}
|
||||
except Exception:
|
||||
logger.exception('Docker cleanup step failed')
|
||||
results['images'] = {'error': 'Cleanup step failed; see server log'}
|
||||
|
||||
# Remove unused networks
|
||||
try:
|
||||
@@ -525,8 +531,9 @@ def docker_cleanup():
|
||||
'success': result['success'],
|
||||
'output': result['output'].strip()
|
||||
}
|
||||
except Exception as e:
|
||||
results['networks'] = {'error': str(e)}
|
||||
except Exception:
|
||||
logger.exception('Docker cleanup step failed')
|
||||
results['networks'] = {'error': 'Cleanup step failed; see server log'}
|
||||
|
||||
# Remove unused volumes (optional)
|
||||
if include_volumes:
|
||||
@@ -536,8 +543,9 @@ def docker_cleanup():
|
||||
'success': result['success'],
|
||||
'output': result['output'].strip()
|
||||
}
|
||||
except Exception as e:
|
||||
results['volumes'] = {'error': str(e)}
|
||||
except Exception:
|
||||
logger.exception('Docker cleanup step failed')
|
||||
results['volumes'] = {'error': 'Cleanup step failed; see server log'}
|
||||
else:
|
||||
results['volumes'] = {'skipped': True, 'message': 'Volume cleanup not requested'}
|
||||
|
||||
@@ -581,24 +589,27 @@ def cleanup_all_apps():
|
||||
try:
|
||||
compose_result = DockerService.compose_down(app.root_path, volumes=True, remove_orphans=True)
|
||||
app_result['steps'].append({'action': 'docker_down', 'success': compose_result.get('success', False)})
|
||||
except Exception as e:
|
||||
app_result['steps'].append({'action': 'docker_down', 'error': str(e)})
|
||||
except Exception:
|
||||
logger.exception('App cleanup step failed')
|
||||
app_result['steps'].append({'action': 'docker_down', 'error': 'Step failed; see server log'})
|
||||
app_result['success'] = False
|
||||
|
||||
# Delete folder
|
||||
try:
|
||||
shutil.rmtree(app.root_path)
|
||||
app_result['steps'].append({'action': 'delete_folder', 'success': True})
|
||||
except Exception as e:
|
||||
app_result['steps'].append({'action': 'delete_folder', 'error': str(e)})
|
||||
except Exception:
|
||||
logger.exception('App cleanup step failed')
|
||||
app_result['steps'].append({'action': 'delete_folder', 'error': 'Step failed; see server log'})
|
||||
app_result['success'] = False
|
||||
|
||||
# Remove from database
|
||||
try:
|
||||
db.session.delete(app)
|
||||
app_result['steps'].append({'action': 'delete_db', 'success': True})
|
||||
except Exception as e:
|
||||
app_result['steps'].append({'action': 'delete_db', 'error': str(e)})
|
||||
except Exception:
|
||||
logger.exception('App cleanup step failed')
|
||||
app_result['steps'].append({'action': 'delete_db', 'error': 'Step failed; see server log'})
|
||||
app_result['success'] = False
|
||||
|
||||
results.append(app_result)
|
||||
|
||||
@@ -643,10 +643,21 @@ def list_updates():
|
||||
"""List installed plugins that have a newer version in the registry.
|
||||
|
||||
Each entry: {slug, plugin_id, installed_version, available_version,
|
||||
update_available, compatible, source}.
|
||||
update_available, compatible, source, display_name, update_source,
|
||||
incompatible_reason, requires_ack, risk}. ``?refresh=1`` refetches the
|
||||
registry index first.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from app.services import registry_service
|
||||
from app.services.plugin_service import check_for_updates
|
||||
return jsonify({'updates': check_for_updates()})
|
||||
refresh = request.args.get('refresh', '').lower() in ('1', 'true', 'yes')
|
||||
updates = check_for_updates(refresh=refresh)
|
||||
return jsonify({
|
||||
'updates': updates,
|
||||
'count': sum(1 for u in updates if u['update_available'] and u['compatible']),
|
||||
'checked_at': datetime.now(timezone.utc).isoformat(),
|
||||
'registry_source': registry_service.registry_source_label(),
|
||||
})
|
||||
|
||||
|
||||
@plugins_bp.route('/<int:plugin_id>/update', methods=['POST'])
|
||||
@@ -670,21 +681,23 @@ def update_plugin_route(plugin_id):
|
||||
if not plugin:
|
||||
return jsonify({'error': 'Plugin not found'}), 404
|
||||
|
||||
entry = registry_service.get_entry(plugin.slug)
|
||||
if not entry:
|
||||
builtin = plugin.source_type == 'builtin' # local bundled code: no consent
|
||||
entry = None if builtin else registry_service.get_entry(plugin.slug)
|
||||
if not builtin and not entry:
|
||||
return jsonify({
|
||||
'error': f"No registry entry for '{plugin.slug}' — cannot update "
|
||||
f"from the registry."
|
||||
}), 400
|
||||
# Hidden means not updatable either: unreviewed entries only exist in
|
||||
# development contexts (see registry_service._show_unreviewed).
|
||||
if entry.get('trust') == 'unreviewed' \
|
||||
if entry and entry.get('trust') == 'unreviewed' \
|
||||
and not registry_service._show_unreviewed():
|
||||
return jsonify({'error': 'Extension not found in the registry'}), 404
|
||||
|
||||
body = json_object(optional=True)
|
||||
acknowledged = body.get('acknowledge_risk') is True
|
||||
reason, message = registry_service.consent_gate(entry, acknowledged)
|
||||
reason, message = (None, None) if builtin else \
|
||||
registry_service.consent_gate(entry, acknowledged)
|
||||
if reason:
|
||||
return jsonify({
|
||||
'error': f'{message} Resend with acknowledge_risk: true to proceed.',
|
||||
@@ -703,7 +716,7 @@ def update_plugin_route(plugin_id):
|
||||
target_id=plugin.id,
|
||||
details={
|
||||
'name': plugin.name, 'version': plugin.version,
|
||||
'source': 'registry-update',
|
||||
'source': 'builtin-update' if builtin else 'registry-update',
|
||||
# Forensics (audit I7): the signature verdict of the bytes
|
||||
# that just landed.
|
||||
'signature': sig.get('status') or 'unsigned',
|
||||
|
||||
@@ -891,15 +891,15 @@ def get_server_metrics(server_id):
|
||||
try:
|
||||
from_dt = datetime.fromisoformat(from_time.replace('Z', '+00:00'))
|
||||
query = query.filter(ServerMetrics.timestamp >= from_dt)
|
||||
except:
|
||||
pass
|
||||
except ValueError:
|
||||
raise ValidationError("Invalid 'from' timestamp; use ISO 8601")
|
||||
|
||||
if to_time:
|
||||
try:
|
||||
to_dt = datetime.fromisoformat(to_time.replace('Z', '+00:00'))
|
||||
query = query.filter(ServerMetrics.timestamp <= to_dt)
|
||||
except:
|
||||
pass
|
||||
except ValueError:
|
||||
raise ValidationError("Invalid 'to' timestamp; use ISO 8601")
|
||||
|
||||
metrics = query.order_by(ServerMetrics.timestamp.desc()).limit(limit).all()
|
||||
|
||||
|
||||
@@ -413,7 +413,8 @@ def _compare_versions(v1, v2):
|
||||
elif a > b:
|
||||
return 1
|
||||
return 0
|
||||
except:
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
current_app.logger.warning('Could not compare versions %r and %r', v1, v2)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""SSO / OAuth API blueprint."""
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from flask import Blueprint, request, jsonify, session
|
||||
from flask_jwt_extended import (
|
||||
@@ -16,6 +17,8 @@ from app.error_reporting import record_unexpected
|
||||
from app.exceptions import NotFoundError
|
||||
from app.api._request import json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
sso_bp = Blueprint('sso', __name__)
|
||||
|
||||
VALID_PROVIDERS = ('google', 'github', 'oidc', 'saml')
|
||||
@@ -47,8 +50,9 @@ def authorize(provider):
|
||||
try:
|
||||
auth_url, state = sso_service.generate_auth_url(provider, redirect_uri)
|
||||
return jsonify({'auth_url': auth_url, 'state': state}), 200
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
except Exception:
|
||||
logger.exception('SSO authorize failed for %s', provider)
|
||||
return jsonify({'error': 'Could not start single sign-on'}), 400
|
||||
|
||||
|
||||
@sso_bp.route('/callback/<provider>', methods=['POST'])
|
||||
@@ -169,8 +173,9 @@ def link_provider(provider):
|
||||
|
||||
try:
|
||||
profile = sso_service.handle_oauth_callback(provider, code, state, redirect_uri)
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
except Exception:
|
||||
logger.exception('SSO link callback failed for %s', provider)
|
||||
return jsonify({'error': 'Single sign-on failed'}), 400
|
||||
|
||||
# Check if this identity is already linked to another user
|
||||
existing = OAuthIdentity.query.filter_by(
|
||||
|
||||
@@ -84,7 +84,7 @@ def check_update():
|
||||
def parse_version(v):
|
||||
try:
|
||||
return tuple(int(x) for x in v.split('.'))
|
||||
except:
|
||||
except ValueError:
|
||||
return (0, 0, 0)
|
||||
|
||||
if parse_version(latest_version) > parse_version(current_version):
|
||||
@@ -96,7 +96,8 @@ def check_update():
|
||||
else:
|
||||
result['error'] = f'GitHub API error: {e.code}'
|
||||
except Exception as e:
|
||||
result['error'] = f'Failed to check for updates: {str(e)}'
|
||||
current_app.logger.warning('Update check failed: %s', e)
|
||||
result['error'] = 'Failed to check for updates'
|
||||
|
||||
# Cache the result
|
||||
_update_cache['last_check'] = time.time()
|
||||
|
||||
@@ -6,6 +6,7 @@ Routes are mounted at ``/api/v1/waf``. Reads require access to the target app;
|
||||
mutations and install require an admin user (mirrors ``app/api/dns_zones.py``).
|
||||
Service ``ValueError``s map to HTTP 400.
|
||||
"""
|
||||
import logging
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
@@ -14,6 +15,8 @@ from app.middleware.rbac import require_admin_user
|
||||
from app.api._access import require_app
|
||||
from app.api._request import json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
waf_bp = Blueprint('waf', __name__)
|
||||
|
||||
|
||||
@@ -47,8 +50,9 @@ def update_policy(app_id):
|
||||
# ModSecurity isn't present on the host.
|
||||
try:
|
||||
apply_result = WafService.apply(app_id)
|
||||
except Exception as e: # pragma: no cover - defensive
|
||||
apply_result = {'success': False, 'error': str(e)}
|
||||
except Exception: # pragma: no cover - defensive
|
||||
logger.exception('WAF apply failed for app %s', app_id)
|
||||
apply_result = {'success': False, 'error': 'Failed to apply WAF policy'}
|
||||
|
||||
response = policy.to_dict()
|
||||
response['apply'] = apply_result
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"--border-strong": "#2c313b",
|
||||
"--text": "#e9ebf0",
|
||||
"--text-dim": "#9aa1af",
|
||||
"--text-faint": "#646b7a",
|
||||
"--text-faint": "#868e9c",
|
||||
"--text-ghost": "#444b58",
|
||||
"--green": "#3ddc97",
|
||||
"--green-bg": "rgba(61,220,151,0.12)",
|
||||
@@ -54,7 +54,7 @@
|
||||
"--border-strong": "#cdd3e0",
|
||||
"--text": "#161a23",
|
||||
"--text-dim": "#515a6b",
|
||||
"--text-faint": "#79818f",
|
||||
"--text-faint": "#5f6777",
|
||||
"--text-ghost": "#a6adba",
|
||||
"--green": "#3ddc97",
|
||||
"--green-bg": "rgba(61,220,151,0.12)",
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
from flask import Flask
|
||||
|
||||
# sha256 of the build-injected import map (frontend/vite.config.js, from
|
||||
# src/plugins/runtime/vendorManifest.js). test_security_headers recomputes it.
|
||||
VENDOR_IMPORTMAP_HASH = 'sha256-lIJXjhqB4GwFLcjRTSjM91Q7vwXxH4Wbcn475CzkW4U='
|
||||
|
||||
|
||||
def register_security_headers(app: Flask):
|
||||
"""Register security headers as an after_request handler."""
|
||||
@@ -37,9 +41,13 @@ def register_security_headers(app: Flask):
|
||||
"form-action 'self' https://github.com",
|
||||
]
|
||||
else:
|
||||
# style-src keeps 'unsafe-inline' because React renders style="" attributes;
|
||||
# script-src has no 'unsafe-inline'/'unsafe-eval': the FOUC snippet is
|
||||
# /theme-init.js; the one inline script (build-injected vendor importmap)
|
||||
# is allowed by hash; blob: is for runtime extensions (plugins/runtime/loader.js).
|
||||
csp_directives = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
|
||||
"script-src 'self' '%s' blob:" % VENDOR_IMPORTMAP_HASH,
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: https:",
|
||||
"font-src 'self'",
|
||||
|
||||
@@ -19,10 +19,9 @@ import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models.chat_webhook import ChatWebhookConnection
|
||||
from app.utils import safe_http
|
||||
from app.utils.crypto import encrypt_secret
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -405,8 +404,11 @@ class ChatWebhookService:
|
||||
headers[SIGNATURE_HEADER] = 'sha256=' + signature
|
||||
|
||||
try:
|
||||
resp = requests.post(url, data=body, headers=headers,
|
||||
timeout=_REQUEST_TIMEOUT)
|
||||
resp = safe_http.post(url, data=body, headers=headers,
|
||||
timeout=_REQUEST_TIMEOUT)
|
||||
except safe_http.UnsafeURLError as exc:
|
||||
# Non-retryable: the URL itself is the problem, retrying can't help.
|
||||
return DeliveryResult.skipped(f'webhook url refused: {exc}')
|
||||
except Exception as exc: # network error -> retryable failure
|
||||
return DeliveryResult.failed(str(exc))
|
||||
|
||||
|
||||
@@ -214,7 +214,7 @@ class MonitoringService:
|
||||
@classmethod
|
||||
def send_webhook_alert(cls, alerts: List[Dict]) -> Dict:
|
||||
"""Send webhook alert notification."""
|
||||
import requests
|
||||
from app.utils import safe_http
|
||||
|
||||
config = cls.get_config()
|
||||
webhook_config = config.get('webhook', {})
|
||||
@@ -229,7 +229,7 @@ class MonitoringService:
|
||||
'alerts': alerts
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
response = safe_http.post(
|
||||
webhook_config['url'],
|
||||
json=payload,
|
||||
timeout=10
|
||||
@@ -239,6 +239,8 @@ class MonitoringService:
|
||||
return {'success': True, 'message': 'Webhook sent'}
|
||||
return {'success': False, 'error': f'Webhook returned {response.status_code}'}
|
||||
|
||||
except safe_http.UnsafeURLError as e:
|
||||
return {'success': False, 'error': f'Webhook URL refused: {e}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
|
||||
@@ -214,13 +214,13 @@ SSL_BLOCK = '''
|
||||
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
|
||||
|
||||
# Baseline response-header hardening. These are safe for reverse-proxied apps;
|
||||
# the CSP is deliberately permissive so it does not break managed apps while
|
||||
# the CSP is permissive (inline allowed, no eval) so it does not break managed apps while
|
||||
# still satisfying "a CSP is present" and blocking cross-origin framing.
|
||||
# Tighten the CSP per-app when the upstream can support a stricter policy.
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob: https:; frame-ancestors 'self'; upgrade-insecure-requests" always;
|
||||
add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' data: blob: https:; frame-ancestors 'self'; upgrade-insecure-requests" always;
|
||||
'''
|
||||
|
||||
SSL_REDIRECT_TEMPLATE = '''server {{
|
||||
|
||||
@@ -2133,37 +2133,71 @@ def install_registry_extension(slug, user_id=None):
|
||||
)
|
||||
|
||||
|
||||
def check_for_updates():
|
||||
"""Compare installed plugins to the registry; return update candidates.
|
||||
def check_for_updates(refresh=False):
|
||||
"""Compare installed plugins to the registry / bundled manifests.
|
||||
|
||||
Update v1 is registry-driven: a plugin whose slug is in the registry with a
|
||||
higher version than installed is flagged. Panel-version compatibility is
|
||||
surfaced so the UI can gray out an update the panel can't run yet. The
|
||||
installed plugin's ``source_type`` is included so callers can see the
|
||||
provenance the update would cross (audit M2 — a registry entry only ever
|
||||
matches on slug; the update route's consent gate is the enforcement).
|
||||
Registry-driven for url/registry rows (matched on slug); ``builtin`` rows
|
||||
compare against the bundled manifest in builtin-extensions/. Rows with no
|
||||
known source of truth (url/local/upload/git without a registry entry) are
|
||||
skipped. A malformed version means "no update"; one bad row never breaks
|
||||
the list. ``requires_ack``/``risk`` mirror the update route's consent gate.
|
||||
"""
|
||||
from app.services import registry_service
|
||||
from app.utils.version import compare_versions, version_satisfies, get_panel_version
|
||||
if refresh:
|
||||
registry_service.refresh(force=True)
|
||||
panel = get_panel_version()
|
||||
bundled = {b['slug']: b['manifest'] for b in list_builtin_extensions()}
|
||||
out = []
|
||||
for p in InstalledPlugin.query.all():
|
||||
entry = registry_service.get_entry(p.slug)
|
||||
if not entry:
|
||||
continue
|
||||
available = entry.get('version')
|
||||
out.append({
|
||||
'slug': p.slug,
|
||||
'plugin_id': p.id,
|
||||
'installed_version': p.version,
|
||||
'available_version': available,
|
||||
'update_available': compare_versions(available, p.version) > 0,
|
||||
'compatible': version_satisfies(
|
||||
panel, entry.get('min_panel_version'), entry.get('max_panel_version')
|
||||
),
|
||||
'source': entry.get('source'),
|
||||
'installed_source_type': p.source_type,
|
||||
})
|
||||
try:
|
||||
if p.source_type == 'builtin':
|
||||
m = bundled.get(p.slug)
|
||||
if not m:
|
||||
continue
|
||||
available = m.get('version')
|
||||
row = {
|
||||
'display_name': m.get('display_name') or p.name,
|
||||
'update_source': 'builtin', 'source': None,
|
||||
'compatible': True, 'requires_ack': False, 'risk': None,
|
||||
}
|
||||
minv = m.get('min_panel_version')
|
||||
maxv = m.get('max_panel_version')
|
||||
else:
|
||||
entry = registry_service.get_entry(p.slug)
|
||||
if not entry:
|
||||
continue
|
||||
available = entry.get('version')
|
||||
minv = entry.get('min_panel_version')
|
||||
maxv = entry.get('max_panel_version')
|
||||
risk, _ = registry_service.consent_gate(entry, False)
|
||||
row = {
|
||||
'display_name': entry.get('display_name') or p.name,
|
||||
'update_source': 'registry', 'source': entry.get('source'),
|
||||
'requires_ack': bool(risk), 'risk': risk,
|
||||
}
|
||||
try:
|
||||
newer = compare_versions(available, p.version) > 0
|
||||
except Exception: # noqa: BLE001 - malformed version = no update
|
||||
newer = False
|
||||
compatible = version_satisfies(panel, minv, maxv)
|
||||
row['compatible'] = bool(compatible)
|
||||
row['incompatible_reason'] = None if compatible else (
|
||||
f"Needs panel {minv or '*'}–{maxv or '*'} (this panel is {panel})."
|
||||
)
|
||||
if minv:
|
||||
row['min_panel_version'] = minv
|
||||
out.append({
|
||||
'slug': p.slug,
|
||||
'plugin_id': p.id,
|
||||
'installed_version': p.version,
|
||||
'available_version': available,
|
||||
'update_available': newer,
|
||||
'installed_source_type': p.source_type,
|
||||
**row,
|
||||
})
|
||||
except Exception as exc: # noqa: BLE001 - isolate bad rows
|
||||
logger.warning(f'Update check skipped {p.slug}: {exc}')
|
||||
return out
|
||||
|
||||
|
||||
@@ -2173,6 +2207,15 @@ def update_plugin(plugin_id, user_id=None):
|
||||
plugin = InstalledPlugin.query.get(plugin_id)
|
||||
if not plugin:
|
||||
raise ValueError('Plugin not found')
|
||||
folder = next((b['path'] for b in list_builtin_extensions()
|
||||
if b['slug'] == plugin.slug), None) \
|
||||
if plugin.source_type == 'builtin' else None
|
||||
# A builtin row with no bundled folder (e.g. stamped by hand) falls
|
||||
# through to the registry path below.
|
||||
if folder:
|
||||
return install_from_path(
|
||||
folder, user_id=user_id, force=True, source_type='builtin',
|
||||
)
|
||||
entry = registry_service.get_entry(plugin.slug)
|
||||
if not entry:
|
||||
raise ValueError(
|
||||
|
||||
+10
-6
@@ -5,6 +5,8 @@ import threading
|
||||
import time
|
||||
import queue
|
||||
import re
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
from app.services.system_service import SystemService
|
||||
from app.services.log_service import LogService, LogStreamer
|
||||
@@ -12,6 +14,8 @@ from app.services.docker_service import DockerService
|
||||
from app import sockets_rooms as rooms
|
||||
from app.utils.background_loop import BackgroundLoop
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AuthorizedSocketIO(SocketIO):
|
||||
"""Recheck audience authorization before every server-side delivery.
|
||||
@@ -775,11 +779,11 @@ def handle_subscribe_container_logs(data):
|
||||
try:
|
||||
process.terminate()
|
||||
process.wait(timeout=2)
|
||||
except:
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
try:
|
||||
process.kill()
|
||||
except:
|
||||
pass
|
||||
except OSError as kill_err:
|
||||
logger.debug('Could not kill log stream process: %s', kill_err)
|
||||
|
||||
thread = threading.Thread(target=stream_logs, daemon=True)
|
||||
thread.start()
|
||||
@@ -836,11 +840,11 @@ def stop_container_log_stream(sid: str):
|
||||
try:
|
||||
process.terminate()
|
||||
process.wait(timeout=2)
|
||||
except:
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
try:
|
||||
process.kill()
|
||||
except:
|
||||
pass
|
||||
except OSError as kill_err:
|
||||
logger.debug('Could not kill log stream process: %s', kill_err)
|
||||
|
||||
|
||||
def emit_container_log(app_id: int, line: str, level: str = 'info'):
|
||||
|
||||
@@ -1 +1 @@
|
||||
5279
|
||||
6102
|
||||
+8
-8
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"php": "e6d77fd5ac90d438b9f694b3dcf50d63746bd87f3e20030e0c4bd6e94c6f372a",
|
||||
"wordpress": "e6d77fd5ac90d438b9f694b3dcf50d63746bd87f3e20030e0c4bd6e94c6f372a",
|
||||
"flask": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b",
|
||||
"django": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b",
|
||||
"python": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b",
|
||||
"docker": "a18576b49626ed0f88126de8946163720d715016ee24119de22afdb38fda4400",
|
||||
"remote": "7bc871f2c95a333cfe14129ae40df409a3a2165e79fb7c9205510957c95af99f",
|
||||
"static": "91d63c4279f9fa1fa1ecc1cfd0e3f8c5b63e134613d319ae189a4560d3738e28"
|
||||
"php": "a1de4fd08a9d277ecf4c7aaa46514bcae28a05b0a90a87bc2190cfa18dbb237f",
|
||||
"wordpress": "a1de4fd08a9d277ecf4c7aaa46514bcae28a05b0a90a87bc2190cfa18dbb237f",
|
||||
"flask": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c",
|
||||
"django": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c",
|
||||
"python": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c",
|
||||
"docker": "362d30566ba5452cb3ed9e7376da4f95c1fda61e6ec5b6a65b1ef98aa461aca5",
|
||||
"remote": "0589dd632da88d569e41c339681c0a38656037d40b733179986bfc5f80f5bd27",
|
||||
"static": "d3ff984ff1aac1c22e8e59f70f7fdf0c3d838726b4621f3313aa7cd4d78ee139"
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
"""GET /backups must not 500 when the backup directory cannot be created."""
|
||||
import pytest
|
||||
|
||||
from app.services.backup_service import BackupService
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unwritable(monkeypatch):
|
||||
def deny():
|
||||
raise PermissionError(13, 'Permission denied', '/var/backups/serverkit')
|
||||
monkeypatch.setattr(BackupService, 'ensure_backup_dirs', deny)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('path', ['/api/v1/backups', '/api/v1/backups/stats'])
|
||||
def test_get_degrades_with_a_warning(client, auth_headers, unwritable, path):
|
||||
resp = client.get(path, headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
assert 'not accessible' in body['warning']
|
||||
assert '/var/backups' not in body['warning']
|
||||
assert body.get('backups', []) == []
|
||||
|
||||
|
||||
def test_create_returns_503_with_code_when_dir_unwritable(client, auth_headers, unwritable):
|
||||
resp = client.post('/api/v1/backups/database', headers=auth_headers,
|
||||
json={'db_type': 'mysql', 'db_name': 'x'})
|
||||
|
||||
assert resp.status_code == 503
|
||||
body = resp.get_json()
|
||||
assert body['code'] == 'backup_dir_unavailable'
|
||||
assert body['error'] == 'Backup directory is not writable'
|
||||
assert '/var/backups' not in resp.get_data(as_text=True)
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Unexpected failures answer with a generic message; the detail is only logged."""
|
||||
from app.services import sso_service
|
||||
|
||||
|
||||
def test_sso_authorize_does_not_echo_exception_text(client, monkeypatch):
|
||||
def boom(*a, **kw):
|
||||
raise RuntimeError('secret internal path /etc/serverkit/oidc.key')
|
||||
monkeypatch.setattr(sso_service, 'generate_auth_url', boom)
|
||||
|
||||
resp = client.get('/api/v1/sso/authorize/google?redirect_uri=http://localhost/cb')
|
||||
|
||||
assert resp.status_code == 400
|
||||
assert '/etc/serverkit' not in resp.get_data(as_text=True)
|
||||
@@ -321,7 +321,7 @@ class TestSigningAndDelivery:
|
||||
captured.update({'url': url, 'data': data, 'headers': headers})
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr('app.services.chat_webhook_service.requests.post', fake_post)
|
||||
monkeypatch.setattr('app.services.chat_webhook_service.safe_http.post', fake_post)
|
||||
|
||||
user = _make_user()
|
||||
conn = ChatWebhookService.add({'kind': 'webhook', 'name': 'Ops', 'url': 'https://hooks/x',
|
||||
@@ -392,7 +392,7 @@ class TestConnectionTesting:
|
||||
status_code = 503
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.chat_webhook_service.requests.post',
|
||||
'app.services.chat_webhook_service.safe_http.post',
|
||||
lambda *args, **kwargs: _Resp(),
|
||||
)
|
||||
conn = ChatWebhookService.add({
|
||||
@@ -428,7 +428,7 @@ class TestConnectionTesting:
|
||||
raise RuntimeError(f'failed POST {url}')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.chat_webhook_service.requests.post', fail_post,
|
||||
'app.services.chat_webhook_service.safe_http.post', fail_post,
|
||||
)
|
||||
secret_url = 'https://hooks.example/super-secret-token'
|
||||
conn = ChatWebhookService.add({
|
||||
@@ -454,7 +454,7 @@ class TestConnectionTesting:
|
||||
raise RuntimeError(f'failed POST {url}')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.chat_webhook_service.requests.post', fail_post,
|
||||
'app.services.chat_webhook_service.safe_http.post', fail_post,
|
||||
)
|
||||
conn = ChatWebhookService.add({
|
||||
'kind': 'webhook',
|
||||
@@ -624,7 +624,7 @@ class TestApi:
|
||||
status_code = 503
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.chat_webhook_service.requests.post',
|
||||
'app.services.chat_webhook_service.safe_http.post',
|
||||
lambda *args, **kwargs: _Resp(),
|
||||
)
|
||||
conn = ChatWebhookService.add({
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""PermissionService + User permission resolution per role."""
|
||||
import pytest
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.permission_service import PermissionService
|
||||
|
||||
|
||||
def _user(role, name=None):
|
||||
u = User(email=f'{name or role}@example.com', username=name or role,
|
||||
password_hash=generate_password_hash('x'), role=role, is_active=True)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def test_role_templates_cover_every_feature_for_admin():
|
||||
admin = PermissionService.get_role_template('admin')
|
||||
assert set(admin) == set(User.PERMISSION_FEATURES)
|
||||
assert all(v == {'read': True, 'write': True} for v in admin.values())
|
||||
|
||||
|
||||
def test_unknown_role_has_no_permissions(app):
|
||||
assert PermissionService.get_role_template('wizard') == {}
|
||||
u = _user('viewer', 'nobody')
|
||||
u.role = 'wizard'
|
||||
assert not u.has_permission('files')
|
||||
|
||||
|
||||
def test_developer_defaults_follow_template(app):
|
||||
dev = _user('developer')
|
||||
assert dev.has_permission('applications', 'write')
|
||||
assert dev.has_permission('monitoring', 'read')
|
||||
assert not dev.has_permission('monitoring', 'write')
|
||||
assert not dev.has_permission('users') # not in the developer template
|
||||
|
||||
|
||||
def test_admin_always_allowed(app):
|
||||
admin = _user('admin')
|
||||
assert all(admin.has_permission(f, 'write') for f in User.PERMISSION_FEATURES)
|
||||
assert admin.has_permission('anything-at-all')
|
||||
|
||||
|
||||
def test_viewer_cannot_write_anything(app):
|
||||
viewer = _user('viewer')
|
||||
assert not any(viewer.has_permission(f, 'write') for f in User.PERMISSION_FEATURES)
|
||||
|
||||
|
||||
def test_get_user_permissions_missing_user(app):
|
||||
assert PermissionService.get_user_permissions(999999) is None
|
||||
|
||||
|
||||
def test_update_custom_permissions_overrides_role(app):
|
||||
dev = _user('developer')
|
||||
res = PermissionService.update_user_permissions(
|
||||
dev.id, {'files': {'read': True, 'write': False}})
|
||||
assert res['success']
|
||||
assert res['permissions'] == {'files': {'read': True, 'write': False}}
|
||||
assert not dev.has_permission('files', 'write')
|
||||
assert not dev.has_permission('applications') # custom set replaces the template wholesale
|
||||
|
||||
|
||||
def test_reset_restores_role_template(app):
|
||||
dev = _user('developer')
|
||||
PermissionService.update_user_permissions(dev.id, {'files': {'read': True}})
|
||||
res = PermissionService.reset_to_role_defaults(dev.id)
|
||||
assert res['success'] and res['permissions'] == User.ROLE_PERMISSION_TEMPLATES['developer']
|
||||
assert dev.permissions is None
|
||||
|
||||
|
||||
def test_admin_permissions_cannot_be_customized(app):
|
||||
admin = _user('admin')
|
||||
res = PermissionService.update_user_permissions(admin.id, {'files': {'read': False}})
|
||||
assert res == {'success': False, 'error': 'Admin permissions cannot be customized'}
|
||||
|
||||
|
||||
def test_unknown_user_is_reported(app):
|
||||
assert PermissionService.update_user_permissions(424242, {}) == {
|
||||
'success': False, 'error': 'User not found'}
|
||||
assert PermissionService.reset_to_role_defaults(424242) == {
|
||||
'success': False, 'error': 'User not found'}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('perms, fragment', [
|
||||
('nope', 'must be an object'),
|
||||
({'bogus': {'read': True}}, 'Unknown feature'),
|
||||
({'files': True}, 'read/write object'),
|
||||
({'files': {'execute': True}}, 'Invalid permission key'),
|
||||
({'files': {'read': 'yes'}}, 'must be boolean'),
|
||||
({'files': {'read': False, 'write': True}}, 'without read'),
|
||||
])
|
||||
def test_validate_permissions_rejects(perms, fragment):
|
||||
assert fragment in PermissionService.validate_permissions(perms)
|
||||
|
||||
|
||||
def test_validate_permissions_accepts_good_input():
|
||||
assert PermissionService.validate_permissions({}) is None
|
||||
assert PermissionService.validate_permissions(
|
||||
{'files': {'read': True, 'write': True}, 'cron': {'read': True}}) is None
|
||||
|
||||
|
||||
def test_invalid_update_does_not_persist(app):
|
||||
dev = _user('developer')
|
||||
res = PermissionService.update_user_permissions(dev.id, {'bogus': {}})
|
||||
assert not res['success']
|
||||
assert dev.permissions is None
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Update detection: registry + builtin rows, compat, consent hints, API shape."""
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models.plugin import InstalledPlugin
|
||||
from app.services import plugin_service, registry_service
|
||||
|
||||
pytestmark = pytest.mark.fresh_app
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_registry_cache():
|
||||
registry_service._cache.update({'ts': 0.0, 'entries': None, 'source': None})
|
||||
yield
|
||||
registry_service._cache.update({'ts': 0.0, 'entries': None, 'source': None})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def plugin_dirs(tmp_path, monkeypatch):
|
||||
d = {n: tmp_path / n for n in ('b', 'f', 'builtin')}
|
||||
for p in d.values():
|
||||
p.mkdir()
|
||||
monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(d['b']))
|
||||
monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(d['f']))
|
||||
monkeypatch.setattr(plugin_service, 'BUILTIN_EXTENSIONS_DIR', str(d['builtin']))
|
||||
return d
|
||||
|
||||
|
||||
def _manifest(slug, version):
|
||||
return {'name': slug, 'display_name': 'Ext ' + slug, 'version': version,
|
||||
'category': 'utility',
|
||||
'contributions': {'nav': [{'id': slug, 'label': 'X', 'route': '/x'}]}}
|
||||
|
||||
|
||||
def _zip(slug, version):
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, 'w') as zf:
|
||||
zf.writestr('plugin.json', json.dumps(_manifest(slug, version)))
|
||||
zf.writestr('frontend/index.jsx', 'export function P(){return null;}\n')
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _install_registry_row(monkeypatch, version='1.0.0'):
|
||||
data = _zip('regext', version)
|
||||
monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(data))
|
||||
return plugin_service.install_from_url('https://x/regext.zip')
|
||||
|
||||
|
||||
def _advertise(version, **extra):
|
||||
registry_service._cache.update({
|
||||
'ts': 9e18, 'source': 'test',
|
||||
'entries': [registry_service._normalize({
|
||||
'slug': 'regext', 'display_name': 'Registry Ext', 'version': version,
|
||||
'source': 'https://x/regext.zip', 'min_panel_version': '0.0.1',
|
||||
**extra})],
|
||||
})
|
||||
|
||||
|
||||
def _by_slug():
|
||||
return {u['slug']: u for u in plugin_service.check_for_updates()}
|
||||
|
||||
|
||||
def test_registry_update_fields(app, plugin_dirs, monkeypatch):
|
||||
_install_registry_row(monkeypatch)
|
||||
_advertise('2.0.0')
|
||||
u = _by_slug()['regext']
|
||||
assert u['update_available'] is True
|
||||
assert u['display_name'] == 'Registry Ext'
|
||||
assert u['update_source'] == 'registry'
|
||||
assert isinstance(u['requires_ack'], bool)
|
||||
assert u['requires_ack'] == (u['risk'] is not None)
|
||||
assert u['incompatible_reason'] is None
|
||||
|
||||
|
||||
def test_up_to_date(app, plugin_dirs, monkeypatch):
|
||||
_install_registry_row(monkeypatch)
|
||||
_advertise('1.0.0')
|
||||
assert _by_slug()['regext']['update_available'] is False
|
||||
|
||||
|
||||
def test_incompatible_panel(app, plugin_dirs, monkeypatch):
|
||||
_install_registry_row(monkeypatch)
|
||||
_advertise('2.0.0', min_panel_version='999.0.0')
|
||||
u = _by_slug()['regext']
|
||||
assert u['compatible'] is False
|
||||
assert '999.0.0' in u['incompatible_reason']
|
||||
|
||||
|
||||
def test_malformed_version_no_raise(app, plugin_dirs, monkeypatch):
|
||||
p = _install_registry_row(monkeypatch)
|
||||
_advertise('banana')
|
||||
assert _by_slug()['regext']['update_available'] is False
|
||||
p.version = 'also-bad'
|
||||
db.session.commit()
|
||||
assert _by_slug()['regext']['update_available'] is False
|
||||
|
||||
|
||||
def test_builtin_update(app, plugin_dirs, monkeypatch):
|
||||
folder = plugin_dirs['builtin'] / 'bi-ext'
|
||||
(folder / 'frontend').mkdir(parents=True)
|
||||
(folder / 'frontend' / 'index.jsx').write_text('export function P(){return null;}\n')
|
||||
(folder / 'plugin.json').write_text(json.dumps(_manifest('bi-ext', '1.0.0')))
|
||||
p = plugin_service.install_from_path(str(folder), source_type='builtin')
|
||||
assert p.source_type == 'builtin'
|
||||
# A registry entry with the same slug must be ignored for builtin rows.
|
||||
assert plugin_service.check_for_updates()[0]['update_available'] is False
|
||||
|
||||
(folder / 'plugin.json').write_text(json.dumps(_manifest('bi-ext', '1.1.0')))
|
||||
u = _by_slug()['bi-ext']
|
||||
assert u['update_available'] is True
|
||||
assert u['update_source'] == 'builtin'
|
||||
assert u['requires_ack'] is False and u['risk'] is None
|
||||
|
||||
updated = plugin_service.update_plugin(p.id)
|
||||
assert updated.version == '1.1.0'
|
||||
assert updated.source_type == 'builtin'
|
||||
assert InstalledPlugin.query.filter_by(slug='bi-ext').count() == 1
|
||||
|
||||
|
||||
def test_api_shape_and_refresh(app, client, auth_headers, plugin_dirs, monkeypatch):
|
||||
calls = []
|
||||
_install_registry_row(monkeypatch)
|
||||
_advertise('2.0.0')
|
||||
monkeypatch.setattr(registry_service, 'refresh',
|
||||
lambda force=False: calls.append(force) or registry_service._cache['entries'])
|
||||
r = client.get('/api/v1/plugins/updates', headers=auth_headers)
|
||||
assert r.status_code == 200
|
||||
body = r.get_json()
|
||||
assert body['count'] == 1 and body['checked_at']
|
||||
assert 'registry_source' in body
|
||||
assert True not in calls
|
||||
client.get('/api/v1/plugins/updates?refresh=1', headers=auth_headers)
|
||||
assert True in calls
|
||||
@@ -20,6 +20,14 @@ PANEL_NGINX_CONFIGS = [
|
||||
/ 'sites-available'
|
||||
/ 'serverkit.conf',
|
||||
]
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
ALL_CSP_CONFIGS = PANEL_NGINX_CONFIGS + [
|
||||
ROOT / 'nginx' / 'sites-available' / 'example.conf.template',
|
||||
]
|
||||
|
||||
|
||||
def _script_src(csp):
|
||||
return next(d.strip() for d in csp.split(';') if d.strip().startswith('script-src '))
|
||||
|
||||
|
||||
def _make_app(hsts_enabled, debug):
|
||||
@@ -86,3 +94,43 @@ def test_resolve_ssl_mode(monkeypatch):
|
||||
assert cfg._resolve_ssl_mode() == 'insecure'
|
||||
monkeypatch.delenv('SERVERKIT_SSL_MODE', raising=False)
|
||||
assert cfg._resolve_ssl_mode() == 'insecure'
|
||||
|
||||
|
||||
def test_prod_csp_script_src_is_strict():
|
||||
r = _make_app(hsts_enabled=False, debug=False).test_client().get('/ping')
|
||||
script_src = _script_src(r.headers['Content-Security-Policy'])
|
||||
assert 'unsafe-eval' not in script_src
|
||||
assert 'unsafe-inline' not in script_src
|
||||
|
||||
|
||||
@pytest.mark.parametrize('config_path', ALL_CSP_CONFIGS)
|
||||
def test_nginx_csp_script_src_is_strict(config_path):
|
||||
line = next(
|
||||
l for l in config_path.read_text(encoding='utf-8').splitlines()
|
||||
if 'Content-Security-Policy' in l
|
||||
)
|
||||
script_src = _script_src(line.split('"')[1])
|
||||
assert 'unsafe-eval' not in script_src
|
||||
assert 'unsafe-inline' not in script_src
|
||||
|
||||
|
||||
def test_index_html_has_no_inline_script():
|
||||
html = (ROOT / 'frontend' / 'index.html').read_text(encoding='utf-8')
|
||||
assert '<script>' not in html
|
||||
|
||||
|
||||
def test_csp_importmap_hash_matches_vendor_manifest():
|
||||
import base64, hashlib, json, re
|
||||
from app.middleware.security import VENDOR_IMPORTMAP_HASH
|
||||
src = (ROOT / 'frontend/src/plugins/runtime/vendorManifest.js').read_text(encoding='utf-8')
|
||||
pairs = re.findall(r"specifier: '([^']+)', file: '([^']+)'", src)
|
||||
body = json.dumps({'imports': {s: '/serverkit-vendor/' + f for s, f in pairs}}, separators=(',', ':'))
|
||||
digest = base64.b64encode(hashlib.sha256(body.encode()).digest()).decode()
|
||||
assert VENDOR_IMPORTMAP_HASH == 'sha256-' + digest
|
||||
for path in ALL_CSP_CONFIGS:
|
||||
assert VENDOR_IMPORTMAP_HASH in path.read_text(encoding='utf-8')
|
||||
|
||||
|
||||
def test_managed_app_nginx_template_has_no_unsafe_eval():
|
||||
from app.services.nginx import templates
|
||||
assert 'unsafe-eval' not in Path(templates.__file__).read_text(encoding='utf-8')
|
||||
@@ -108,3 +108,17 @@ def test_list_servers_metrics_are_batched_not_per_row(client, auth_headers, serv
|
||||
assert count_metric_queries() == baseline, (
|
||||
'metrics lookup grew with the server count — it must stay batched'
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('param', ['from', 'to'])
|
||||
def test_metrics_rejects_a_malformed_timestamp_with_400(app, client, auth_headers, param):
|
||||
with app.app_context():
|
||||
server = _mk_server('delta')
|
||||
db.session.commit()
|
||||
server_id = server.id
|
||||
|
||||
resp = client.get(f'/api/v1/servers/{server_id}/metrics?{param}=not-a-date',
|
||||
headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 400
|
||||
assert resp.get_json()['error']
|
||||
@@ -0,0 +1,174 @@
|
||||
"""TOTPService / TwoFactorSetup behaviour (RFC 6238 via pyotp)."""
|
||||
import time
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pyotp
|
||||
import pytest
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.totp_service import TOTPService, TwoFactorSetup
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def secret():
|
||||
return TOTPService.generate_secret()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user(app):
|
||||
u = User(email='t@example.com', username='totp-user',
|
||||
password_hash=generate_password_hash('x'), role='developer', is_active=True)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def test_generate_secret_is_random_valid_base32():
|
||||
a, b = TOTPService.generate_secret(), TOTPService.generate_secret()
|
||||
assert a != b
|
||||
assert len(a) == 32
|
||||
pyotp.TOTP(a).now() # decodes as base32
|
||||
|
||||
|
||||
def test_current_code_verifies(secret):
|
||||
code = TOTPService.get_current_code(secret)
|
||||
assert len(code) == 6 and code.isdigit()
|
||||
assert TOTPService.verify_code(secret, code)
|
||||
|
||||
|
||||
def test_code_with_spaces_and_dashes_is_normalised(secret):
|
||||
code = TOTPService.get_current_code(secret)
|
||||
assert TOTPService.verify_code(secret, f'{code[:3]} {code[3:]}')
|
||||
assert TOTPService.verify_code(secret, f'{code[:3]}-{code[3:]}')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', ['', None, 'abcdef', '12345', '1234567', '000000x'])
|
||||
def test_malformed_or_missing_code_is_rejected(secret, bad):
|
||||
# A wrong 6-digit code could collide with the real one 1-in-a-million; use a shape check only.
|
||||
assert not TOTPService.verify_code(secret, bad)
|
||||
|
||||
|
||||
def test_missing_secret_is_rejected():
|
||||
assert not TOTPService.verify_code(None, '123456')
|
||||
assert not TOTPService.verify_code('', '123456')
|
||||
|
||||
|
||||
def test_wrong_code_is_rejected(secret):
|
||||
real = TOTPService.get_current_code(secret)
|
||||
wrong = f'{(int(real) + 1) % 1000000:06d}'
|
||||
# Neighbouring-window codes are also valid, so make sure we truly picked a stranger.
|
||||
totp = TOTPService.get_totp(secret)
|
||||
now = time.time()
|
||||
valid = {totp.at(now + d * 30) for d in (-1, 0, 1)}
|
||||
if wrong in valid:
|
||||
pytest.skip('collided with a neighbouring window')
|
||||
assert not TOTPService.verify_code(secret, wrong)
|
||||
|
||||
|
||||
def test_window_drift(secret):
|
||||
totp = TOTPService.get_totp(secret)
|
||||
prev = totp.at(time.time() - 30)
|
||||
far = totp.at(time.time() - 120)
|
||||
assert TOTPService.verify_code(secret, prev, valid_window=1)
|
||||
assert not TOTPService.verify_code(secret, far, valid_window=1)
|
||||
assert not TOTPService.verify_code(secret, far, valid_window=0)
|
||||
|
||||
|
||||
def test_provisioning_uri(secret):
|
||||
uri = TOTPService.get_provisioning_uri(secret, 'me@example.com')
|
||||
parsed = urlparse(uri)
|
||||
assert parsed.scheme == 'otpauth' and parsed.netloc == 'totp'
|
||||
qs = parse_qs(parsed.query)
|
||||
assert qs['secret'] == [secret]
|
||||
assert qs['issuer'] == ['ServerKit']
|
||||
assert 'me%40example.com' in parsed.path or 'me@example.com' in parsed.path
|
||||
|
||||
|
||||
def test_qr_code_is_png_data_uri(secret):
|
||||
qr = TOTPService.generate_qr_code_base64(secret, 'me@example.com')
|
||||
if qr is None:
|
||||
pytest.skip('qrcode not installed')
|
||||
assert qr.startswith('data:image/png;base64,')
|
||||
|
||||
|
||||
def test_backup_codes_roundtrip():
|
||||
plain, hashed = TOTPService.generate_backup_codes()
|
||||
assert len(plain) == len(hashed) == TOTPService.BACKUP_CODE_COUNT
|
||||
assert len(set(plain)) == len(plain)
|
||||
assert all(len(c) == TOTPService.BACKUP_CODE_LENGTH for c in plain)
|
||||
assert TOTPService.verify_backup_code(plain[0], hashed) == hashed[0]
|
||||
assert TOTPService.verify_backup_code(plain[0].upper(), hashed) == hashed[0]
|
||||
formatted = TOTPService.format_backup_codes([plain[0]])[0]
|
||||
assert formatted == f'{plain[0][:4]}-{plain[0][4:]}'
|
||||
assert TOTPService.verify_backup_code(formatted, hashed) == hashed[0]
|
||||
|
||||
|
||||
def test_backup_code_rejects_unknown_and_empty():
|
||||
_, hashed = TOTPService.generate_backup_codes()
|
||||
assert TOTPService.verify_backup_code('deadbeef', hashed) is None
|
||||
assert TOTPService.verify_backup_code('', hashed) is None
|
||||
assert TOTPService.verify_backup_code('abcd1234', []) is None
|
||||
|
||||
|
||||
def test_setup_flow_enables_2fa_and_returns_backup_codes(user):
|
||||
setup = TwoFactorSetup(user)
|
||||
assert setup.confirm_setup('123456') == (False, '2FA setup not initiated')
|
||||
|
||||
data = setup.initiate_setup()
|
||||
assert data['issuer'] == 'ServerKit' and data['secret'] == user.totp_secret
|
||||
assert not user.totp_enabled
|
||||
|
||||
ok, codes = setup.confirm_setup(TOTPService.get_current_code(user.totp_secret))
|
||||
assert ok and len(codes) == 10
|
||||
assert user.totp_enabled and user.totp_confirmed_at
|
||||
assert setup.get_remaining_backup_codes_count() == 10
|
||||
|
||||
|
||||
def test_confirm_with_wrong_code_does_not_enable(user):
|
||||
setup = TwoFactorSetup(user)
|
||||
setup.initiate_setup()
|
||||
totp = TOTPService.get_totp(user.totp_secret)
|
||||
now = time.time()
|
||||
wrong = next(f'{n:06d}' for n in range(1000000)
|
||||
if f'{n:06d}' not in {totp.at(now + d * 30) for d in (-1, 0, 1)})
|
||||
assert setup.confirm_setup(wrong) == (False, 'Invalid verification code')
|
||||
assert not user.totp_enabled
|
||||
|
||||
|
||||
def _enabled(user):
|
||||
setup = TwoFactorSetup(user)
|
||||
setup.initiate_setup()
|
||||
_, codes = setup.confirm_setup(TOTPService.get_current_code(user.totp_secret))
|
||||
return setup, codes
|
||||
|
||||
|
||||
def test_disable_with_totp_code(user):
|
||||
setup, _ = _enabled(user)
|
||||
ok, err = setup.disable(TOTPService.get_current_code(user.totp_secret))
|
||||
assert ok and err is None
|
||||
assert not user.totp_enabled and user.totp_secret is None and user.backup_codes is None
|
||||
|
||||
|
||||
def test_disable_with_backup_code(user):
|
||||
setup, codes = _enabled(user)
|
||||
ok, err = setup.disable(codes[0])
|
||||
assert ok and err is None and not user.totp_enabled
|
||||
|
||||
|
||||
def test_disable_rejects_garbage_and_when_not_enabled(user):
|
||||
setup = TwoFactorSetup(user)
|
||||
assert setup.disable('123456') == (False, '2FA is not enabled')
|
||||
setup, _ = _enabled(user)
|
||||
assert setup.disable('zzzz-zzzz') == (False, 'Invalid verification code')
|
||||
assert user.totp_enabled
|
||||
|
||||
|
||||
def test_regenerate_backup_codes_replaces_old_set(user):
|
||||
setup, old = _enabled(user)
|
||||
old_hashes = set(user.get_backup_codes())
|
||||
ok, new = setup.regenerate_backup_codes(TOTPService.get_current_code(user.totp_secret))
|
||||
assert ok and len(new) == 10
|
||||
assert not old_hashes & set(user.get_backup_codes())
|
||||
assert setup.regenerate_backup_codes('abc') == (False, 'Invalid verification code')
|
||||
@@ -0,0 +1,37 @@
|
||||
"""User-configured webhook URLs must go through app.utils.safe_http."""
|
||||
import pytest
|
||||
|
||||
from app.notifications.channels.base import DeliveryResult
|
||||
from app.services.chat_webhook_service import ChatWebhookService
|
||||
from app.services.monitoring_service import MonitoringService
|
||||
|
||||
PRIVATE_URLS = ['http://127.0.0.1:5000/hook', 'http://169.254.169.254/latest/meta-data', 'http://localhost/x']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', PRIVATE_URLS)
|
||||
def test_monitoring_webhook_refuses_private_targets(url, monkeypatch):
|
||||
monkeypatch.setattr(MonitoringService, 'get_config',
|
||||
classmethod(lambda cls: {'webhook': {'enabled': True, 'url': url}}))
|
||||
result = MonitoringService.send_webhook_alert([{'type': 'cpu'}])
|
||||
assert result['success'] is False
|
||||
assert 'refused' in result['error']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', PRIVATE_URLS)
|
||||
def test_chat_webhook_refuses_private_targets(url):
|
||||
class _Notification:
|
||||
severity = 'info'
|
||||
event_key = 'x'
|
||||
title = 't'
|
||||
body = 'b'
|
||||
created_at = None
|
||||
category = 'c'
|
||||
action_path = None
|
||||
id = 1
|
||||
|
||||
def get_data(self):
|
||||
return {}
|
||||
|
||||
result = ChatWebhookService._deliver_webhook(None, {'url': url}, _Notification())
|
||||
assert result.status == DeliveryResult.SKIPPED # terminal: the queue must not retry
|
||||
assert 'refused' in result.error
|
||||
@@ -40,7 +40,7 @@ Relevant endpoints:
|
||||
|---|---|
|
||||
| `GET /api/v1/marketplace/registry` | list registry entries + live install state |
|
||||
| `POST /api/v1/marketplace/registry/<slug>/install` | checksum-verified install (admin) |
|
||||
| `GET /api/v1/plugins/updates` | installed plugins with a newer registry version |
|
||||
| `GET /api/v1/plugins/updates` | installed plugins with a newer registry/bundled version; returns `{updates, count, checked_at, registry_source}`, `?refresh=1` refetches |
|
||||
| `POST /api/v1/plugins/<id>/update` | update a plugin to the registry version (admin) |
|
||||
|
||||
---
|
||||
|
||||
@@ -19,12 +19,12 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`.
|
||||
| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 849 | 850 | migrate when touched; new endpoints raise |
|
||||
| Raw subprocess calls outside the runners | app/utils/system.py runners | 23 | 23 | migrate when touched |
|
||||
| Controller-boundary violations (routes doing service work) | service layer extraction | 453 | 453 | migrate when touched (first-wave ratchet) |
|
||||
| raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 374 | 398 | migrate when touched |
|
||||
| per-page toast.error extractions in pages/ | E1: query-layer error presentation | 191 | 206 | migrate when touched |
|
||||
| hand-rolled form-group blocks | F2: FormField/useForm | 315 | 321 | migrate when touched |
|
||||
| raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 371 | 371 | migrate when touched |
|
||||
| per-page toast.error extractions in pages/ | E1: query-layer error presentation | 190 | 206 | migrate when touched |
|
||||
| hand-rolled form-group blocks | F2: FormField/useForm | 314 | 321 | migrate when touched |
|
||||
| unencoded ?k=${v} query interpolations in services/api | C4: buildQuery/encoding template | 0 | 0 | INVARIANT at 0 |
|
||||
| raw setInterval pollers | E2: usePolling/refetchInterval | 7 | 7 | DELIBERATE RESIDUE: clock ticks, socket-fallback hooks, and sibling-repo extension timers - each listed per file |
|
||||
| direct navigator.clipboard call sites | F3: copyToClipboard | 0 | 0 | INVARIANT at 0 |
|
||||
| hex colour literals outside token files | G: var(--token) | 139 | 139 | migrate when touched |
|
||||
| hex colour literals outside token files | G: var(--token) | 137 | 137 | migrate when touched |
|
||||
| SCSS class names defined in multiple files | single-owner partials | 0 | 0 | needs eyes on pages (no byte-identical proof available) |
|
||||
|
||||
+1
-27
@@ -13,33 +13,7 @@
|
||||
No Google Fonts / third-party CDN: a self-hosted control panel must not
|
||||
leak every user's IP + usage to Google. Falls back to system-ui until
|
||||
the woff2 files are present (run frontend/scripts/fetch-fonts.mjs). -->
|
||||
<script>
|
||||
// Prevent flash of unstyled content (FOUC) by setting theme + accent before React loads
|
||||
(function() {
|
||||
var d = document.documentElement;
|
||||
d.setAttribute('data-theme', localStorage.getItem('theme') || 'dark');
|
||||
var accent = localStorage.getItem('accent_color');
|
||||
if (accent) {
|
||||
var m = accent.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
|
||||
if (m) {
|
||||
var r = parseInt(m[1],16), g = parseInt(m[2],16), b = parseInt(m[3],16);
|
||||
var hx = function(v){ return Math.max(0,Math.min(255,v)).toString(16).padStart(2,'0'); };
|
||||
var dk = function(v){ return Math.round(v*0.88); };
|
||||
var br = function(v){ return Math.round(v + (255-v)*0.30); }; // toward white
|
||||
var dm = function(v){ return Math.round(v*0.70); };
|
||||
d.style.setProperty('--accent-primary', accent);
|
||||
d.style.setProperty('--accent', accent);
|
||||
d.style.setProperty('--accent-hover', '#'+hx(dk(r))+hx(dk(g))+hx(dk(b)));
|
||||
d.style.setProperty('--accent-bright', '#'+hx(br(r))+hx(br(g))+hx(br(b)));
|
||||
d.style.setProperty('--accent-dim', '#'+hx(dm(r))+hx(dm(g))+hx(dm(b)));
|
||||
d.style.setProperty('--accent-bg', 'rgba('+r+','+g+','+b+',0.13)');
|
||||
d.style.setProperty('--accent-bg-soft', 'rgba('+r+','+g+','+b+',0.07)');
|
||||
d.style.setProperty('--accent-glow', 'rgba('+r+','+g+','+b+',0.35)');
|
||||
d.style.setProperty('--accent-shadow', 'rgba('+r+','+g+','+b+',0.3)');
|
||||
}
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script src="/theme-init.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,26 @@
|
||||
// Prevent flash of unstyled content (FOUC) by setting theme + accent before React loads.
|
||||
// External file (not inline) so the CSP needs no 'unsafe-inline' for scripts.
|
||||
(function() {
|
||||
var d = document.documentElement;
|
||||
d.setAttribute('data-theme', localStorage.getItem('theme') || 'dark');
|
||||
var accent = localStorage.getItem('accent_color');
|
||||
if (accent) {
|
||||
var m = accent.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
|
||||
if (m) {
|
||||
var r = parseInt(m[1],16), g = parseInt(m[2],16), b = parseInt(m[3],16);
|
||||
var hx = function(v){ return Math.max(0,Math.min(255,v)).toString(16).padStart(2,'0'); };
|
||||
var dk = function(v){ return Math.round(v*0.88); };
|
||||
var br = function(v){ return Math.round(v + (255-v)*0.30); }; // toward white
|
||||
var dm = function(v){ return Math.round(v*0.70); };
|
||||
d.style.setProperty('--accent-primary', accent);
|
||||
d.style.setProperty('--accent', accent);
|
||||
d.style.setProperty('--accent-hover', '#'+hx(dk(r))+hx(dk(g))+hx(dk(b)));
|
||||
d.style.setProperty('--accent-bright', '#'+hx(br(r))+hx(br(g))+hx(br(b)));
|
||||
d.style.setProperty('--accent-dim', '#'+hx(dm(r))+hx(dm(g))+hx(dm(b)));
|
||||
d.style.setProperty('--accent-bg', 'rgba('+r+','+g+','+b+',0.13)');
|
||||
d.style.setProperty('--accent-bg-soft', 'rgba('+r+','+g+','+b+',0.07)');
|
||||
d.style.setProperty('--accent-glow', 'rgba('+r+','+g+','+b+',0.35)');
|
||||
d.style.setProperty('--accent-shadow', 'rgba('+r+','+g+','+b+',0.3)');
|
||||
}
|
||||
}
|
||||
})();
|
||||
@@ -1 +1 @@
|
||||
41
|
||||
40
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { brotliDecompressSync } from 'node:zlib';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
@@ -9,11 +10,72 @@ const FRONTEND = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const FONT_DIR = join(FRONTEND, 'public', 'fonts');
|
||||
const FONT_STYLES = join(FRONTEND, 'src', 'styles', 'base', '_fonts.scss');
|
||||
const FONTS = [
|
||||
['ibm-plex-sans-400.woff2', 400],
|
||||
['ibm-plex-sans-500.woff2', 500],
|
||||
['ibm-plex-sans-600.woff2', 600],
|
||||
['ibm-plex-sans-700.woff2', 700],
|
||||
];
|
||||
|
||||
const GLYF = 10;
|
||||
const LOCA = 11;
|
||||
const KNOWN_TAGS = { 1: 'head', 4: 'maxp', [GLYF]: 'glyf' };
|
||||
const HEAD_MAGIC = 0x5f0f3cf5;
|
||||
|
||||
// Parse the WOFF2 header + table directory and brotli-decode the table data,
|
||||
// so a truncated or bit-rotted file fails here instead of silently in the browser.
|
||||
function validateWoff2(font, filename) {
|
||||
const fail = (why) => { throw new Error(`${filename}: ${why}`); };
|
||||
if (font.length < 48) fail('shorter than the WOFF2 header');
|
||||
if (font.readUInt32BE(8) !== font.length) fail('header length does not match file size');
|
||||
const numTables = font.readUInt16BE(12);
|
||||
const compressedSize = font.readUInt32BE(20);
|
||||
if (numTables === 0) fail('has no tables');
|
||||
|
||||
let pos = 48;
|
||||
const base128 = () => {
|
||||
let value = 0;
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
if (pos >= font.length) fail('table directory is truncated');
|
||||
const byte = font[pos++];
|
||||
value = value * 128 + (byte & 0x7f);
|
||||
if (!(byte & 0x80)) return value;
|
||||
}
|
||||
return fail('invalid UIntBase128 in table directory');
|
||||
};
|
||||
let expected = 0;
|
||||
const tables = {};
|
||||
for (let i = 0; i < numTables; i += 1) {
|
||||
const flags = font[pos++];
|
||||
const index = flags & 0x3f;
|
||||
const version = flags >> 6;
|
||||
if (index === 63) pos += 4;
|
||||
const origLength = base128();
|
||||
const transformed = index === GLYF || index === LOCA ? version !== 3 : version !== 0;
|
||||
const length = transformed ? base128() : origLength;
|
||||
if (KNOWN_TAGS[index]) tables[KNOWN_TAGS[index]] = { offset: expected, length };
|
||||
expected += length;
|
||||
}
|
||||
if (pos + compressedSize > font.length) fail('compressed table data runs past end of file');
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = brotliDecompressSync(font.subarray(pos, pos + compressedSize));
|
||||
} catch (error) {
|
||||
fail(`table data does not brotli-decode (${error.message})`);
|
||||
}
|
||||
if (data.length !== expected) {
|
||||
fail(`decoded table data is ${data.length} bytes, directory declares ${expected}`);
|
||||
}
|
||||
|
||||
// brotli can succeed on zeroed-out tables, which browsers' font sanitizer then rejects.
|
||||
const { head, maxp, glyf } = tables;
|
||||
if (!head || !maxp || !glyf) fail('missing head/maxp/glyf table');
|
||||
if (data.readUInt32BE(head.offset + 12) !== HEAD_MAGIC) fail('head table magic number is wrong');
|
||||
const numGlyphs = data.readUInt16BE(maxp.offset + 4);
|
||||
if (numGlyphs === 0) fail('maxp declares zero glyphs');
|
||||
if (data.readUInt16BE(glyf.offset + 4) !== numGlyphs) fail('glyf glyph count does not match maxp');
|
||||
}
|
||||
|
||||
const styles = await readFile(FONT_STYLES, 'utf8');
|
||||
const fontFaces = [...styles.matchAll(/@font-face\s*\{([\s\S]*?)\}/g)]
|
||||
.map((match) => match[1]);
|
||||
@@ -27,6 +89,7 @@ for (const [filename, weight] of FONTS) {
|
||||
if (!font.some((byte) => byte !== 0)) {
|
||||
throw new Error(`${filename} contains only zero bytes`);
|
||||
}
|
||||
validateWoff2(font, filename);
|
||||
|
||||
const face = fontFaces.find((block) => block.includes(filename));
|
||||
if (!face || !face.includes(`font-weight: ${weight};`)) {
|
||||
@@ -34,4 +97,4 @@ for (const [filename, weight] of FONTS) {
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✓ font integrity: IBM Plex Sans 500/600/700 are valid WOFF2 assets');
|
||||
console.log('✓ font integrity: IBM Plex Sans 400/500/600/700 decode as valid WOFF2 assets');
|
||||
@@ -86,7 +86,6 @@ const LEGACY_COLOR_LITERALS = new Map(Object.entries({
|
||||
'styles/pages/_file-manager.scss': 10,
|
||||
'styles/pages/_git.scss': 6,
|
||||
'styles/pages/_import-wizard.scss': 1,
|
||||
'styles/pages/_marketplace.scss': 2,
|
||||
'styles/pages/_notification-center.scss': 4,
|
||||
'styles/pages/_settings.scss': 14,
|
||||
'styles/pages/_setup-wizard.scss': 5,
|
||||
@@ -227,7 +226,7 @@ for (const file of LEGACY_POLLERS.keys()) {
|
||||
const ADOPTION_CEILINGS = [
|
||||
{
|
||||
name: 'raw api.* calls in pages/ (E1: useServerQuery/useServerMutation)',
|
||||
ceiling: 398,
|
||||
ceiling: 371,
|
||||
include: (file) => file.startsWith('pages/'),
|
||||
pattern: /\bapi\s*\.\s*\w+\s*\(/g,
|
||||
},
|
||||
|
||||
@@ -22,10 +22,6 @@ const KEEP = {
|
||||
'main.jsx': 'entry point',
|
||||
'styles/main.scss': 'entry stylesheet',
|
||||
'plugins/runtime/vendorManifest.js': 'read by the vendor-shim generator and extension bundle checks',
|
||||
'components/domains/CutoverDrawer.jsx': 'built, never mounted: wire into Domains or delete (product call)',
|
||||
'components/settings/MemberActionsCard.jsx': 'built, never mounted: wire in or delete (product call)',
|
||||
'components/dashboard/AccountSecurityNudge.jsx': 'built, never mounted: wire in or delete (product call)',
|
||||
'styles/pages/_cutover.scss': 'styles CutoverDrawer above; goes or gets imported with it',
|
||||
'utils/snapshotBones.js': 'imported by scripts/capture-skeletons.mjs',
|
||||
};
|
||||
// Trees loaded by import.meta.glob, tests, and bundled extension copies.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// ServerKit self-hosts its fonts for privacy (no Google Fonts CDN — that would
|
||||
// leak every visitor's IP + usage to a third party). This script downloads the
|
||||
// OFL-licensed IBM Plex faces once into the repo's public/fonts/ folder so
|
||||
// they're served from our own origin. The Sans 500/600/700 faces come directly
|
||||
// they're served from our own origin. The Sans 400/500/600/700 faces come directly
|
||||
// from the official IBM/plex repository; existing valid faces retain their
|
||||
// original @fontsource jsDelivr source.
|
||||
//
|
||||
@@ -27,7 +27,7 @@ const IBM_PLEX_BASE = `https://raw.githubusercontent.com/IBM/plex/${IBM_PLEX_REV
|
||||
|
||||
// local filename -> source URL
|
||||
const FONTS = {
|
||||
'ibm-plex-sans-400.woff2': `${FONTSOURCE_BASE}/@fontsource/ibm-plex-sans/files/ibm-plex-sans-latin-400-normal.woff2`,
|
||||
'ibm-plex-sans-400.woff2': `${IBM_PLEX_BASE}/packages/plex-sans/fonts/complete/woff2/IBMPlexSans-Regular.woff2`,
|
||||
'ibm-plex-sans-500.woff2': `${IBM_PLEX_BASE}/packages/plex-sans/fonts/complete/woff2/IBMPlexSans-Medium.woff2`,
|
||||
'ibm-plex-sans-600.woff2': `${IBM_PLEX_BASE}/packages/plex-sans/fonts/complete/woff2/IBMPlexSans-SemiBold.woff2`,
|
||||
'ibm-plex-sans-700.woff2': `${IBM_PLEX_BASE}/packages/plex-sans/fonts/complete/woff2/IBMPlexSans-Bold.woff2`,
|
||||
|
||||
@@ -143,8 +143,17 @@ function SetupRoute({ children }) {
|
||||
return children;
|
||||
}
|
||||
|
||||
// /git-ext was the in-tree git page; it now ships as the serverkit-git
|
||||
// extension at /git. Without the extension that route is never registered, so
|
||||
// send the operator to its marketplace entry instead of a "page not found".
|
||||
const GIT_EXTENSION_SLUG = 'serverkit-git';
|
||||
|
||||
function LegacyGitExtRedirect() {
|
||||
const { tab } = useParams();
|
||||
const { routes, __ready } = useContributions();
|
||||
if (!__ready) return <AppLoader />;
|
||||
const installed = (routes || []).some((route) => route.plugin === GIT_EXTENSION_SLUG);
|
||||
if (!installed) return <Navigate to={`/extensions?install=${GIT_EXTENSION_SLUG}`} replace />;
|
||||
return <Navigate to={tab ? `/git/${tab}` : '/git'} replace />;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import useLabel from '../i18n/labels';
|
||||
import { MANAGED_CAPABILITY_MAP } from './sidebarItems';
|
||||
import { formatDate } from '@/utils/intl';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// The managed card: what a held capability's page shows instead of
|
||||
// its content. It names the capability, who holds it and since when, and links
|
||||
@@ -36,9 +37,12 @@ export default function ManagedCard({ capability, profile, compact = false }) {
|
||||
{t('managed.card.title', '{{label}} is managed by {{heldBy}}', { label, heldBy })}
|
||||
</h3>
|
||||
<p className="managed-card__body">
|
||||
{t('managed.card.bodyShort', 'Hidden, not removed. Returns when Managed ends.')}{' '}
|
||||
<InfoTip>
|
||||
{since
|
||||
? t('managed.card.bodySince', 'ServerKit Cloud took this over on {{date}} as part of your Managed service. The page is hidden, not removed. Its API still answers and everything returns the moment the Managed scope ends.', { date: since })
|
||||
: t('managed.card.body', 'ServerKit Cloud takes care of this as part of your Managed service. The page is hidden, not removed. Its API still answers and everything returns the moment the Managed scope ends.')}
|
||||
</InfoTip>
|
||||
{capability === 'updates' && (
|
||||
<> {t('managed.card.updatesNote', 'The panel still updates itself; only the update screens are hidden.')}</>
|
||||
)}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Link } from 'react-router-dom';
|
||||
import { Boxes, Terminal } from 'lucide-react';
|
||||
import { useResourceTier } from '../contexts/useResourceTier.js';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import InfoTip from './InfoTip';
|
||||
|
||||
/**
|
||||
* Explains a Dockerless install instead of letting the page fail at click time.
|
||||
@@ -31,7 +32,10 @@ const RequiresDocker = ({ children, what = 'This page' }) => {
|
||||
<h2 className="requires-docker__title">{t('app.requiresDocker.dockerIsnTAvailable', 'Docker isn\'t available')}</h2>
|
||||
|
||||
<p className="requires-docker__text">
|
||||
{what} {t('app.requiresDocker.needsDockerToRunContainersAnd', 'needs Docker to run containers, and this server was installed with the')} <strong>{profileLabel}</strong> {t('app.requiresDocker.profileWhichLeavesItOutNothing', 'profile, which leaves it out. Nothing is locked; adding Docker turns this page on.')}
|
||||
{what} {t('app.requiresDocker.needsDocker', 'needs Docker.')}
|
||||
<InfoTip>
|
||||
{what} {t('app.requiresDocker.needsDockerToRunContainersAnd', 'needs Docker to run containers, and this server was installed with the')} <strong>{profileLabel}</strong> {t('app.requiresDocker.profileWhichLeavesItOutNothing', 'profile, which leaves it out. Nothing is locked; adding Docker turns this page on.')}
|
||||
</InfoTip>
|
||||
</p>
|
||||
|
||||
<div className="requires-docker__how">
|
||||
@@ -48,8 +52,12 @@ const RequiresDocker = ({ children, what = 'This page' }) => {
|
||||
</div>
|
||||
|
||||
<p className="requires-docker__footnote">
|
||||
{t('app.requiresDocker.serverkitReChecksForDockerAutomatically', 'ServerKit re-checks for Docker automatically. Monitoring, domains, certificates, cron and DNS keep working without it. See')}{' '}
|
||||
<Link to="/settings/system">{t('app.requiresDocker.settingsSystem', 'Settings → System')}</Link> {t('app.requiresDocker.forThisInstallSProfile', 'for this install\'s profile.')}
|
||||
{t('app.requiresDocker.checkedAutomatically', 'Re-checked automatically.')}{' '}
|
||||
<Link to="/settings/system">{t('app.requiresDocker.settingsSystem', 'Settings → System')}</Link>
|
||||
<InfoTip>
|
||||
{t('app.requiresDocker.serverkitReChecksForDockerAutomatically', 'ServerKit re-checks for Docker automatically. Monitoring, domains, certificates, cron and DNS keep working without it. See')}{' '}
|
||||
{t('app.requiresDocker.settingsSystem', 'Settings → System')} {t('app.requiresDocker.forThisInstallSProfile', 'for this install\'s profile.')}
|
||||
</InfoTip>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Card as SharedCard } from '@/components/ui/card';
|
||||
import { CardFooter as SharedCardFooter } from '@/components/ui/card';
|
||||
import { formatDateTime } from '@/utils/intl';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// `embedded` renders this inside the Settings → Git & Deploy section, where the
|
||||
// shared RepoConnectForm already owns the connect/disconnect + repo identity. In
|
||||
@@ -257,7 +258,7 @@ const DeployTab = ({ appId, embedded = false }) => {
|
||||
<SharedCard variant="legacy" className="card deploy-timeline-card">
|
||||
<h3>{t('app.deployTab.configCheckpoints', 'Restore points')}</h3>
|
||||
<p className="deploy-timeline-card__hint">
|
||||
{t('app.deployTab.anImmutableConfigCheckpointEnvKeys', 'An immutable restore point (env keys, domains, image, build method, volumes) is captured before each deployment. Secret values are masked. Open a restore point to diff it against the previous one or restore it.')}
|
||||
{t('app.deployTab.restorePointsShort', 'Captured before every deployment.')} <InfoTip>{t('app.deployTab.anImmutableConfigCheckpointEnvKeys', 'An immutable restore point (env keys, domains, image, build method, volumes) is captured before each deployment. Secret values are masked. Open a restore point to diff it against the previous one or restore it.')}</InfoTip>
|
||||
</p>
|
||||
<DeploymentTimeline appId={appId} />
|
||||
</SharedCard>
|
||||
|
||||
@@ -15,6 +15,7 @@ import { InfoList, InfoItem } from '../InfoList';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import { formatDateTime } from '@/utils/intl';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Short SHA helper for image digests (handles "sha256:abcdef..." or bare hashes)
|
||||
function shortDigest(digest) {
|
||||
@@ -122,7 +123,7 @@ const ImageUpdateSection = ({ app, onChanged }) => {
|
||||
<div className="app-panel-body">
|
||||
{!isCompose && (
|
||||
<p className="app-panel-hint">
|
||||
{t('app.containerOpsPanel.imageUpdatesApplyToDockerCompose', 'Image updates apply to services deployed with Docker Compose. You can still check this service\'s digest, but "Update now" is only available for Docker Compose deployments.')}
|
||||
{t('app.containerOpsPanel.imageUpdatesApplyToDockerComposeShort', 'Image updates need Docker Compose.')} <InfoTip>{t('app.containerOpsPanel.imageUpdatesApplyToDockerCompose', 'Image updates apply to services deployed with Docker Compose. You can still check this service\'s digest, but "Update now" is only available for Docker Compose deployments.')}</InfoTip>
|
||||
</p>
|
||||
)}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Must match app/services/deploy_settings.py DEFAULTS / _RULES.
|
||||
const TIMEOUT_DEFAULT = 120;
|
||||
@@ -59,7 +60,7 @@ const DeploySafetyPanel = ({ app, onChanged }) => {
|
||||
</div>
|
||||
<div className="app-panel-body">
|
||||
<p className="app-panel-hint">
|
||||
{t('app.deploySafetyPanel.intro', 'Before a new release counts as live, ServerKit asks it for this path and waits for a 2xx or 3xx answer three times in a row. A release that never answers fails the deploy.')}
|
||||
{t('app.deploySafetyPanel.introShort', 'New releases must answer before going live.')} <InfoTip>{t('app.deploySafetyPanel.intro', 'Before a new release counts as live, ServerKit asks it for this path and waits for a 2xx or 3xx answer three times in a row. A release that never answers fails the deploy.')}</InfoTip>
|
||||
</p>
|
||||
|
||||
<div className="settings-row">
|
||||
|
||||
@@ -9,6 +9,7 @@ import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Paste-in .htaccess -> nginx converter for the per-site custom nginx rules
|
||||
// editor. Pairs with the site-import feature: imported cPanel sites carry
|
||||
@@ -112,7 +113,7 @@ export default function HtaccessConverter({ onInsert, trigger = null }) {
|
||||
>
|
||||
<div className="htaccess-converter">
|
||||
<p className="htaccess-converter__hint">
|
||||
{t('app.htaccessConverter.pasteTheContentsOfAnApache', 'Paste the contents of an Apache')} <code>.htaccess</code> {t('app.htaccessConverter.fileEGFromAnImported', 'file (e.g. from an imported cPanel site). Rewrites, redirects, access rules and basic auth are translated to nginx directives for the custom rules box; anything that has no equivalent is listed below instead of being dropped.')}
|
||||
{t('app.htaccessConverter.hintShort', 'Paste an .htaccess file to convert it.')} <InfoTip>{t('app.htaccessConverter.pasteTheContentsOfAnApache', 'Paste the contents of an Apache')} <code>.htaccess</code> {t('app.htaccessConverter.fileEGFromAnImported', 'file (e.g. from an imported cPanel site). Rewrites, redirects, access rules and basic auth are translated to nginx directives for the custom rules box; anything that has no equivalent is listed below instead of being dropped.')}</InfoTip>
|
||||
</p>
|
||||
|
||||
<Textarea
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useConfirm } from '@/hooks/useConfirm';
|
||||
import { formatPercent } from '@/utils/intl';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Must match NginxService.MICROCACHE_TTL_DEFAULT / MICROCACHE_TTL_MAX.
|
||||
const TTL_DEFAULT = 10;
|
||||
@@ -122,7 +123,7 @@ const MicroCachePanel = ({ app, onChanged }) => {
|
||||
</div>
|
||||
<div className="app-panel-body">
|
||||
<p className="app-panel-hint">
|
||||
{t('app.microCachePanel.cachesFullPagesInNginx', 'Caches full pages in nginx for a few seconds, so traffic spikes hit the cache instead of your service, and visitors still get the last good page while the service restarts or errors. It is safe to enable: requests from logged-in users, carts and checkouts, admin and login pages, non-GET requests, and URLs with query strings always bypass the cache and reach the service directly.')}
|
||||
{t('app.microCachePanel.cachesFullPagesShort', 'Caches pages in nginx for a few seconds.')} <InfoTip>{t('app.microCachePanel.cachesFullPagesInNginx', 'Caches full pages in nginx for a few seconds, so traffic spikes hit the cache instead of your service, and visitors still get the last good page while the service restarts or errors. It is safe to enable: requests from logged-in users, carts and checkouts, admin and login pages, non-GET requests, and URLs with query strings always bypass the cache and reach the service directly.')}</InfoTip>
|
||||
</p>
|
||||
|
||||
<div className="settings-row">
|
||||
@@ -148,7 +149,7 @@ const MicroCachePanel = ({ app, onChanged }) => {
|
||||
<div className="settings-label">
|
||||
<span>{t('app.microCachePanel.longCacheAssets', 'Long-cache fingerprinted assets')}</span>
|
||||
<span className="settings-hint">
|
||||
{t('app.microCachePanel.longCacheAssetsHint', 'Browsers keep files whose name carries a content hash (app.3f9a2c1d.js) for a year. Only turn this on if your build names assets that way: a file that changes without a new name would stay stale.')}
|
||||
{t('app.microCachePanel.longCacheAssetsShort', 'Browsers keep hashed assets for a year.')} <InfoTip>{t('app.microCachePanel.longCacheAssetsHint', 'Browsers keep files whose name carries a content hash (app.3f9a2c1d.js) for a year. Only turn this on if your build names assets that way: a file that changes without a new name would stay stale.')}</InfoTip>
|
||||
</span>
|
||||
</div>
|
||||
<div className="settings-control">
|
||||
@@ -169,7 +170,7 @@ const MicroCachePanel = ({ app, onChanged }) => {
|
||||
{t('app.microCachePanel.cacheLifetime', 'Cache lifetime (seconds)')}
|
||||
</label>
|
||||
<span className="settings-hint">
|
||||
{t('app.microCachePanel.cacheLifetimeHint', 'How long a page is served from the cache before the service is asked again (1–{{max}}). Longer means fewer requests reach the service, and changes take longer to show.', { max: TTL_MAX })}
|
||||
{t('app.microCachePanel.cacheLifetimeShort', 'How long pages stay cached.')} <InfoTip>{t('app.microCachePanel.cacheLifetimeHint', 'How long a page is served from the cache before the service is asked again (1–{{max}}). Longer means fewer requests reach the service, and changes take longer to show.', { max: TTL_MAX })}</InfoTip>
|
||||
</span>
|
||||
</div>
|
||||
<div className="settings-control micro-cache__ttl">
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Docker memory limit: number + one-letter unit (b/k/m/g), e.g. "512m", "2g".
|
||||
const MEMORY_LIMIT_RE = /^\d+(\.\d+)?(b|k|m|g)$/i;
|
||||
@@ -104,7 +105,7 @@ const ResourceLimitsPanel = ({ app, onChanged }) => {
|
||||
</div>
|
||||
<div className="app-panel-body">
|
||||
<p className="app-panel-hint">
|
||||
{t('app.resourceLimitsPanel.capHowMuchCpuAndMemory', 'Cap how much CPU and memory this service\'s container may use. Leave a field empty for no limit. Limits are written into the generated compose configuration and enforced by Docker.')}
|
||||
{t('app.resourceLimitsPanel.capShort', 'Cap CPU and memory. Empty means no limit.')} <InfoTip>{t('app.resourceLimitsPanel.capHowMuchCpuAndMemory', 'Cap how much CPU and memory this service\'s container may use. Leave a field empty for no limit. Limits are written into the generated compose configuration and enforced by Docker.')}</InfoTip>
|
||||
</p>
|
||||
|
||||
{usage ? (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
import Modal from '@/components/Modal';
|
||||
import { Layers } from 'lucide-react';
|
||||
import api from '../../services/api';
|
||||
@@ -129,7 +130,7 @@ const SlotDeploysPanel = ({ app, onChanged }) => {
|
||||
</div>
|
||||
<div className="app-panel-body">
|
||||
<p className="app-panel-hint">
|
||||
{t('app.slotDeploysPanel.intro', 'Each deploy boots the new release in a second slot on its own port while the live one keeps serving. It switches traffic only after the new release passes its health check, watches it for a while, and switches back on its own if it falls over. The previous release stays warm for an instant manual switch back.')}
|
||||
{t('app.slotDeploysPanel.introShort', 'Zero-downtime deploys with automatic rollback.')} <InfoTip>{t('app.slotDeploysPanel.intro', 'Each deploy boots the new release in a second slot on its own port while the live one keeps serving. It switches traffic only after the new release passes its health check, watches it for a while, and switches back on its own if it falls over. The previous release stays warm for an instant manual switch back.')}</InfoTip>
|
||||
</p>
|
||||
|
||||
<div className="settings-row">
|
||||
@@ -156,7 +157,7 @@ const SlotDeploysPanel = ({ app, onChanged }) => {
|
||||
<div className="settings-label">
|
||||
<span>{t('app.slotDeploysPanel.split', 'Move the stateful services first')}</span>
|
||||
<span className="settings-hint">
|
||||
{t('app.slotDeploysPanel.splitHint', 'A database or cache cannot run twice. It moves once into a shared data compose project that both slots reach by the same name, on the same volumes. Preview exactly what changes before anything happens.')}
|
||||
{t('app.slotDeploysPanel.splitHintShort', 'Databases and caches move once.')} <InfoTip>{t('app.slotDeploysPanel.splitHint', 'A database or cache cannot run twice. It moves once into a shared data compose project that both slots reach by the same name, on the same volumes. Preview exactly what changes before anything happens.')}</InfoTip>
|
||||
</span>
|
||||
</div>
|
||||
<div className="settings-control">
|
||||
@@ -202,7 +203,7 @@ const SlotDeploysPanel = ({ app, onChanged }) => {
|
||||
<div className="settings-label">
|
||||
<span>{t('app.slotDeploysPanel.volumes', 'Two copies may share the volumes')}</span>
|
||||
<span className="settings-hint">
|
||||
{t('app.slotDeploysPanel.volumesHint', 'For a few seconds around each switch both releases mount the same volumes. Leave this off if the service keeps something like SQLite there, which breaks when two processes write to it.')}
|
||||
{t('app.slotDeploysPanel.volumesHintShort', 'Both releases mount the volumes briefly.')} <InfoTip>{t('app.slotDeploysPanel.volumesHint', 'For a few seconds around each switch both releases mount the same volumes. Leave this off if the service keeps something like SQLite there, which breaks when two processes write to it.')}</InfoTip>
|
||||
</span>
|
||||
</div>
|
||||
<div className="settings-control">
|
||||
@@ -218,7 +219,7 @@ const SlotDeploysPanel = ({ app, onChanged }) => {
|
||||
{t('app.slotDeploysPanel.release', 'Release command')}
|
||||
</label>
|
||||
<span className="settings-hint">
|
||||
{t('app.slotDeploysPanel.releaseHint', 'Runs once in a throwaway container of the new release, before traffic switches, for example database migrations. If it fails the deploy stops and the live release is untouched. Empty uses the release: line of the Procfile or serverkit.yaml, if there is one.')}
|
||||
{t('app.slotDeploysPanel.releaseHintShort', 'Runs before traffic switches.')} <InfoTip>{t('app.slotDeploysPanel.releaseHint', 'Runs once in a throwaway container of the new release, before traffic switches, for example database migrations. If it fails the deploy stops and the live release is untouched. Empty uses the release: line of the Procfile or serverkit.yaml, if there is one.')}</InfoTip>
|
||||
</span>
|
||||
</div>
|
||||
<div className="settings-control">
|
||||
@@ -244,7 +245,7 @@ const SlotDeploysPanel = ({ app, onChanged }) => {
|
||||
<div className="settings-label">
|
||||
<span>{t('app.slotDeploysPanel.stopOld', 'Stop the live release before the release command')}</span>
|
||||
<span className="settings-hint">
|
||||
{t('app.slotDeploysPanel.stopOldHint', 'For schema changes the running release cannot survive. The service is down from the release command until the new release passes its health check; a failure starts the old release again.')}
|
||||
{t('app.slotDeploysPanel.stopOldHintShort', 'Needed for incompatible schema changes.')} <InfoTip>{t('app.slotDeploysPanel.stopOldHint', 'For schema changes the running release cannot survive. The service is down from the release command until the new release passes its health check; a failure starts the old release again.')}</InfoTip>
|
||||
</span>
|
||||
</div>
|
||||
<div className="settings-control">
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Label } from '@/components/ui/label';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// A single volume row with an inline detach confirm (the "also delete data"
|
||||
// checkbox is off by default and disabled while the app is running, so a detach
|
||||
@@ -138,7 +139,7 @@ const VolumesPanel = ({ app, onChanged }) => {
|
||||
</div>
|
||||
<div className="app-panel-body">
|
||||
<p className="app-panel-hint">
|
||||
{t('app.volumesPanel.firstClassPersistentStorageThatSurvives', 'First-class persistent storage that survives redeploys. Each volume is a named Docker volume mounted into the container at the path you choose, which is safer than a relative bind mount. Changes apply on the next deploy.')}
|
||||
{t('app.volumesPanel.firstClassPersistentStorageThatSurvivesShort', 'Persistent storage that survives redeploys.')} <InfoTip>{t('app.volumesPanel.firstClassPersistentStorageThatSurvives', 'First-class persistent storage that survives redeploys. Each volume is a named Docker volume mounted into the container at the path you choose, which is safer than a relative bind mount. Changes apply on the next deploy.')}</InfoTip>
|
||||
</p>
|
||||
|
||||
{loading ? (
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { Calendar, Save, Loader2 } from 'lucide-react';
|
||||
import SchedulePicker from '../SchedulePicker';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Card 2 of the backup "Protection" panel: the editable schedule form.
|
||||
// The saved policy carries a raw cron string; this card now mounts the shared
|
||||
@@ -187,7 +188,7 @@ const ScheduleCard = ({ policy, remoteConfigured, onSave, saving }) => {
|
||||
onChange={setDrillCadence}
|
||||
/>
|
||||
<p className="app-panel-hint">
|
||||
{t('app.scheduleCard.periodicallyTestRestoreTheLatestBackup', 'Periodically test-restore the latest backup to prove it can actually be recovered. Drills run into a throwaway location and never touch this site. Replaying an incremental backup chain during a drill needs GNU tar, so those drills run on Linux hosts only.')}
|
||||
{t('app.scheduleCard.periodicallyTestRestoreTheLatestBackupShort', 'Test-restore the latest backup periodically.')} <InfoTip>{t('app.scheduleCard.periodicallyTestRestoreTheLatestBackup', 'Periodically test-restore the latest backup to prove it can actually be recovered. Drills run into a throwaway location and never touch this site. Replaying an incremental backup chain during a drill needs GNU tar, so those drills run on Linux hosts only.')}</InfoTip>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import api from '../../services/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ShieldAlert, X } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// Per-user "secure your account" nudge. Shows when the requesting
|
||||
// user has no second factor, deep-linking to Settings → Security where the full
|
||||
// guided enrolment lives (passkey-first, then TOTP with its QR). Dismissible;
|
||||
// the dismissal is persisted to the account's `setup_snoozes` so it
|
||||
// follows the user across browsers, with localStorage kept only as a fast cache
|
||||
// so the nudge doesn't flash before the account fetch resolves.
|
||||
|
||||
const DISMISS_KEY = 'account_security_nudge_dismissed';
|
||||
const ITEM_KEY = 'setup.account_security';
|
||||
const SNOOZE_DAYS = 30;
|
||||
|
||||
const AccountSecurityNudge = () => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [item, setItem] = useState(null);
|
||||
const [dismissed, setDismissed] = useState(() => {
|
||||
try { return localStorage.getItem(DISMISS_KEY) === '1'; } catch { return false; }
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (dismissed) return;
|
||||
let cancelled = false;
|
||||
api.getAccountSecurity()
|
||||
.then((res) => {
|
||||
if (cancelled) return;
|
||||
const acct = (res.items || []).find((c) => c.key === ITEM_KEY);
|
||||
// The account row is the source of truth: a server-side snooze
|
||||
// (set from any browser) means "dismissed" here too.
|
||||
if (acct && acct.snoozed) {
|
||||
try { localStorage.setItem(DISMISS_KEY, '1'); } catch { /* ignore */ }
|
||||
setDismissed(true);
|
||||
return;
|
||||
}
|
||||
if (acct && acct.status !== 'ok') setItem(acct);
|
||||
})
|
||||
.catch(() => { /* stay quiet */ });
|
||||
return () => { cancelled = true; };
|
||||
}, [dismissed]);
|
||||
|
||||
if (dismissed || !item) return null;
|
||||
|
||||
const dismiss = () => {
|
||||
// Cache locally for an instant hide, then persist to the account so the
|
||||
// dismissal survives across browsers/devices. Best-effort: a failed
|
||||
// persist still hides it for this session.
|
||||
try { localStorage.setItem(DISMISS_KEY, '1'); } catch { /* ignore */ }
|
||||
setDismissed(true);
|
||||
api.snoozeSetupItem(ITEM_KEY, SNOOZE_DAYS).catch(() => { /* keep the local hide */ });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="account-security-nudge" role="status">
|
||||
<ShieldAlert size={18} className="account-security-nudge__icon" />
|
||||
<div className="account-security-nudge__body">
|
||||
<span className="account-security-nudge__title">{t('app.accountSecurityNudge.secureYourAccount', 'Secure your account')}</span>
|
||||
<span className="account-security-nudge__detail">{item.detail}</span>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => navigate(item.fix?.to || '/settings/security')}>
|
||||
{t('app.accountSecurityNudge.addAPasskeyOr2fa', 'Add a passkey or 2FA')}
|
||||
</Button>
|
||||
<Button variant="unstyled" type="button" className="account-security-nudge__close" onClick={dismiss} aria-label={t('common.actions.dismiss', 'Dismiss')}>
|
||||
<X size={16} />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AccountSecurityNudge;
|
||||
@@ -14,6 +14,7 @@ import { ENGINE_META } from './dbAdapter';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { translateLabel } from '@/i18n/labels';
|
||||
import { formatDateTime } from '@/utils/intl';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Import a SQL dump into an existing database.
|
||||
//
|
||||
@@ -276,7 +277,7 @@ export default function ImportDumpModal({ preset, isAdmin = false, onClose, onIm
|
||||
/>
|
||||
</div>
|
||||
<p className="dbx-field-hint">
|
||||
{t('app.importDumpModal.anAbsolutePathOnTheServer', 'An absolute path on the panel server. There is no upload endpoint, so a file on your own machine has to be copied across first (scp, the file manager, or a backup taken here).')} <code>.gz</code> {t('app.importDumpModal.isDecompressedAutomatically', 'is decompressed automatically.')}
|
||||
{t('app.importDumpModal.anAbsolutePathShort', 'Absolute path on the panel server.')} <InfoTip>{t('app.importDumpModal.anAbsolutePathOnTheServer', 'An absolute path on the panel server. There is no upload endpoint, so a file on your own machine has to be copied across first (scp, the file manager, or a backup taken here).')} <code>.gz</code> {t('app.importDumpModal.isDecompressedAutomatically', 'is decompressed automatically.')}</InfoTip>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -8,6 +8,7 @@ import LogContent from '../log-viewer/LogContent';
|
||||
import EmptyState from '../EmptyState';
|
||||
import { ErrorState } from '../ErrorState';
|
||||
import Modal from '@/components/Modal';
|
||||
import { SheetPanel } from '@/components/ui/sheet';
|
||||
import { Drawer, DataTable, DataTableFooter, Pill, SearchField } from '@/components/ds';
|
||||
import {
|
||||
useTableChrome, GridViewPicker, GridChips, GridFilterButton,
|
||||
@@ -986,9 +987,12 @@ const ContainerInspector = ({ container, stats, onAction, onOpenLogs, onOpenExec
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="dx-drawer-backdrop" onClick={onClose} />
|
||||
<aside className="dx-inspector dx-inspector-drawer">
|
||||
<SheetPanel
|
||||
className="dx-inspector dx-inspector-drawer"
|
||||
overlayClassName="dx-drawer-backdrop"
|
||||
label={getContainerName(container)}
|
||||
onClose={onClose}
|
||||
>
|
||||
<div className="dx-inspector-header">
|
||||
<div className="dx-inspector-icon">
|
||||
<Box size={18} />
|
||||
@@ -1151,8 +1155,7 @@ const ContainerInspector = ({ container, stats, onAction, onOpenLogs, onOpenExec
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
</SheetPanel>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,484 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
ArrowRightLeft, ArrowLeft, ArrowRight, Camera, CheckCircle2, RotateCcw,
|
||||
AlertTriangle, Globe, RadioTower,
|
||||
} from 'lucide-react';
|
||||
import { DataTable, Drawer, Pill } from '@/components/ds';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ConfirmDialog } from '@/components/ConfirmDialog';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import Spinner from '../Spinner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// Per-domain reversible DNS cutover. One shared slide-over,
|
||||
// reached from the /domains detail drawer and from the Import wizard's final
|
||||
// step, so the survey → migrate → cutover journey ends in the same place.
|
||||
//
|
||||
// Internal stages: target → review (snapshot + TTL guidance + dry-run diff) →
|
||||
// verify (propagation check + one-click revert). Every write is snapshot-backed
|
||||
// so it can always be rolled back.
|
||||
//
|
||||
// <CutoverDrawer open={open} onClose={close} domain="example.com"
|
||||
// providerZoneId="abc123" provider="cloudflare"
|
||||
// initialTarget="203.0.113.10" />
|
||||
|
||||
const HEAD_ICON_SIZE = 18;
|
||||
const DRAWER_WIDTH = 720;
|
||||
|
||||
// Read-only step reports (the planned record changes, then per-resolver
|
||||
// propagation): no sorting, no column menu.
|
||||
const PLAN_COLUMNS = [
|
||||
{
|
||||
key: 'record_type',
|
||||
headerKey: 'common.labels.type', header: 'Type',
|
||||
cellClassName: 'sk-cell-dim',
|
||||
render: (op) => op.record_type,
|
||||
},
|
||||
{
|
||||
key: 'name',
|
||||
headerKey: 'common.labels.name', header: 'Name',
|
||||
cellClassName: 'sk-cell-mono',
|
||||
render: (op) => op.name,
|
||||
},
|
||||
{
|
||||
key: 'action',
|
||||
headerKey: 'common.labels.action', header: 'Action',
|
||||
render: (op) => <Pill kind={op.action === 'create' ? 'cyan' : 'amber'}>{op.action}</Pill>,
|
||||
},
|
||||
{
|
||||
key: 'old_content',
|
||||
headerKey: 'common.labels.current', header: 'Current',
|
||||
cellClassName: 'sk-cell-mono',
|
||||
render: (op) => op.old_content || '—',
|
||||
},
|
||||
{
|
||||
key: 'new_content',
|
||||
headerKey: 'app.cutoverDrawer.new', header: 'New',
|
||||
cellClassName: 'sk-cell-mono',
|
||||
render: (op) => op.new_content,
|
||||
},
|
||||
];
|
||||
|
||||
const RESOLVER_COLUMNS = [
|
||||
{
|
||||
key: 'nameserver',
|
||||
headerKey: 'app.cutoverDrawer.resolver', header: 'Resolver',
|
||||
cellClassName: 'sk-cell-mono',
|
||||
render: (r) => r.nameserver,
|
||||
},
|
||||
{
|
||||
key: 'result',
|
||||
headerKey: 'app.cutoverDrawer.answer', header: 'Answer',
|
||||
cellClassName: 'sk-cell-mono',
|
||||
render: (r) => (r.result || []).join(', ') || '—',
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
headerKey: 'common.labels.status', header: 'Status',
|
||||
render: (r) => <Pill kind={r.propagated ? 'green' : 'gray'}>{r.propagated ? 'live' : 'stale'}</Pill>,
|
||||
},
|
||||
];
|
||||
|
||||
// Record types a cutover can repoint. A/AAAA/CNAME cover the "point at the new
|
||||
// box" case; the operator keeps everything else untouched.
|
||||
const RECORD_TYPE_CHOICES = ['A', 'AAAA', 'CNAME'];
|
||||
|
||||
const STAGES = [
|
||||
{ id: 'target', labelKey: 'common.labels.target', label: 'Target' },
|
||||
{ id: 'review', labelKey: 'app.cutoverDrawer.review', label: 'Review' },
|
||||
{ id: 'verify', labelKey: 'app.cutoverDrawer.verify', label: 'Verify' },
|
||||
];
|
||||
|
||||
// The provider guards (NO_PROVIDER / NO_ZONE) come back as 501/400 with a code;
|
||||
// surface a plain-language line instead of a raw request-failed toast.
|
||||
function friendlyError(err) {
|
||||
const code = err?.data?.code;
|
||||
if (code === 'NO_PROVIDER') {
|
||||
return 'Connect a DNS provider first — the cutover reads and writes live records through it.';
|
||||
}
|
||||
if (code === 'NO_ZONE') {
|
||||
return 'This domain has no connected provider zone, so its records can\'t be read or repointed.';
|
||||
}
|
||||
if (code === 'PROVIDER_READ_FAILED') {
|
||||
return `Couldn't read the zone's live records: ${err.message}`;
|
||||
}
|
||||
return err?.message || 'Something went wrong.';
|
||||
}
|
||||
|
||||
const CutoverDrawer = ({ open, onClose, domain, providerZoneId, provider, initialTarget }) => {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
|
||||
const [stage, setStage] = useState('target');
|
||||
const [target, setTarget] = useState('');
|
||||
const [zoneId, setZoneId] = useState('');
|
||||
const [recordTypes, setRecordTypes] = useState(['A']);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const [snapshot, setSnapshot] = useState(null);
|
||||
const [ttl, setTtl] = useState(null);
|
||||
const [plan, setPlan] = useState(null);
|
||||
const [cutoverResult, setCutoverResult] = useState(null);
|
||||
const [verifyResult, setVerifyResult] = useState(null);
|
||||
const [revertResult, setRevertResult] = useState(null);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
|
||||
// Re-seed from props each time the drawer is opened, so a previous, possibly
|
||||
// abandoned cutover never leaks into the next domain.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setStage('target');
|
||||
setTarget(initialTarget || '');
|
||||
setZoneId(providerZoneId || '');
|
||||
setRecordTypes(['A']);
|
||||
setBusy(false);
|
||||
setError('');
|
||||
setSnapshot(null);
|
||||
setTtl(null);
|
||||
setPlan(null);
|
||||
setCutoverResult(null);
|
||||
setVerifyResult(null);
|
||||
setRevertResult(null);
|
||||
setConfirmOpen(false);
|
||||
}, [open, initialTarget, providerZoneId]);
|
||||
|
||||
const toggleRecordType = (t) => {
|
||||
setRecordTypes((prev) => (prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]));
|
||||
};
|
||||
|
||||
// target → review: snapshot the live records, derive TTL guidance from them,
|
||||
// and compute the (provider-free) dry-run diff.
|
||||
const captureAndReview = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const snap = await api.snapshotDnsForCutover(domain, zoneId.trim(), provider || null);
|
||||
setSnapshot(snap);
|
||||
const [guidance, dry] = await Promise.all([
|
||||
api.getCutoverTtlGuidance(snap.records || []).catch(() => null),
|
||||
api.performDnsCutover(snap.id, target.trim(), { recordTypes, dryRun: true }),
|
||||
]);
|
||||
setTtl(guidance);
|
||||
setPlan(dry.plan || null);
|
||||
setStage('review');
|
||||
} catch (err) {
|
||||
setError(friendlyError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
// review → verify: perform the real cutover through the guarded write path.
|
||||
const applyCutover = async () => {
|
||||
if (!snapshot) return;
|
||||
setConfirmOpen(false);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await api.performDnsCutover(snapshot.id, target.trim(), { recordTypes, dryRun: false });
|
||||
setSnapshot(res.snapshot || snapshot);
|
||||
setCutoverResult(res.cutover || null);
|
||||
setStage('verify');
|
||||
if (res.cutover?.success) {
|
||||
toast.success(t('app.cutoverDrawer.cutoverAppliedNowPointsAt', 'Cutover applied. {{domain}} now points at {{value}}', { domain: domain, value: target.trim() }));
|
||||
} else {
|
||||
toast.error(t('app.cutoverDrawer.cutoverFinishedWithErrorsReviewThe', 'Cutover finished with errors. Review the results and consider reverting.'));
|
||||
}
|
||||
} catch (err) {
|
||||
const message = friendlyError(err);
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const checkPropagation = useCallback(async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const primaryType = recordTypes[0] || 'A';
|
||||
const res = await api.verifyDnsCutover(domain, {
|
||||
recordType: primaryType,
|
||||
expected: target.trim(),
|
||||
snapshotId: snapshot?.id || null,
|
||||
});
|
||||
setVerifyResult(res);
|
||||
} catch (err) {
|
||||
setError(friendlyError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [domain, recordTypes, target, snapshot]);
|
||||
|
||||
const revert = async () => {
|
||||
if (!snapshot) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await api.revertDnsCutover(snapshot.id);
|
||||
setSnapshot(res.snapshot || snapshot);
|
||||
setRevertResult(res.revert || null);
|
||||
if (res.revert?.success) {
|
||||
toast.success(t('app.cutoverDrawer.revertedRestoredSPreCutoverRecords', "Reverted: restored {{domain}}'s pre-cutover records", { domain: domain }));
|
||||
} else {
|
||||
toast.error(t('app.cutoverDrawer.revertFinishedWithErrorsCheckThe', 'Revert finished with errors. Check the results.'));
|
||||
}
|
||||
} catch (err) {
|
||||
const message = friendlyError(err);
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const noZone = !zoneId.trim();
|
||||
const canCapture = !!target.trim() && !noZone && recordTypes.length > 0;
|
||||
const stageIndex = STAGES.findIndex((s) => s.id === stage);
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
onOpenChange={(v) => !v && onClose()}
|
||||
title={t('app.cutoverDrawer.dnsCutover', 'DNS cutover')}
|
||||
subtitle={<span className="mono">{domain}</span>}
|
||||
icon={<ArrowRightLeft size={HEAD_ICON_SIZE} />}
|
||||
width={DRAWER_WIDTH}
|
||||
>
|
||||
<div className="cutover">
|
||||
<ol className="cutover__stepper">
|
||||
{STAGES.map((s, i) => (
|
||||
<li
|
||||
key={s.id}
|
||||
className={`cutover__step${i === stageIndex ? ' is-active' : ''}${i < stageIndex ? ' is-done' : ''}`}
|
||||
>
|
||||
<span className="cutover__step-dot">
|
||||
{i < stageIndex ? <CheckCircle2 size={13} aria-hidden="true" /> : i + 1}
|
||||
</span>
|
||||
{s.label}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
{error && (
|
||||
<div className="cutover__callout cutover__callout--danger">
|
||||
<AlertTriangle size={16} aria-hidden="true" />
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stage 1 — pick the target address + record types */}
|
||||
{stage === 'target' && (
|
||||
<div className="cutover__stage">
|
||||
<p className="cutover__lead">
|
||||
{t('app.cutoverDrawer.repoint', 'Repoint')} <strong>{domain}</strong> {t('app.cutoverDrawer.atTheBoxWhereTheImported', 'at the server where the imported site now lives. Its current records are snapshotted first, so the switch can always be reverted.')}
|
||||
</p>
|
||||
|
||||
<div className="cutover__field">
|
||||
<Label htmlFor="cutover-target">{t('app.cutoverDrawer.newAddressTarget', 'New address (target)')}</Label>
|
||||
<Input
|
||||
id="cutover-target"
|
||||
value={target}
|
||||
onChange={(e) => setTarget(e.target.value)}
|
||||
placeholder="203.0.113.10"
|
||||
disabled={busy}
|
||||
/>
|
||||
<span className="cutover__hint">{t('app.cutoverDrawer.theIpOrHostnameForCname', 'The IP (or hostname for CNAME) the records should point to.')}</span>
|
||||
</div>
|
||||
|
||||
<div className="cutover__field">
|
||||
<Label htmlFor="cutover-zone">{t('app.cutoverDrawer.providerZoneId', 'Provider zone id')}</Label>
|
||||
<Input
|
||||
id="cutover-zone"
|
||||
value={zoneId}
|
||||
onChange={(e) => setZoneId(e.target.value)}
|
||||
placeholder={t('app.cutoverDrawer.theDnsProviderSZoneIdentifier', 'the DNS provider\'s zone identifier')}
|
||||
disabled={busy}
|
||||
/>
|
||||
{noZone && (
|
||||
<span className="cutover__hint cutover__hint--warn">
|
||||
{t('app.cutoverDrawer.thisDomainHasNoConnectedProvider', 'This domain has no connected provider zone. Cutover needs one to read and write records.')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="cutover__field">
|
||||
<Label>{t('app.cutoverDrawer.recordTypes', 'Record types')}</Label>
|
||||
<div className="cutover__types">
|
||||
{RECORD_TYPE_CHOICES.map((t) => (
|
||||
<label key={t} className="cutover__type">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={recordTypes.includes(t)}
|
||||
onChange={() => toggleRecordType(t)}
|
||||
disabled={busy}
|
||||
/>
|
||||
{t}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="cutover__actions">
|
||||
<span />
|
||||
<Button onClick={captureAndReview} disabled={busy || !canCapture}>
|
||||
{busy ? <><Spinner size="sm" /> {t('app.cutoverDrawer.capturing', 'Capturing…')}</> : <><Camera size={14} /> {t('app.cutoverDrawer.snapshotPreview', 'Snapshot and preview')} <ArrowRight size={14} /></>}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stage 2 — snapshot summary, TTL guidance, dry-run diff */}
|
||||
{stage === 'review' && (
|
||||
<div className="cutover__stage">
|
||||
<div className="cutover__summary">
|
||||
<div className="cutover__stat">
|
||||
<span className="cutover__stat-val">{snapshot?.record_count ?? 0}</span>
|
||||
<span className="cutover__stat-label">{t('app.cutoverDrawer.recordsCaptured', 'records captured')}</span>
|
||||
</div>
|
||||
<div className="cutover__stat">
|
||||
<span className="cutover__stat-val">{target.trim()}</span>
|
||||
<span className="cutover__stat-label">{t('app.cutoverDrawer.newTarget', 'new target')}</span>
|
||||
</div>
|
||||
<div className="cutover__stat">
|
||||
<span className="cutover__stat-val">{recordTypes.join(', ')}</span>
|
||||
<span className="cutover__stat-label">{t('app.cutoverDrawer.recordTypes2', 'record types')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{ttl && (
|
||||
<div className={`cutover__callout${ttl.needs_lowering ? ' cutover__callout--warning' : ' cutover__callout--info'}`}>
|
||||
<RadioTower size={16} aria-hidden="true" />
|
||||
<p>{ttl.message}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="cutover__section">
|
||||
<h3><Globe size={15} aria-hidden="true" /> {t('app.cutoverDrawer.plannedChanges', 'Planned changes')}</h3>
|
||||
{plan?.ops?.length ? (
|
||||
<DataTable
|
||||
columns={PLAN_COLUMNS}
|
||||
data={plan.ops.map((op, i) => ({ ...op, __idx: i }))}
|
||||
keyField={(op) => `${op.record_type}-${op.name}-${op.__idx}`}
|
||||
sortable={false}
|
||||
columnMenu={false}
|
||||
className="cutover__table-wrap"
|
||||
/>
|
||||
) : (
|
||||
<p className="cutover__muted">{t('app.cutoverDrawer.noChangesToApplyForThe', 'No changes to apply for the selected record types.')}</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="cutover__actions">
|
||||
<Button variant="outline" onClick={() => setStage('target')} disabled={busy}>
|
||||
<ArrowLeft size={14} /> {t('common.actions.back', 'Back')}
|
||||
</Button>
|
||||
<Button onClick={() => setConfirmOpen(true)} disabled={busy || !plan?.ops?.length}>
|
||||
{busy ? <><Spinner size="sm" /> {t('app.cutoverDrawer.applying', 'Applying…')}</> : <><ArrowRightLeft size={14} /> {t('app.cutoverDrawer.applyCutover', 'Apply cutover')}</>}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stage 3 — cutover result, verify, revert */}
|
||||
{stage === 'verify' && (
|
||||
<div className="cutover__stage">
|
||||
{cutoverResult && (
|
||||
<div className={`cutover__callout${cutoverResult.success ? ' cutover__callout--success' : ' cutover__callout--danger'}`}>
|
||||
{cutoverResult.success
|
||||
? <CheckCircle2 size={16} aria-hidden="true" />
|
||||
: <AlertTriangle size={16} aria-hidden="true" />}
|
||||
<p>
|
||||
{cutoverResult.success
|
||||
? <>{t('app.cutoverDrawer.cutoverApplied', 'Cutover applied:')} <strong>{domain}</strong> {t('app.cutoverDrawer.nowPointsAt', 'now points at')} <code>{target.trim()}</code>.</>
|
||||
: <>{t('app.cutoverDrawer.cutoverFinishedWithErrorsReviewBelow', 'Cutover finished with errors. Review below and revert if needed.')}</>}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="cutover__section">
|
||||
<h3><RadioTower size={15} aria-hidden="true" /> {t('app.cutoverDrawer.propagation', 'Propagation')}</h3>
|
||||
<p className="cutover__muted">
|
||||
{t('app.cutoverDrawer.publicResolversCacheTheOldAddress', 'Public resolvers cache the old address until their TTL expires. Check where the new address has taken effect.')}
|
||||
</p>
|
||||
|
||||
{verifyResult && (
|
||||
<div className="cutover__verify-head">
|
||||
{verifyResult.matches_expected != null && (
|
||||
<Pill kind={verifyResult.matches_expected ? 'green' : 'amber'}>
|
||||
{verifyResult.matches_expected ? t('app.cutoverDrawer.matchesNewTarget', 'Matches new target') : t('app.cutoverDrawer.notFullyPropagated', 'Not fully propagated')}
|
||||
</Pill>
|
||||
)}
|
||||
<Pill kind={verifyResult.propagated ? 'green' : 'gray'}>
|
||||
{verifyResult.propagated ? t('app.cutoverDrawer.propagated', 'Propagated') : t('app.cutoverDrawer.propagating', 'Propagating')}
|
||||
</Pill>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{verifyResult?.resolvers?.length > 0 && (
|
||||
<DataTable
|
||||
columns={RESOLVER_COLUMNS}
|
||||
data={verifyResult.resolvers.map((r, i) => ({ ...r, __idx: i }))}
|
||||
keyField={(r) => `${r.nameserver}-${r.__idx}`}
|
||||
sortable={false}
|
||||
columnMenu={false}
|
||||
className="cutover__table-wrap"
|
||||
/>
|
||||
)}
|
||||
|
||||
<Button variant="outline" size="sm" onClick={checkPropagation} disabled={busy}>
|
||||
{busy ? <><Spinner size="sm" /> {t('common.checking', 'Checking…')}</> : <><RadioTower size={14} /> {t('app.cutoverDrawer.checkPropagation', 'Check propagation')}</>}
|
||||
</Button>
|
||||
</section>
|
||||
|
||||
<section className="cutover__section cutover__section--revert">
|
||||
<h3><RotateCcw size={15} aria-hidden="true" /> {t('app.cutoverDrawer.rollBack', 'Roll back')}</h3>
|
||||
{revertResult ? (
|
||||
<div className={`cutover__callout${revertResult.success ? ' cutover__callout--success' : ' cutover__callout--danger'}`}>
|
||||
{revertResult.success
|
||||
? <CheckCircle2 size={16} aria-hidden="true" />
|
||||
: <AlertTriangle size={16} aria-hidden="true" />}
|
||||
<p>
|
||||
{t('app.cutoverDrawer.restoredRecords', { count: revertResult.results?.length ?? 0, defaultValue_one: 'Restored 1 record.', defaultValue_other: 'Restored {{count}} records.' })}
|
||||
{revertResult.deleted_count
|
||||
? ` ${t('app.cutoverDrawer.deletedCreatedRecords', { count: revertResult.deleted_count, defaultValue_one: 'Deleted 1 record the cutover created.', defaultValue_other: 'Deleted {{count}} records the cutover created.' })}`
|
||||
: ''}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="cutover__muted">
|
||||
{t('app.cutoverDrawer.oneClickRestoresTheSnapshotCaptured', 'One click restores the snapshot captured before this cutover, including deleting any records the cutover created.')}
|
||||
</p>
|
||||
)}
|
||||
<Button variant="outline" size="sm" onClick={revert} disabled={busy || !!revertResult}>
|
||||
{busy ? <><Spinner size="sm" /> {t('app.cutoverDrawer.reverting', 'Reverting…')}</> : <><RotateCcw size={14} /> {t('app.cutoverDrawer.revertCutover', 'Revert cutover')}</>}
|
||||
</Button>
|
||||
</section>
|
||||
|
||||
<div className="cutover__actions">
|
||||
<span />
|
||||
<Button variant="outline" onClick={onClose} disabled={busy}>{t('common.actions.done', 'Done')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={confirmOpen}
|
||||
title={t('app.cutoverDrawer.applyDnsCutover', 'Apply DNS cutover?')}
|
||||
message={t('app.cutoverDrawer.repointsRecords', { count: recordTypes.length, types: recordTypes.join(', '), domain: domain, target: target.trim(), defaultValue_one: 'This repoints the {{types}} record for {{domain}} at {{target}}. The snapshot lets you revert.', defaultValue_other: 'This repoints the {{types}} records for {{domain}} at {{target}}. The snapshot lets you revert.' })}
|
||||
confirmText={t('app.cutoverDrawer.applyCutover', 'Apply cutover')}
|
||||
variant="danger"
|
||||
onConfirm={applyCutover}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
|
||||
export default CutoverDrawer;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ChevronUp, ChevronDown, ChevronRight, Filter } from 'lucide-react';
|
||||
import { ArrowDownNarrowWide, ArrowUpNarrowWide, ChevronUp, ChevronDown, ChevronRight, Filter } from 'lucide-react';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { applyTableSorts, nextSorts, useTableSort } from '@/hooks/useTableSort';
|
||||
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
|
||||
@@ -19,6 +20,8 @@ import { useTranslation } from 'react-i18next';
|
||||
import { translateLabel } from '../../i18n/labels';
|
||||
import { Button as SharedButton } from '@/components/ui/button';
|
||||
|
||||
const SORT_NONE = '__none__';
|
||||
|
||||
/**
|
||||
* Declarative data table built on top of the shadcn/ui Table primitives.
|
||||
*
|
||||
@@ -41,6 +44,14 @@ import { Button as SharedButton } from '@/components/ui/button';
|
||||
* Enter triggers onRowClick, x toggles the cursor row's selection. Keys are
|
||||
* ignored while typing in a field or while a dialog holds focus.
|
||||
*
|
||||
* Responsive: under 640px every row becomes a stacked card (pure CSS on the
|
||||
* same markup, so sorting, selection, grouping and keyboard nav keep working).
|
||||
* The first visible column is the card title, the rest become "label · value"
|
||||
* rows using the column header as the label, a header-less trailing column
|
||||
* (actions) becomes a footer row of 40px targets, and the sortable headers
|
||||
* collapse into one sort select + direction toggle above the cards. Pass `responsive={false}` for
|
||||
* editor-style grids that must stay tabular on phones.
|
||||
*
|
||||
* Example:
|
||||
* <DataTable
|
||||
* columns={[
|
||||
@@ -105,6 +116,7 @@ export function DataTable({
|
||||
className,
|
||||
rowClassName,
|
||||
tableClassName,
|
||||
responsive = true,
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const internal = useTableSort({
|
||||
@@ -325,6 +337,13 @@ export function DataTable({
|
||||
return selectedKeys?.includes(key);
|
||||
});
|
||||
|
||||
// Card mode (<640px, see .sk-dtable--stack): the column header is the label.
|
||||
const cellLabel = (column) => (typeof column.header === 'string' ? translateLabel(t, column, 'header') : '');
|
||||
const cellRole = (column, index) => {
|
||||
if (isDecorative(column)) return 'sk-dtable__cell--actions';
|
||||
return index === 0 ? 'sk-dtable__cell--title' : undefined;
|
||||
};
|
||||
|
||||
const renderDataRow = (row) => {
|
||||
const key = typeof keyField === 'function' ? keyField(row) : row[keyField];
|
||||
const computedRowClass = typeof rowClassName === 'function'
|
||||
@@ -365,23 +384,61 @@ export function DataTable({
|
||||
/>
|
||||
</TableCell>
|
||||
)}
|
||||
{visibleColumns.map((column) => (
|
||||
{visibleColumns.map((column, columnIndex) => (
|
||||
<TableCell
|
||||
key={`${key}-${column.key}`}
|
||||
className={column.cellClassName}
|
||||
className={cn(column.cellClassName, cellRole(column, columnIndex))}
|
||||
data-label={cellLabel(column) || undefined}
|
||||
>
|
||||
{column.render
|
||||
? column.render(row)
|
||||
: row[column.key]}
|
||||
<div className="sk-dtable__value">
|
||||
{column.render
|
||||
? column.render(row)
|
||||
: row[column.key]}
|
||||
</div>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
};
|
||||
|
||||
// Phones hide the header, so column sort moves to a select + direction toggle.
|
||||
const sortColumns = visibleColumns.filter((column) => sortable && column.sortable && typeof column.header === 'string');
|
||||
const activeSort = sorts[0];
|
||||
const sortBar = responsive && sortColumns.length > 0 && (
|
||||
<div className="sk-dtable__sortbar">
|
||||
<Select
|
||||
value={activeSort?.key ?? SORT_NONE}
|
||||
onValueChange={(key) => setSorts(key === SORT_NONE ? [] : [{ key, direction: activeSort?.direction ?? 'asc' }])}
|
||||
>
|
||||
<SelectTrigger aria-label={t('app.dataTable.sortBy', 'Sort by')}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={SORT_NONE}>{t('app.dataTable.defaultOrder', 'Default order')}</SelectItem>
|
||||
{sortColumns.map((column) => (
|
||||
<SelectItem key={column.key} value={column.key}>{translateLabel(t, column, 'header')}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<SharedButton
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
disabled={!activeSort}
|
||||
aria-label={activeSort?.direction === 'desc'
|
||||
? t('app.dataTable.sortDescending', 'Sorted descending, switch to ascending')
|
||||
: t('app.dataTable.sortAscending', 'Sorted ascending, switch to descending')}
|
||||
onClick={() => setSorts([{ key: activeSort.key, direction: activeSort.direction === 'asc' ? 'desc' : 'asc' }])}
|
||||
>
|
||||
{activeSort?.direction === 'desc' ? <ArrowDownNarrowWide size={16} /> : <ArrowUpNarrowWide size={16} />}
|
||||
</SharedButton>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={cn('sk-dtable-wrap', className)} ref={wrapRef}>
|
||||
<Table className={cn('sk-dtable', tableClassName)}>
|
||||
{sortBar}
|
||||
<Table className={cn('sk-dtable', responsive && 'sk-dtable--stack', tableClassName)}>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
{selectable && (
|
||||
@@ -391,6 +448,11 @@ export function DataTable({
|
||||
onCheckedChange={(checked) => onToggleAll?.(!!checked)}
|
||||
aria-label={t('app.dataTable.selectAllRows', 'Select all rows')}
|
||||
/>
|
||||
<span className="sk-dtable__checklabel" aria-hidden="true">
|
||||
{selectedKeys?.length
|
||||
? t('app.dataTable.selectedCount', '{{count}} selected', { count: selectedKeys.length })
|
||||
: t('app.dataTable.selectAll', 'Select all')}
|
||||
</span>
|
||||
</TableHead>
|
||||
)}
|
||||
{visibleColumns.map((column, columnIndex) => {
|
||||
|
||||
@@ -50,7 +50,22 @@ export function PageTopbar({ icon, title, meta, tabs, actions, className, navLab
|
||||
);
|
||||
}
|
||||
|
||||
// Tab label plus the optional update-count pill. `iconOnlyNarrow` tabs keep
|
||||
// their label for assistive tech and, on phones, show it only while active.
|
||||
function TabContent({ tab }) {
|
||||
return (
|
||||
<>
|
||||
{tab.icon}
|
||||
{tab.iconOnlyNarrow ? <span className="sk-topbar__tab-label">{tab.label}</span> : tab.label}
|
||||
{tab.badgeCount > 0 && <span className="sk-topbar__badge">{tab.badgeCount}</span>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function matchTab(tab, path) {
|
||||
// Button tabs (`id` + `onSelect`) carry their own `active` flag — the page
|
||||
// owns the selection (e.g. a /page/:tab URL param) rather than the route.
|
||||
if (!tab.to) return !!tab.active;
|
||||
if (tab.end) return path === tab.to;
|
||||
// Segment-aware so "/fleet" doesn't swallow "/fleet-monitor".
|
||||
return path === tab.to || path.startsWith(tab.to + '/');
|
||||
@@ -63,7 +78,8 @@ function TopbarTabs({ tabs, label }) {
|
||||
const [popoverOpen, setPopoverOpen] = useState(false);
|
||||
const safeTabs = useMemo(
|
||||
() => (Array.isArray(tabs) ? tabs : []).filter(
|
||||
(tab) => tab && typeof tab.to === 'string' && tab.to.length > 0
|
||||
(tab) => tab && ((typeof tab.to === 'string' && tab.to.length > 0)
|
||||
|| (tab.id && typeof tab.onSelect === 'function'))
|
||||
),
|
||||
[tabs]
|
||||
);
|
||||
@@ -77,20 +93,56 @@ function TopbarTabs({ tabs, label }) {
|
||||
|
||||
const { containerRef, itemRefs, moreBtnRef, hiddenIndices, hiddenSet } = useOverflowItems({
|
||||
count: safeTabs.length,
|
||||
gap: 2,
|
||||
moreWidth: 56,
|
||||
gap: 4,
|
||||
moreWidth: 80,
|
||||
getActiveIndex,
|
||||
deps: [activeIndex],
|
||||
});
|
||||
|
||||
// Arrow/Home/End roving for button tabs (WAI-ARIA tablist): move focus and
|
||||
// select, like the sibling <Tabs> primitive does.
|
||||
const onKeyDown = (e) => {
|
||||
const keys = ['ArrowLeft', 'ArrowRight', 'Home', 'End'];
|
||||
if (!keys.includes(e.key) || !e.target.closest('[role="tab"]')) return;
|
||||
const visible = safeTabs.map((tab, i) => ({ tab, i })).filter(({ tab, i }) => !tab.to && !hiddenSet.has(i));
|
||||
const cur = visible.findIndex(({ i }) => itemRefs.current[i] === e.target);
|
||||
if (cur < 0) return;
|
||||
const rtl = getComputedStyle(e.currentTarget).direction === 'rtl';
|
||||
const step = e.key === 'ArrowRight' ? (rtl ? -1 : 1) : e.key === 'ArrowLeft' ? (rtl ? 1 : -1) : 0;
|
||||
const next = e.key === 'Home' ? 0 : e.key === 'End' ? visible.length - 1 : (cur + step + visible.length) % visible.length;
|
||||
e.preventDefault();
|
||||
itemRefs.current[visible[next].i]?.focus();
|
||||
visible[next].tab.onSelect();
|
||||
};
|
||||
|
||||
const buttonTabs = safeTabs.some((tab) => !tab.to);
|
||||
|
||||
return (
|
||||
// The nav is the flex-fill measurement region (kept right-aligned so a
|
||||
// changing page title never shoves the tabs sideways); the inner bar is
|
||||
// the visible segmented control that actually holds the tabs.
|
||||
<nav ref={containerRef} className="sk-topbar__tabs" aria-label={t('app.pageTopbar.sections', '{{label}} sections', { label })}>
|
||||
<div className="sk-topbar__tabs-inner">
|
||||
<nav ref={containerRef} className="sk-topbar__tabs" onKeyDown={buttonTabs ? onKeyDown : undefined} aria-label={t('app.pageTopbar.sections', '{{label}} sections', { label })}>
|
||||
<div className="sk-topbar__tabs-inner" role={buttonTabs ? 'tablist' : undefined}>
|
||||
{safeTabs.map((tab, i) => {
|
||||
const isHidden = hiddenSet.has(i);
|
||||
if (!tab.to) {
|
||||
return (
|
||||
<SharedButton
|
||||
key={tab.id}
|
||||
variant="unstyled"
|
||||
type="button"
|
||||
role="tab"
|
||||
ref={(el) => { itemRefs.current[i] = el; }}
|
||||
aria-selected={!!tab.active}
|
||||
tabIndex={tab.active ? 0 : -1}
|
||||
className={cn('sk-topbar__tab', tab.active && 'is-active', isHidden && 'is-hidden')}
|
||||
data-overflow={isHidden ? 'hidden' : undefined}
|
||||
onClick={tab.onSelect}
|
||||
>
|
||||
<TabContent tab={tab} />
|
||||
</SharedButton>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<NavLink
|
||||
key={tab.to}
|
||||
@@ -99,9 +151,10 @@ function TopbarTabs({ tabs, label }) {
|
||||
ref={(el) => { itemRefs.current[i] = el; }}
|
||||
className={({ isActive }) => cn('sk-topbar__tab', isActive && 'is-active', isHidden && 'is-hidden')}
|
||||
data-overflow={isHidden ? 'hidden' : undefined}
|
||||
aria-label={tab.iconOnlyNarrow ? tab.label : undefined}
|
||||
title={tab.iconOnlyNarrow ? tab.label : undefined}
|
||||
>
|
||||
{tab.icon}
|
||||
{tab.label}
|
||||
<TabContent tab={tab} />
|
||||
</NavLink>
|
||||
);
|
||||
})}
|
||||
@@ -123,6 +176,20 @@ function TopbarTabs({ tabs, label }) {
|
||||
{hiddenIndices.map((idx) => {
|
||||
const tab = safeTabs[idx];
|
||||
if (!tab) return null;
|
||||
if (!tab.to) {
|
||||
return (
|
||||
<SharedButton
|
||||
key={tab.id}
|
||||
variant="unstyled"
|
||||
type="button"
|
||||
className="tabs-overflow-item"
|
||||
data-state={idx === activeIndex ? 'active' : 'inactive'}
|
||||
onClick={() => { setPopoverOpen(false); tab.onSelect(); }}
|
||||
>
|
||||
<TabContent tab={tab} />
|
||||
</SharedButton>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<NavLink
|
||||
key={tab.to}
|
||||
@@ -132,8 +199,7 @@ function TopbarTabs({ tabs, label }) {
|
||||
data-state={idx === activeIndex ? 'active' : 'inactive'}
|
||||
onClick={() => setPopoverOpen(false)}
|
||||
>
|
||||
{tab.icon}
|
||||
{tab.label}
|
||||
<TabContent tab={tab} />
|
||||
</NavLink>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Search } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { isExternalReset } from './searchFieldSync';
|
||||
|
||||
// Self-contained search box: an icon + debounced text input. Keeps its own
|
||||
// internal text state and only lifts the (debounced) value up via onSearch, so
|
||||
@@ -15,11 +16,17 @@ export function SearchField({
|
||||
}) {
|
||||
const [text, setText] = useState(value);
|
||||
const timer = useRef(null);
|
||||
// The last text we lifted up. The parent echoing it back as `value` is not
|
||||
// a programmatic change — resyncing then would clobber keystrokes typed
|
||||
// since the emit (and cancel their pending search).
|
||||
const emitted = useRef(value);
|
||||
|
||||
// Sync when the parent resets/changes the value programmatically (e.g. a
|
||||
// "Reset filters" action). Cancel any pending search so it cannot restore
|
||||
// the old query after the parent has cleared it.
|
||||
useEffect(() => {
|
||||
if (!isExternalReset(value, emitted.current)) return;
|
||||
emitted.current = value;
|
||||
if (timer.current) {
|
||||
clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
@@ -33,6 +40,7 @@ export function SearchField({
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => {
|
||||
timer.current = null;
|
||||
emitted.current = next;
|
||||
onSearch?.(next);
|
||||
}, debounce);
|
||||
};
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { useRef } from 'react';
|
||||
import { useScrollTabs } from '@/hooks/useScrollTabs';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button as SharedButton } from '@/components/ui/button';
|
||||
|
||||
@@ -5,8 +7,10 @@ import { Button as SharedButton } from '@/components/ui/button';
|
||||
// options: array of strings, or { value, label, icon?, count? } objects.
|
||||
export function SegControl({ options = [], value, onChange, className, ...props }) {
|
||||
const items = options.map((o) => (typeof o === 'string' ? { value: o, label: o } : o));
|
||||
const ref = useRef(null);
|
||||
useScrollTabs(ref);
|
||||
return (
|
||||
<div className={cn('sk-seg', className)} role="tablist" {...props}>
|
||||
<div ref={ref} className={cn('sk-seg sk-tabscroll', className)} role="tablist" {...props}>
|
||||
{items.map((o) => (
|
||||
<SharedButton variant="unstyled"
|
||||
key={o.value}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// A Pill's dot without the label; the status text rides along as the accessible
|
||||
// name and tooltip. kind: same vocabulary as Pill.
|
||||
export function StatusDot({ kind = 'gray', label, className }) {
|
||||
return <span role="img" aria-label={label} title={label} className={cn('sk-statusdot', `sk-statusdot--${kind}`, className)} />;
|
||||
}
|
||||
|
||||
export default StatusDot;
|
||||
@@ -0,0 +1,23 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
import { isExternalReset } from '../searchFieldSync.js';
|
||||
|
||||
// The parent echoing the debounced query back must not resync the input —
|
||||
// that dropped keystrokes typed while the request was in flight ("word" → "wrd").
|
||||
test('an echo of the last emitted query is not a reset', () => {
|
||||
assert.equal(isExternalReset('wor', 'wor'), false);
|
||||
});
|
||||
|
||||
test('a programmatic change (Reset filters) is a reset', () => {
|
||||
assert.equal(isExternalReset('', 'wor'), true);
|
||||
});
|
||||
|
||||
// No jsdom here, so guard the structural root cause instead: a search-driven
|
||||
// fetch must never swap the Templates tree (and with it the toolbar) out.
|
||||
test('Templates keeps its toolbar mounted while loading', () => {
|
||||
const src = readFileSync(new URL('../../../pages/Templates.jsx', import.meta.url), 'utf8');
|
||||
assert.doesNotMatch(src, /\n\s+if \(loading\) \{\s*\n\s+return/);
|
||||
assert.match(src, /aria-busy=\{loading\}/);
|
||||
});
|
||||
@@ -2,6 +2,7 @@
|
||||
// Shared, reusable building blocks for the new "infra console" look. Styles
|
||||
// live in styles/components/_design-system.scss (sk-* namespace).
|
||||
export { Pill } from './Pill';
|
||||
export { StatusDot } from './StatusDot';
|
||||
export {
|
||||
statusKind, statusVariant, statusDotClass, statusLabel,
|
||||
alertStatusKind, processStateVariant, envActionKind,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// A `value` prop that merely echoes what the field last emitted is not a
|
||||
// programmatic reset: resyncing then would overwrite keystrokes typed since the
|
||||
// emit. Kept out of SearchField.jsx so it is testable without a DOM.
|
||||
export const isExternalReset = (value, emitted) => value !== emitted;
|
||||
@@ -5,6 +5,7 @@ import ListToolbar from '../ds/ListToolbar';
|
||||
import { Button } from '../ui/button';
|
||||
import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '../ui/select';
|
||||
import { useEffectiveEnvironment } from './useEffectiveEnvironment';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
export default function EffectiveEnvironment({ appId }) {
|
||||
const { t } = useTranslation();
|
||||
@@ -27,7 +28,7 @@ export default function EffectiveEnvironment({ appId }) {
|
||||
{ key: 'is_reference', header: t('effectiveEnv.value', 'Value'), render: row => row.is_reference ? t('effectiveEnv.reference', 'Reference · resolved at deployment') : t('effectiveEnv.hidden', 'Hidden') },
|
||||
];
|
||||
return <div className="env-vars-container">
|
||||
<p className="hint">{t('effectiveEnv.explanation', 'Managed variables for the next deployment or restart, not a live container inspection. Image and Compose-file variables are not included. Values are hidden, including references and interpolated secrets.')}</p>
|
||||
<p className="hint">{t('effectiveEnv.explanationShort', 'Managed variables for the next deploy.')} <InfoTip>{t('effectiveEnv.explanation', 'Managed variables for the next deployment or restart, not a live container inspection. Image and Compose-file variables are not included. Values are hidden, including references and interpolated secrets.')}</InfoTip></p>
|
||||
<ListToolbar tools={<Button variant="outline" onClick={refresh} disabled={loading}>{t('effectiveEnv.refresh', 'Refresh')}</Button>}>
|
||||
{services.length > 0 ? <Select value={service || ''} onValueChange={selectService}>
|
||||
<SelectTrigger aria-label={t('effectiveEnv.service', 'Compose service')}><SelectValue /></SelectTrigger>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useLockBodyScroll } from '@/hooks/useLockBodyScroll';
|
||||
import { SheetPanel } from '@/components/ui/sheet';
|
||||
import { X, Edit3, Download, EyeOff, Lock, Trash2, Copy } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import FileIcon from './FileIcon';
|
||||
@@ -32,165 +32,170 @@ export default function PreviewDrawer({
|
||||
fileApi,
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// Lock body scroll only for the overlay drawer; the inline pane scrolls
|
||||
// within its own column and must not freeze the page.
|
||||
useLockBodyScroll(Boolean(file) && !inline);
|
||||
|
||||
if (!file) return null;
|
||||
|
||||
const type = getFileType(file);
|
||||
const isImage = type === 'image';
|
||||
|
||||
return (
|
||||
const content = (
|
||||
<>
|
||||
{!inline && <div className="preview-drawer-backdrop" onClick={onClose} />}
|
||||
<aside
|
||||
className={inline ? 'preview-drawer file-preview-pane' : 'preview-drawer'}
|
||||
role={inline ? 'complementary' : 'dialog'}
|
||||
aria-label={t('app.previewDrawer.filePreview', 'File preview')}
|
||||
>
|
||||
<header className="preview-drawer-header">
|
||||
<FileIcon entry={file} size={20} />
|
||||
<div className="preview-drawer-title">
|
||||
<h3>{file.name}</h3>
|
||||
<p className="preview-drawer-path">{file.path}</p>
|
||||
</div>
|
||||
<Button variant="unstyled" type="button" className="preview-drawer-close" onClick={onClose} aria-label={t('common.actions.close', 'Close')}>
|
||||
<X size={18} />
|
||||
</Button>
|
||||
</header>
|
||||
<header className="preview-drawer-header">
|
||||
<FileIcon entry={file} size={20} />
|
||||
<div className="preview-drawer-title">
|
||||
<h3>{file.name}</h3>
|
||||
<p className="preview-drawer-path">{file.path}</p>
|
||||
</div>
|
||||
<Button variant="unstyled" type="button" className="preview-drawer-close" onClick={onClose} aria-label={t('common.actions.close', 'Close')}>
|
||||
<X size={18} />
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<div className="preview-drawer-meta">
|
||||
<div className="meta-item">
|
||||
<span className="meta-label">{t('common.labels.size', 'Size')}</span>
|
||||
<span className="meta-value">{file.size_human}</span>
|
||||
</div>
|
||||
<div className="meta-item">
|
||||
<span className="meta-label">{t('app.previewDrawer.owner', 'Owner')}</span>
|
||||
<span className="meta-value">{file.owner}</span>
|
||||
</div>
|
||||
<div className="meta-item">
|
||||
<span className="meta-label">{t('app.previewDrawer.group', 'Group')}</span>
|
||||
<span className="meta-value">{file.group}</span>
|
||||
</div>
|
||||
<div className="meta-item">
|
||||
<span className="meta-label">{t('common.labels.permissions', 'Permissions')}</span>
|
||||
<span className="meta-value mono">{file.permissions}</span>
|
||||
</div>
|
||||
{file.mime_type && (
|
||||
<div className="meta-item meta-item-wide">
|
||||
<span className="meta-label">MIME</span>
|
||||
<span className="meta-value mono">{file.mime_type}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="preview-drawer-meta">
|
||||
<div className="meta-item">
|
||||
<span className="meta-label">{t('common.labels.size', 'Size')}</span>
|
||||
<span className="meta-value">{file.size_human}</span>
|
||||
</div>
|
||||
<div className="meta-item">
|
||||
<span className="meta-label">{t('app.previewDrawer.owner', 'Owner')}</span>
|
||||
<span className="meta-value">{file.owner}</span>
|
||||
</div>
|
||||
<div className="meta-item">
|
||||
<span className="meta-label">{t('app.previewDrawer.group', 'Group')}</span>
|
||||
<span className="meta-value">{file.group}</span>
|
||||
</div>
|
||||
<div className="meta-item">
|
||||
<span className="meta-label">{t('common.labels.permissions', 'Permissions')}</span>
|
||||
<span className="meta-value mono">{file.permissions}</span>
|
||||
</div>
|
||||
{file.mime_type && (
|
||||
<div className="meta-item meta-item-wide">
|
||||
<span className="meta-label">{t('app.previewDrawer.modified', 'Modified')}</span>
|
||||
<span className="meta-value">{formatDateTime(file.modified)}</span>
|
||||
<span className="meta-label">MIME</span>
|
||||
<span className="meta-value mono">{file.mime_type}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="meta-item meta-item-wide">
|
||||
<span className="meta-label">{t('app.previewDrawer.modified', 'Modified')}</span>
|
||||
<span className="meta-value">{formatDateTime(file.modified)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="preview-drawer-actions">
|
||||
{!file.is_dir && (
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn" onClick={() => onDownload(file)}>
|
||||
<Download size={14} /> {t('common.actions.download', 'Download')}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn" onClick={() => onCopyPath(file.path)}>
|
||||
<Copy size={14} /> {t('app.previewDrawer.copyPath', 'Copy path')}
|
||||
<div className="preview-drawer-actions">
|
||||
{!file.is_dir && (
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn" onClick={() => onDownload(file)}>
|
||||
<Download size={14} /> {t('common.actions.download', 'Download')}
|
||||
</Button>
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn" onClick={() => onRename(file)}>
|
||||
<Edit3 size={14} /> {t('app.previewDrawer.rename', 'Rename')}
|
||||
</Button>
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn" onClick={() => onPermissions(file)}>
|
||||
<Lock size={14} /> {t('common.labels.permissions', 'Permissions')}
|
||||
</Button>
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn danger" onClick={() => onDelete(file)}>
|
||||
<Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn" onClick={() => onCopyPath(file.path)}>
|
||||
<Copy size={14} /> {t('app.previewDrawer.copyPath', 'Copy path')}
|
||||
</Button>
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn" onClick={() => onRename(file)}>
|
||||
<Edit3 size={14} /> {t('app.previewDrawer.rename', 'Rename')}
|
||||
</Button>
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn" onClick={() => onPermissions(file)}>
|
||||
<Lock size={14} /> {t('common.labels.permissions', 'Permissions')}
|
||||
</Button>
|
||||
<Button variant="unstyled" type="button" className="drawer-action-btn danger" onClick={() => onDelete(file)}>
|
||||
<Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="preview-drawer-body">
|
||||
{isImage ? (
|
||||
<div className="preview-image-wrap">
|
||||
<ImageThumb
|
||||
path={file.path}
|
||||
fileApi={fileApi}
|
||||
fallback={
|
||||
<div className="preview-unavailable">
|
||||
<EyeOff size={48} strokeWidth={1.5} />
|
||||
<p>{t('app.previewDrawer.imagePreviewUnavailable', 'Image preview unavailable')}</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : file.is_editable ? (
|
||||
<div className="editor-wrap">
|
||||
<div className="editor-toolbar">
|
||||
<span className="editor-status">{editing ? t('app.previewDrawer.editing', 'Editing') : t('app.previewDrawer.readOnly', 'Read-only')}</span>
|
||||
<div className="editor-buttons">
|
||||
{!editing ? (
|
||||
<Button size="sm" onClick={onStartEdit}>
|
||||
<Edit3 size={14} /> {t('common.actions.edit', 'Edit')}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={onCancelEdit}>
|
||||
{t('common.actions.cancel', 'Cancel')}
|
||||
</Button>
|
||||
<Button size="sm" onClick={onSave}>{t('common.actions.save', 'Save')}</Button>
|
||||
</>
|
||||
)}
|
||||
<div className="preview-drawer-body">
|
||||
{isImage ? (
|
||||
<div className="preview-image-wrap">
|
||||
<ImageThumb
|
||||
path={file.path}
|
||||
fileApi={fileApi}
|
||||
fallback={
|
||||
<div className="preview-unavailable">
|
||||
<EyeOff size={48} strokeWidth={1.5} />
|
||||
<p>{t('app.previewDrawer.imagePreviewUnavailable', 'Image preview unavailable')}</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : file.is_editable ? (
|
||||
<div className="editor-wrap">
|
||||
<div className="editor-toolbar">
|
||||
<span className="editor-status">{editing ? t('app.previewDrawer.editing', 'Editing') : t('app.previewDrawer.readOnly', 'Read-only')}</span>
|
||||
<div className="editor-buttons">
|
||||
{!editing ? (
|
||||
<Button size="sm" onClick={onStartEdit}>
|
||||
<Edit3 size={14} /> {t('common.actions.edit', 'Edit')}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={onCancelEdit}>
|
||||
{t('common.actions.cancel', 'Cancel')}
|
||||
</Button>
|
||||
<Button size="sm" onClick={onSave}>{t('common.actions.save', 'Save')}</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{(() => {
|
||||
if (editing) {
|
||||
return (
|
||||
<textarea
|
||||
className="file-editor"
|
||||
value={fileContent}
|
||||
onChange={(e) => setFileContent(e.target.value)}
|
||||
spellCheck={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const lines = (fileContent ?? '').split('\n');
|
||||
if (lines.length > MAX_HIGHLIGHT_LINES) {
|
||||
return (
|
||||
<textarea
|
||||
className="file-editor"
|
||||
value={fileContent}
|
||||
readOnly
|
||||
spellCheck={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const ext = fileExt(file.name);
|
||||
</div>
|
||||
{(() => {
|
||||
if (editing) {
|
||||
return (
|
||||
<div className="pv-code" aria-label={t('app.previewDrawer.fileContents', 'File contents')}>
|
||||
{lines.map((l, i) => (
|
||||
<div className="pv-code__line" key={i}>
|
||||
<span className="pv-code__n">{i + 1}</span>
|
||||
<span
|
||||
className="pv-code__c"
|
||||
dangerouslySetInnerHTML={{ __html: highlightLine(l, ext) || ' ' }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<textarea
|
||||
className="file-editor"
|
||||
value={fileContent}
|
||||
onChange={(e) => setFileContent(e.target.value)}
|
||||
spellCheck={false}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="preview-unavailable">
|
||||
<EyeOff size={48} strokeWidth={1.5} />
|
||||
<p>{t('app.previewDrawer.previewNotAvailableForThisFile', 'Preview not available for this file type')}</p>
|
||||
<Button onClick={() => onDownload(file)}>
|
||||
<Download size={16} /> {t('app.previewDrawer.downloadFile', 'Download file')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
}
|
||||
const lines = (fileContent ?? '').split('\n');
|
||||
if (lines.length > MAX_HIGHLIGHT_LINES) {
|
||||
return (
|
||||
<textarea
|
||||
className="file-editor"
|
||||
value={fileContent}
|
||||
readOnly
|
||||
spellCheck={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const ext = fileExt(file.name);
|
||||
return (
|
||||
<div className="pv-code" aria-label={t('app.previewDrawer.fileContents', 'File contents')}>
|
||||
{lines.map((l, i) => (
|
||||
<div className="pv-code__line" key={i}>
|
||||
<span className="pv-code__n">{i + 1}</span>
|
||||
<span
|
||||
className="pv-code__c"
|
||||
dangerouslySetInnerHTML={{ __html: highlightLine(l, ext) || ' ' }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="preview-unavailable">
|
||||
<EyeOff size={48} strokeWidth={1.5} />
|
||||
<p>{t('app.previewDrawer.previewNotAvailableForThisFile', 'Preview not available for this file type')}</p>
|
||||
<Button onClick={() => onDownload(file)}>
|
||||
<Download size={16} /> {t('app.previewDrawer.downloadFile', 'Download file')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
const label = t('app.previewDrawer.filePreview', 'File preview');
|
||||
|
||||
// Overlay mode is a real modal dialog (focus trap, Escape, focus restore);
|
||||
// inline mode is a plain landmark column.
|
||||
if (!inline) {
|
||||
return (
|
||||
<SheetPanel className="preview-drawer" overlayClassName="preview-drawer-backdrop" label={label} onClose={onClose}>
|
||||
{content}
|
||||
</SheetPanel>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<aside className="preview-drawer file-preview-pane" role="complementary" aria-label={label}>
|
||||
{content}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -291,7 +291,8 @@ export default function ResourceListPage({
|
||||
|
||||
// Nothing to host while the page is empty or still loading — the chrome
|
||||
// acts on a table that isn't there.
|
||||
const hasTable = !loading && resolvedTotal > 0;
|
||||
// A refetch over existing rows keeps the chrome (and the search box's focus).
|
||||
const hasTable = resolvedTotal > 0;
|
||||
const { hosted: chromeHoisted, portal: chromePortal } = useTopbarChrome(
|
||||
chromeNode,
|
||||
{ enabled: chromeInTopbar && hasTable },
|
||||
@@ -326,6 +327,7 @@ export default function ResourceListPage({
|
||||
// card grid when the page opted into one.
|
||||
return (
|
||||
<div className={cn('sk-tabgroup__inner', className)}>
|
||||
{chromePortal}
|
||||
<EmptyState
|
||||
loading
|
||||
loadingVariant={renderCard && view === 'cards' ? 'cards' : 'table'}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { CheckCircle2, DownloadCloud, ArrowUpCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { CatalogCard } from '@/components/ds';
|
||||
import { ExtensionCover } from './ExtensionCover';
|
||||
import { titleCase } from './extensionCatalog';
|
||||
|
||||
// Trust as a plain-text fact on the card: only the two states that carry
|
||||
// information (a hash-bound review, or a registry entry nobody reviewed).
|
||||
// Built-in entries never carry a trust field, so they show nothing.
|
||||
const TrustFact = ({ entry }) => {
|
||||
const { t } = useTranslation();
|
||||
if (entry.trust === 'reviewed') {
|
||||
const review = entry.review || {};
|
||||
const title = review.reviewer && review.date
|
||||
? `Reviewed by ${review.reviewer} on ${review.date}`
|
||||
: 'Reviewed by the ServerKit maintainers';
|
||||
return <span title={title}>{t('app.marketplace.reviewed', 'Reviewed')}</span>;
|
||||
}
|
||||
if (entry.trust === 'unreviewed' && entry.source === 'registry') {
|
||||
return <span>{t('app.marketplace.unreviewed', 'Unreviewed')}</span>;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const CatalogExtensionCard = ({ entry, update, busy, installing, onInstall, onUpdate, onOpenDetail }) => {
|
||||
const { t } = useTranslation();
|
||||
const category = entry.category || 'utility';
|
||||
const isLocal = entry.source === 'local';
|
||||
const installedLabel = entry.status && entry.status !== 'active'
|
||||
? titleCase(entry.status)
|
||||
: t('app.marketplace.installed', 'Installed');
|
||||
const hasTrustFact = entry.trust === 'reviewed'
|
||||
|| (entry.trust === 'unreviewed' && entry.source === 'registry');
|
||||
const canUpdate = Boolean(update?.update_available && update.compatible !== false);
|
||||
|
||||
let action;
|
||||
if (!entry.installed) {
|
||||
action = (
|
||||
<Button variant="outline" size="sm" disabled={installing} onClick={() => onInstall(entry.installKey)}>
|
||||
<DownloadCloud aria-hidden="true" />
|
||||
{installing
|
||||
? t('app.marketplace.installing', 'Installing…')
|
||||
: t('app.marketplace.install', 'Install')}
|
||||
</Button>
|
||||
);
|
||||
} else if (canUpdate) {
|
||||
action = (
|
||||
<Button size="sm" disabled={busy} onClick={() => onUpdate(update)}>
|
||||
<ArrowUpCircle aria-hidden="true" />
|
||||
{busy ? t('app.marketplace.updating', 'Updating…') : t('app.marketplace.updateTo', 'Update v{{version}}', { version: update.available_version })}
|
||||
</Button>
|
||||
);
|
||||
} else {
|
||||
action = (
|
||||
<span className="marketplace-installed-label">
|
||||
<CheckCircle2 aria-hidden="true" />
|
||||
{installedLabel}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CatalogCard
|
||||
icon={<ExtensionCover base="sk-catalog-card__art" entry={entry} category={category} brandSize={20} />}
|
||||
title={entry.displayName}
|
||||
sub={t('app.marketplace.versionByAuthor', 'v{{version}} · by {{author}}', {
|
||||
version: entry.version,
|
||||
author: entry.author || 'ServerKit',
|
||||
})}
|
||||
tag={titleCase(category)}
|
||||
featured={entry.featured}
|
||||
description={entry.description}
|
||||
facts={(isLocal || hasTrustFact) && (
|
||||
<>
|
||||
{isLocal && t('app.marketplace.builtIn', 'Built-in')}
|
||||
{isLocal && hasTrustFact && ' · '}
|
||||
<TrustFact entry={entry} />
|
||||
</>
|
||||
)}
|
||||
onClick={() => onOpenDetail(entry)}
|
||||
action={action}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default CatalogExtensionCard;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Package } from 'lucide-react';
|
||||
import { SegControl } from '@/components/ds';
|
||||
import { getCategoryIcon, titleCase } from './extensionCatalog';
|
||||
|
||||
// Scrollable category chips (fade edges come from SegControl's sk-tabscroll).
|
||||
export default function CategoryChips({ categories, value, onChange }) {
|
||||
const { t } = useTranslation();
|
||||
const options = [
|
||||
{ value: '', label: t('app.marketplace.all', 'All'), icon: <Package size={14} aria-hidden="true" /> },
|
||||
...categories.map((c) => {
|
||||
const Icon = getCategoryIcon(c);
|
||||
return { value: c, label: titleCase(c), icon: <Icon size={14} aria-hidden="true" /> };
|
||||
}),
|
||||
];
|
||||
return (
|
||||
<SegControl
|
||||
className="marketplace-chips"
|
||||
aria-label={t('app.marketplace.categories', 'Categories')}
|
||||
options={options}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useState } from 'react';
|
||||
import { sanitizeSvgInner } from '../../utils/sanitizeSvg';
|
||||
import { ExtensionBrandMark } from '../icons/ExtensionBrands';
|
||||
import { hasBrandMark, extensionCoverStyle } from '../icons/extensionBrandData';
|
||||
import { resolveExtensionIcon } from '../icons/ExtensionIcons';
|
||||
import { getCategoryIcon } from './extensionCatalog';
|
||||
|
||||
// Cover tile + artwork with a deterministic fallback chain:
|
||||
// registry logo image -> bundled illustrated icon -> Simple Icons brand mark ->
|
||||
// manifest icon SVG -> category lucide glyph. Image artwork (logo or bundled
|
||||
// icon) sits on a dark surface tile at one shared size; the white brand-mark /
|
||||
// glyph fallbacks keep the deterministic gradient so they stay legible. The
|
||||
// tile is chosen from what actually renders, so a registry logo that fails to
|
||||
// load falls back to the gradient instead of a blank tile. `base` is
|
||||
// the cover class ('sk-catalog-card__art' for the compact catalog-card icon,
|
||||
// 'extension-detail__cover' for the modal header tile); both share this component.
|
||||
export const ExtensionCover = ({ base, entry, category, brandSize = 34, children }) => {
|
||||
const [logoFailed, setLogoFailed] = useState(false);
|
||||
const rasterIcon = resolveExtensionIcon(entry.installKey, category);
|
||||
const imageSrc = entry.logo && !logoFailed ? entry.logo : rasterIcon;
|
||||
|
||||
if (imageSrc) {
|
||||
return (
|
||||
<div className={`${base} ${base}--icon`}>
|
||||
<img
|
||||
src={imageSrc}
|
||||
loading="lazy"
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className="extension-card__icon"
|
||||
onError={imageSrc === entry.logo ? () => setLogoFailed(true) : undefined}
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={base} style={extensionCoverStyle(entry.installKey, category)}>
|
||||
<ExtensionGlyph entry={entry} category={category} brandSize={brandSize} />
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const ExtensionGlyph = ({ entry, category, brandSize }) => {
|
||||
const Icon = getCategoryIcon(category);
|
||||
const iconSvg = entry.icon ? sanitizeSvgInner(entry.icon) : '';
|
||||
|
||||
if (hasBrandMark(entry.installKey)) {
|
||||
return (
|
||||
<ExtensionBrandMark
|
||||
slug={entry.installKey}
|
||||
size={brandSize}
|
||||
className="extension-card__brand"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (iconSvg) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
className="extension-card__glyph"
|
||||
/* sink-safe: iconSvg = sanitizeSvgInner(entry.icon) above */
|
||||
dangerouslySetInnerHTML={{ __html: iconSvg }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <Icon aria-hidden="true" className="extension-card__glyph" />;
|
||||
};
|
||||
|
||||
|
||||
export default ExtensionCover;
|
||||
@@ -0,0 +1,142 @@
|
||||
import { CheckCircle2, DownloadCloud, ExternalLink, ShieldCheck } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import Modal from '@/components/Modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import SignatureBadge from '@/components/marketplace/SignatureBadge';
|
||||
import { ExtensionCover } from './ExtensionCover';
|
||||
import { sourceBadgeVariant, titleCase } from './extensionCatalog';
|
||||
|
||||
// Trust badge derived from the registry's hash-bound review stamp. 'reviewed'
|
||||
// shows who/when in the tooltip; 'unreviewed' warns on registry entries
|
||||
// (built-in entries never carry a trust field).
|
||||
const TrustBadge = ({ entry }) => {
|
||||
const { t } = useTranslation();
|
||||
if (entry.trust === 'reviewed') {
|
||||
const review = entry.review || {};
|
||||
const title = review.reviewer && review.date
|
||||
? `Reviewed by ${review.reviewer} on ${review.date}`
|
||||
: 'Reviewed by the ServerKit maintainers';
|
||||
return (
|
||||
<Badge variant="success" title={title}>
|
||||
<ShieldCheck aria-hidden="true" /> {t('app.marketplace.reviewed', 'Reviewed')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (entry.trust === 'unreviewed' && entry.source === 'registry') {
|
||||
return <Badge variant="warning">{t('app.marketplace.unreviewed', 'Unreviewed')}</Badge>;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
export const ExtensionDetailModal = ({ entry, installing, statusVariant, onClose, onInstall }) => {
|
||||
const { t } = useTranslation();
|
||||
const category = entry.category || 'utility';
|
||||
const isLocal = entry.source === 'local';
|
||||
const screenshots = entry.screenshots || [];
|
||||
const permissions = Array.isArray(entry.permissions) ? entry.permissions : [];
|
||||
const configKeys = entry.configSchema && typeof entry.configSchema === 'object'
|
||||
? Object.keys(entry.configSchema)
|
||||
: [];
|
||||
const installedLabel = entry.status && entry.status !== 'active'
|
||||
? titleCase(entry.status)
|
||||
: 'Installed';
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title={entry.displayName} size="lg">
|
||||
<div className="extension-detail">
|
||||
<div className="extension-detail__header">
|
||||
<ExtensionCover base="extension-detail__cover" entry={entry} category={category} brandSize={22} />
|
||||
<div className="extension-detail__heading">
|
||||
<div className="extension-detail__badges">
|
||||
{entry.firstParty && (
|
||||
<Badge variant="secondary" className="extension-firstparty">{t('app.marketplace.byServerkit2', 'by ServerKit')}</Badge>
|
||||
)}
|
||||
<TrustBadge entry={entry} />
|
||||
{entry.source === 'registry' && (
|
||||
<SignatureBadge signature={{
|
||||
status: entry.signed ? (entry.publisherTrusted ? 'verified' : 'untrusted_key') : 'unsigned',
|
||||
key_id: entry.publisherKeyId,
|
||||
}} />
|
||||
)}
|
||||
<Badge variant={sourceBadgeVariant(entry.source)}>{entry.sourceLabel}</Badge>
|
||||
<Badge variant="outline">{titleCase(category)}</Badge>
|
||||
</div>
|
||||
<div className="extension-detail__meta">
|
||||
<span>v{entry.version}</span>
|
||||
{entry.author && <span>by {entry.author}</span>}
|
||||
<span>{isLocal ? 'built-in' : entry.extensionType}</span>
|
||||
{entry.repo && (
|
||||
<a
|
||||
href={entry.repo}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="extension-detail__repo-link"
|
||||
>
|
||||
<ExternalLink aria-hidden="true" />
|
||||
{t('app.marketplace.sourceRepo', 'Source repo')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="extension-detail__desc">{entry.description}</p>
|
||||
|
||||
{permissions.length > 0 && (
|
||||
<div className="extension-detail__consent">
|
||||
<p className="extension-detail__section-label">{t('app.marketplace.thisExtensionRequests', 'This extension requests:')}</p>
|
||||
<div className="extension-detail__chips">
|
||||
{permissions.map((permission) => (
|
||||
<Badge key={permission} variant="outline">{permission}</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{configKeys.length > 0 && (
|
||||
<div className="extension-detail__config">
|
||||
<p className="extension-detail__section-label">{t('app.marketplace.configuration', 'Settings')}</p>
|
||||
<ul className="extension-detail__config-list">
|
||||
{configKeys.map((key) => (
|
||||
<li key={key}><code>{key}</code></li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{screenshots.length > 0 && (
|
||||
<div className="extension-detail__gallery" aria-label={t('app.marketplace.screenshots', 'Screenshots')}>
|
||||
{screenshots.map((src, index) => (
|
||||
<img
|
||||
key={src}
|
||||
src={src}
|
||||
alt={`${entry.displayName} screenshot ${index + 1}`}
|
||||
className="extension-detail__shot"
|
||||
loading="lazy"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="extension-detail__actions">
|
||||
{entry.installed ? (
|
||||
<Badge variant={isLocal ? statusVariant(entry.status) : 'success'}>
|
||||
<CheckCircle2 aria-hidden="true" />
|
||||
{installedLabel}
|
||||
</Badge>
|
||||
) : (
|
||||
<Button disabled={installing} onClick={onInstall}>
|
||||
<DownloadCloud aria-hidden="true" />
|
||||
{installing ? t('app.marketplace.installing', 'Installing…') : t('app.marketplace.install', 'Install')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
export default ExtensionDetailModal;
|
||||
@@ -7,6 +7,7 @@ import { Pill } from '@/components/ds';
|
||||
import { formatRelativeTime } from '../../utils/time';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { formatDateTime } from '@/utils/intl';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// The backend stamps observations with datetime.utcnow().isoformat(), which
|
||||
// carries no timezone suffix — JS would read that as local time and skew every
|
||||
@@ -51,7 +52,7 @@ const PermissionRow = ({ row }) => {
|
||||
</Pill>
|
||||
</div>
|
||||
<p className="extension-permissions__note">
|
||||
{t('app.extensionPermissionsDialog.thePanelExposesNoGatedHelper', 'The panel exposes no gated helper for this capability. An extension that wants it imports the host module directly, and nothing in the panel sees the call. Whether this extension has used it cannot be answered here.')}
|
||||
{t('app.extensionPermissionsDialog.noGatedHelperShort', 'Panel cannot see this capability.')} <InfoTip>{t('app.extensionPermissionsDialog.thePanelExposesNoGatedHelper', 'The panel exposes no gated helper for this capability. An extension that wants it imports the host module directly, and nothing in the panel sees the call. Whether this extension has used it cannot be answered here.')}</InfoTip>
|
||||
</p>
|
||||
{row.uses > 0 && (
|
||||
<p className="extension-permissions__note">
|
||||
@@ -93,7 +94,7 @@ const PermissionRow = ({ row }) => {
|
||||
</Pill>
|
||||
</div>
|
||||
<p className="extension-permissions__note">
|
||||
{t('app.extensionPermissionsDialog.everyUseOfThisCapabilityHas', 'Every use of this capability has to pass through the panel\'s SDK gate, and the gate has recorded none since the panel process started. Either the extension has not needed it yet, or it declares more than it uses.')}
|
||||
{t('app.extensionPermissionsDialog.noGatedUseShort', 'No gated use since panel start.')} <InfoTip>{t('app.extensionPermissionsDialog.everyUseOfThisCapabilityHas', 'Every use of this capability has to pass through the panel\'s SDK gate, and the gate has recorded none since the panel process started. Either the extension has not needed it yet, or it declares more than it uses.')}</InfoTip>
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
@@ -167,7 +168,7 @@ const PermissionsSection = ({ report }) => {
|
||||
)}
|
||||
|
||||
<p className="extension-permissions__footnote">
|
||||
{t('app.extensionPermissionsDialog.declaredPermissionsAreAConsentSignal', 'Declared permissions are a consent signal, not a sandbox. Extension code runs inside the panel process with the panel\'s privileges; the panel can record what passes through its own SDK and cannot confine what does not.')}
|
||||
{t('app.extensionPermissionsDialog.consentSignalShort', 'Permissions are consent, not a sandbox.')} <InfoTip>{t('app.extensionPermissionsDialog.declaredPermissionsAreAConsentSignal', 'Declared permissions are a consent signal, not a sandbox. Extension code runs inside the panel process with the panel\'s privileges; the panel can record what passes through its own SDK and cannot confine what does not.')}</InfoTip>
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
@@ -194,7 +195,7 @@ const RequirementsSection = ({ requirements }) => {
|
||||
<p className="extension-permissions__note">
|
||||
{pipEnabled
|
||||
? <>{t('app.extensionPermissionsDialog.dependencyInstallationIsCurrentlyEnabledOn', 'Dependency installation is currently enabled on this panel (')}<code>{envVar}</code>).</>
|
||||
: <>{t('app.extensionPermissionsDialog.dependencyInstallationIsOffOnThis', 'Dependency installation is off on this panel. When an extension ships Python packages, the panel writes the file next to the extension instead of installing it, and lists it here.')}</>}
|
||||
: <>{t('app.extensionPermissionsDialog.dependencyInstallOffShort', 'Dependency installation is off.')} <InfoTip>{t('app.extensionPermissionsDialog.dependencyInstallationIsOffOnThis', 'Dependency installation is off on this panel. When an extension ships Python packages, the panel writes the file next to the extension instead of installing it, and lists it here.')}</InfoTip></>}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
@@ -214,7 +215,7 @@ const RequirementsSection = ({ requirements }) => {
|
||||
</p>
|
||||
<p className="extension-permissions__note">
|
||||
{pipEnabled
|
||||
? <>{t('app.extensionPermissionsDialog.dependencyInstallationIsEnabledOnThis', 'Dependency installation is enabled on this panel now (')}<code>{envVar}</code>{t('app.extensionPermissionsDialog.butThisFilePredatesThatThe', '), but this file predates that: the panel only installs requirements while installing or updating an extension. Reinstall or update this extension to apply it.')}</>
|
||||
? <>{t('app.extensionPermissionsDialog.installEnabledNotAppliedShort', 'Enabled now; reinstall to apply.')} <InfoTip>{t('app.extensionPermissionsDialog.dependencyInstallationIsEnabledOnThis', 'Dependency installation is enabled on this panel now (')}<code>{envVar}</code>{t('app.extensionPermissionsDialog.butThisFilePredatesThatThe', '), but this file predates that: the panel only installs requirements while installing or updating an extension. Reinstall or update this extension to apply it.')}</InfoTip></>
|
||||
: <>{t('app.extensionPermissionsDialog.installingTheseRunsPipWithThe', "Installing these runs pip with the backend's privileges (a setup.py hook is arbitrary code), so it is opt-in and off by default. Set")} <code>{envVar}=1</code> {t('app.extensionPermissionsDialog.onTheBackendThenReinstallOr', 'on the backend, then reinstall or update this extension.')}</>}
|
||||
</p>
|
||||
{requirements.path && (
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { AlertTriangle, ArrowUpCircle, MoreHorizontal } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { CatalogCard, StatusDot } from '@/components/ds';
|
||||
import { statusKind, statusLabel } from '@/components/ds/status';
|
||||
import SignatureBadge from './SignatureBadge';
|
||||
import { ExtensionCover } from './ExtensionCover';
|
||||
import { isUpdatable } from './extensionUpdates';
|
||||
|
||||
|
||||
// One installed extension as a dense catalog card: status dot, version, update
|
||||
// badge + one-click Update, everything else behind (i) and the "…" menu.
|
||||
export default function InstalledCard({
|
||||
plugin, update, busy, onToggle, onUpdate, onUninstall, onConfigure, onInspectPermissions,
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const isBusy = Boolean(busy);
|
||||
const canUpdate = isUpdatable(update);
|
||||
const isActive = plugin.status === 'active';
|
||||
const configurable = plugin.config_schema && typeof plugin.config_schema === 'object'
|
||||
&& Object.keys(plugin.config_schema).length > 0;
|
||||
const permissions = Array.isArray(plugin.permissions) ? plugin.permissions : [];
|
||||
const entry = { installKey: plugin.slug };
|
||||
|
||||
const info = (
|
||||
<div className="marketplace-info">
|
||||
{plugin.description && <p>{plugin.description}</p>}
|
||||
{plugin.error_message && <p className="marketplace-info__error">{plugin.error_message}</p>}
|
||||
<p className="marketplace-info__meta">
|
||||
{plugin.source_type === 'builtin' ? t('app.marketplace.builtIn', 'Built-in') : plugin.source_type === 'registry' ? t('app.marketplace.registry', 'Registry') : t('app.marketplace.manual', 'Manual')}{plugin.author ? ` · ${plugin.author}` : ''}
|
||||
{plugin.has_backend ? ` · ${t('app.marketplace.backend', 'Backend')}` : ''}
|
||||
{plugin.has_frontend ? ` · ${t('app.marketplace.frontend', 'Frontend')}` : ''}
|
||||
</p>
|
||||
{plugin.signature && <SignatureBadge signature={plugin.signature} />}
|
||||
{permissions.length > 0 && (
|
||||
<div className="tip-chip-row">
|
||||
{permissions.map((p) => <span key={p} className="tip-chip">{p}</span>)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<CatalogCard
|
||||
className={plugin.status === 'error' ? 'marketplace-card--error' : undefined}
|
||||
icon={<ExtensionCover base="sk-catalog-card__art" entry={entry} category={plugin.category || 'utility'} brandSize={20} />}
|
||||
title={plugin.display_name}
|
||||
sub={(
|
||||
<span className="marketplace-card__sub">
|
||||
<StatusDot kind={statusKind(plugin.status)} label={statusLabel(plugin.status)} />
|
||||
v{plugin.version}
|
||||
</span>
|
||||
)}
|
||||
tag={plugin.status === 'error' && (
|
||||
<AlertTriangle size={14} className="marketplace-card__err" aria-label={t('app.marketplace.error', 'Error')} />
|
||||
)}
|
||||
description={info}
|
||||
facts={update?.update_available && (
|
||||
<Badge variant={canUpdate ? 'info' : 'outline'} className="plugin-update-badge">
|
||||
<ArrowUpCircle aria-hidden="true" />
|
||||
{t('app.marketplace.updateTo', 'Update v{{version}}', { version: update.available_version })}
|
||||
</Badge>
|
||||
)}
|
||||
action={(
|
||||
<>
|
||||
{canUpdate && (
|
||||
<Button size="sm" disabled={isBusy} onClick={() => onUpdate(plugin.id)}>
|
||||
{busy === 'update' ? t('app.marketplace.updating', 'Updating…') : t('app.marketplace.update', 'Update')}
|
||||
</Button>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" disabled={isBusy} aria-label={t('app.marketplace.actions', 'Actions')}>
|
||||
<MoreHorizontal aria-hidden="true" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onSelect={() => onToggle(plugin)}>
|
||||
{isActive ? t('common.actions.disable', 'Disable') : t('common.actions.enable', 'Enable')}
|
||||
</DropdownMenuItem>
|
||||
{configurable && (
|
||||
<DropdownMenuItem onSelect={() => onConfigure(plugin)}>
|
||||
{t('app.marketplace.configure', 'Configure')}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onSelect={() => onInspectPermissions(plugin)}>
|
||||
{t('common.labels.permissions', 'Permissions')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={() => onUninstall(plugin)}>
|
||||
{t('common.actions.uninstall', 'Uninstall')}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
PlugZap,
|
||||
Search,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
} from 'lucide-react';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
@@ -15,6 +14,7 @@ import Modal from '@/components/Modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import SignatureBadge from './SignatureBadge';
|
||||
import DocsLink from '@/components/DocsLink';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
@@ -55,44 +55,6 @@ const SourceInput = ({
|
||||
</div>
|
||||
);
|
||||
|
||||
// Signature verdict badge for the consent card. 'verified' means the
|
||||
// release zip's ed25519 signature checked out against a publisher key pinned
|
||||
// by this panel; everything else is an honest not-verified treatment.
|
||||
const SignatureBadge = ({ signature }) => {
|
||||
const { t } = useTranslation();
|
||||
const status = signature?.status || 'unsigned';
|
||||
if (status === 'verified') {
|
||||
return (
|
||||
<Badge variant="success" className="plugin-install-consent__badge">
|
||||
<ShieldCheck aria-hidden="true" />
|
||||
{t('app.manualInstallModal.signed', 'Signed ·')} {signature.publisher || signature.key_id}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (status === 'untrusted_key') {
|
||||
return (
|
||||
<Badge variant="warning" className="plugin-install-consent__badge">
|
||||
<ShieldAlert aria-hidden="true" />
|
||||
{t('app.manualInstallModal.signedUnknownPublisher', 'Signed · unknown publisher')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (status === 'invalid') {
|
||||
return (
|
||||
<Badge variant="destructive" className="plugin-install-consent__badge">
|
||||
<ShieldAlert aria-hidden="true" />
|
||||
{t('app.manualInstallModal.signatureInvalid', 'Signature invalid')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Badge variant="warning" className="plugin-install-consent__badge">
|
||||
<ShieldAlert aria-hidden="true" />
|
||||
{t('app.manualInstallModal.unsigned', 'Unsigned')}
|
||||
</Badge>
|
||||
);
|
||||
};
|
||||
|
||||
// The consent card shown after a GitHub/zip URL is resolved but before install.
|
||||
// Presents what will be installed and what it wants — the same permissions
|
||||
// presentation as the registry detail modal — so the install is never blind.
|
||||
@@ -117,7 +79,7 @@ const PreviewConsent = ({ preview, installing, onInstall, onCancel }) => {
|
||||
{compat && <span>{compat}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<SignatureBadge signature={preview.signature} />
|
||||
<SignatureBadge signature={preview.signature} className="plugin-install-consent__badge" />
|
||||
</div>
|
||||
|
||||
{preview.description && (
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import Modal from '@/components/Modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select, SelectTrigger, SelectContent, SelectItem, SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
|
||||
// Config editor for an installed plugin (#49). Fields come from the manifest's
|
||||
// config_schema (top-level keys, or JSON-schema `properties`); values persist
|
||||
// via PUT /plugins/<id>/config and the plugin reads them on the backend via
|
||||
// plugins_sdk.config(slug).
|
||||
export const PluginConfigDialog = ({ plugin, onClose }) => {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [values, setValues] = useState(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const schema = plugin.config_schema || {};
|
||||
const fields = schema.properties && typeof schema.properties === 'object'
|
||||
? schema.properties
|
||||
: schema;
|
||||
|
||||
useEffect(() => {
|
||||
api.getPluginConfig(plugin.id)
|
||||
.then((data) => setValues(data.config || {}))
|
||||
.catch(() => setValues({}));
|
||||
}, [plugin.id]);
|
||||
|
||||
const setField = (key, v) => setValues((prev) => ({ ...prev, [key]: v }));
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.updatePluginConfig(plugin.id, values || {});
|
||||
toast.success(t('app.marketplace.extensionConfigurationSaved', 'Extension settings saved'));
|
||||
onClose();
|
||||
} catch (err) {
|
||||
toastError(toast, t('app.marketplace.failedToSaveConfiguration', "Couldn't save the settings."), err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onClose={onClose}
|
||||
title={t('app.marketplace.configure2', 'Configure {{displayname}}', { displayname: plugin.display_name })}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>{t('common.actions.cancel', 'Cancel')}</Button>
|
||||
<Button onClick={save} disabled={saving || values === null}>
|
||||
{saving ? t('common.saving', 'Saving…') : t('common.actions.save', 'Save')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{values === null ? (
|
||||
<p className="text-muted">{t('common.loading', 'Loading…')}</p>
|
||||
) : (
|
||||
<div className="plugin-config-form">
|
||||
{Object.entries(fields).map(([key, spec]) => {
|
||||
const s = spec && typeof spec === 'object' ? spec : {};
|
||||
const type = s.type || 'string';
|
||||
const isNumber = type === 'number' || type === 'integer';
|
||||
const value = values[key] ?? s.default ?? (type === 'boolean' ? false : '');
|
||||
return (
|
||||
<label key={key} className="plugin-config-form__field">
|
||||
<span className="plugin-config-form__label">{s.title || key}</span>
|
||||
{type === 'boolean' ? (
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(value)}
|
||||
onChange={(e) => setField(key, e.target.checked)}
|
||||
/>
|
||||
) : Array.isArray(s.enum) ? (
|
||||
// Radix items need non-empty string values; the
|
||||
// original (possibly numeric) enum entry is restored on change.
|
||||
<Select
|
||||
value={value === '' ? '' : String(value)}
|
||||
onValueChange={(v) => setField(
|
||||
key,
|
||||
s.enum.find((opt) => String(opt) === v) ?? v,
|
||||
)}
|
||||
>
|
||||
<SelectTrigger aria-label={s.title || key}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{s.enum.filter((opt) => String(opt) !== '').map((opt) => (
|
||||
<SelectItem key={String(opt)} value={String(opt)}>{String(opt)}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<input
|
||||
className="ui-input"
|
||||
type={isNumber ? 'number' : (s.secret ? 'password' : 'text')}
|
||||
value={value}
|
||||
onChange={(e) => setField(
|
||||
key,
|
||||
isNumber
|
||||
? (e.target.value === '' ? '' : Number(e.target.value))
|
||||
: e.target.value
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{s.description && (
|
||||
<span className="plugin-config-form__hint text-muted">{s.description}</span>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
{Object.keys(fields).length === 0 && (
|
||||
<p className="text-muted">{t('app.marketplace.thisExtensionDeclaresNoConfigurationFields', 'This extension has no settings.')}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
// Data-policy dialog for plugin uninstall. Keeping data (default) leaves the
|
||||
// extension's tables intact for a later reinstall; purging drops them.
|
||||
export const PluginUninstallDialog = ({ plugin, onCancel, onConfirm }) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onClose={onCancel}
|
||||
title={t('app.marketplace.uninstall', 'Uninstall {{displayname}}?', { displayname: plugin.display_name })}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onCancel}>{t('common.actions.cancel', 'Cancel')}</Button>
|
||||
<Button variant="outline" onClick={() => onConfirm(false)}>{t('app.marketplace.keepData', 'Keep data')}</Button>
|
||||
<Button variant="destructive" onClick={() => onConfirm(true)}>{t('app.marketplace.purgeData', 'Delete data')}</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="plugin-uninstall-dialog">
|
||||
<p>{t('app.marketplace.removingThisExtensionStopsItsRoutes', 'Uninstalling this extension stops its routes and UI contributions.')}</p>
|
||||
<p className="text-muted">
|
||||
<strong>{t('app.marketplace.keepData', 'Keep data')}</strong> {t('app.marketplace.leavesTheExtensionSDatabaseTables', 'leaves the extension\'s database tables intact so you can reinstall later.')} <strong>{t('app.marketplace.purgeData', 'Delete data')}</strong> {t('app.marketplace.permanentlyDropsTheExtensionSTables', 'permanently drops the extension\'s tables and cannot be undone.')}
|
||||
</p>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import { ShieldAlert, ShieldCheck } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
// Release-signature verdict shared by the registry detail modal and the manual
|
||||
// install consent card. `signature.status`: 'verified' (ed25519 signature
|
||||
// checked against a publisher key this panel pins), 'untrusted_key',
|
||||
// 'invalid', or anything else = unsigned.
|
||||
export default function SignatureBadge({ signature, className }) {
|
||||
const { t } = useTranslation();
|
||||
const status = signature?.status || 'unsigned';
|
||||
const signer = signature?.publisher || signature?.key_id;
|
||||
if (status === 'verified') {
|
||||
return (
|
||||
<Badge
|
||||
variant="success"
|
||||
className={className}
|
||||
title={t('app.signatureBadge.verifiedHint', 'Release zip is signed; the panel verifies the ed25519 signature at install')}
|
||||
>
|
||||
<ShieldCheck aria-hidden="true" />
|
||||
{t('app.signatureBadge.signed', 'Signed')}{signer ? ` · ${signer}` : ''}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (status === 'untrusted_key') {
|
||||
return (
|
||||
<Badge
|
||||
variant="warning"
|
||||
className={className}
|
||||
title={signer ? t('app.signatureBadge.unknownSignerHint', "Signed with publisher key '{{key}}', which this panel does not pin", { key: signer }) : undefined}
|
||||
>
|
||||
<ShieldAlert aria-hidden="true" />
|
||||
{t('app.signatureBadge.unknownSigner', 'Unknown signer')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (status === 'invalid') {
|
||||
return (
|
||||
<Badge variant="destructive" className={className}>
|
||||
<ShieldAlert aria-hidden="true" />
|
||||
{t('app.signatureBadge.invalid', 'Signature invalid')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Badge
|
||||
variant="warning"
|
||||
className={className}
|
||||
title={t('app.signatureBadge.unsignedHint', 'This release carries no publisher signature')}
|
||||
>
|
||||
<ShieldAlert aria-hidden="true" />
|
||||
{t('app.signatureBadge.unsigned', 'Unsigned')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { ArrowUpCircle, Loader2 } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Compact strip shown on every Extensions view while updates are pending.
|
||||
export default function UpdatesBanner({ count, readyCount, progress, onUpdateAll }) {
|
||||
const { t } = useTranslation();
|
||||
if (!count) return null;
|
||||
const running = Boolean(progress);
|
||||
return (
|
||||
<div className="marketplace-banner" role="status">
|
||||
<ArrowUpCircle size={18} aria-hidden="true" className="marketplace-banner__icon" />
|
||||
<span className="marketplace-banner__text">
|
||||
{t('app.marketplace.updatesAvailable', { count, defaultValue_one: '1 update available', defaultValue_other: '{{count}} updates available' })}
|
||||
</span>
|
||||
<InfoTip title={t('app.marketplace.updates', 'Updates')}>
|
||||
{t('app.marketplace.updatesInfo', 'Updates come from the registry and bundled sources. Update all skips anything that needs review or fails; update those one by one.')}
|
||||
</InfoTip>
|
||||
{readyCount > 0 && (
|
||||
<Button size="sm" className="marketplace-banner__action" disabled={running} onClick={onUpdateAll}>
|
||||
{running
|
||||
? <Loader2 className="animate-spin" aria-hidden="true" />
|
||||
: <ArrowUpCircle aria-hidden="true" />}
|
||||
{running
|
||||
? `${progress.done}/${progress.total}`
|
||||
: t('app.marketplace.updateAll', 'Update all')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { ArrowUpCircle, CheckCircle2, Info, RefreshCw } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { CatalogCard, CatalogGrid } from '@/components/ds';
|
||||
import EmptyState from '../EmptyState';
|
||||
import ErrorState from '../ErrorState';
|
||||
import PageLoader from '../PageLoader';
|
||||
import { ExtensionCover } from './ExtensionCover';
|
||||
import { isUpdatable, minutesSince, versionLabel } from './extensionUpdates';
|
||||
|
||||
function CheckedAgo({ checkedAt }) {
|
||||
const { t } = useTranslation();
|
||||
const min = minutesSince(checkedAt);
|
||||
if (min == null) return null;
|
||||
return (
|
||||
<span className="marketplace-updates__checked">
|
||||
{min < 1
|
||||
? t('app.marketplace.checkedJustNow', 'Checked just now')
|
||||
: t('app.marketplace.checkedMinAgo', 'Checked {{n}} min ago', { n: min })}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// Updates tab body: only the cards with a newer version, plus "Check now".
|
||||
export default function UpdatesView({ store, categories, busyId, onUpdate }) {
|
||||
const { t } = useTranslation();
|
||||
const { updates, loading, error, loaded, checkedAt, refresh } = store;
|
||||
const pending = updates.filter((u) => u.update_available);
|
||||
|
||||
const checkNow = (
|
||||
<div className="marketplace-updates__bar">
|
||||
<Button variant="outline" size="sm" disabled={loading} onClick={() => refresh({ force: true })}>
|
||||
<RefreshCw className={loading ? 'animate-spin' : undefined} aria-hidden="true" />
|
||||
{t('app.marketplace.checkNow', 'Check now')}
|
||||
</Button>
|
||||
<CheckedAgo checkedAt={checkedAt} />
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!loaded) return <PageLoader />;
|
||||
if (error && pending.length === 0) {
|
||||
return (
|
||||
<ErrorState
|
||||
title={t('app.marketplace.couldntCheckUpdates', "Couldn't check for updates.")}
|
||||
error={error}
|
||||
onRetry={() => refresh({ force: true })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (pending.length === 0) {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={CheckCircle2}
|
||||
title={t('app.marketplace.allUpToDate', 'All extensions are up to date')}
|
||||
action={checkNow}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{checkNow}
|
||||
<CatalogGrid>
|
||||
{pending.map((u) => {
|
||||
const ok = isUpdatable(u);
|
||||
const reason = !ok
|
||||
? (u.incompatible_reason || t('app.marketplace.panelVersionIsTooOldFor', 'Panel version is too old for this update'))
|
||||
: u.requires_ack
|
||||
? t('app.marketplace.needsReview', 'Needs review before updating')
|
||||
: null;
|
||||
return (
|
||||
<CatalogCard
|
||||
key={u.slug}
|
||||
icon={<ExtensionCover base="sk-catalog-card__art" entry={{ installKey: u.slug }} category={categories[u.slug] || 'utility'} brandSize={20} />}
|
||||
title={u.display_name || u.slug}
|
||||
sub={versionLabel(u)}
|
||||
description={reason}
|
||||
facts={reason && (
|
||||
<Badge variant="outline"><Info aria-hidden="true" />{ok ? t('app.marketplace.review', 'Review') : t('app.marketplace.incompatible', 'Incompatible')}</Badge>
|
||||
)}
|
||||
action={ok && (
|
||||
<Button size="sm" disabled={busyId === u.plugin_id} onClick={() => onUpdate(u.plugin_id)}>
|
||||
<ArrowUpCircle aria-hidden="true" />
|
||||
{busyId === u.plugin_id ? t('app.marketplace.updating', 'Updating…') : t('app.marketplace.update', 'Update')}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</CatalogGrid>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
countUpdatable, indexUpdates, isUpdatable, minutesSince, partitionUpdates, versionLabel,
|
||||
} from '../extensionUpdates.js';
|
||||
|
||||
const u = (over) => ({
|
||||
plugin_id: 1, slug: 'a', installed_version: '1.0.0', available_version: '1.1.0',
|
||||
update_available: true, compatible: true, requires_ack: false, ...over,
|
||||
});
|
||||
|
||||
test('only compatible updates count', () => {
|
||||
const list = [u(), u({ plugin_id: 2, compatible: false }), u({ plugin_id: 3, update_available: false })];
|
||||
assert.equal(countUpdatable(list), 1);
|
||||
assert.equal(isUpdatable(list[1]), false);
|
||||
assert.equal(countUpdatable(undefined), 0);
|
||||
});
|
||||
|
||||
test('partition splits ready / review / incompatible and drops non-updates', () => {
|
||||
const p = partitionUpdates([
|
||||
u({ plugin_id: 1 }),
|
||||
u({ plugin_id: 2, requires_ack: true }),
|
||||
u({ plugin_id: 3, compatible: false }),
|
||||
u({ plugin_id: 4, update_available: false }),
|
||||
]);
|
||||
assert.deepEqual(p.ready.map((x) => x.plugin_id), [1]);
|
||||
assert.deepEqual(p.review.map((x) => x.plugin_id), [2]);
|
||||
assert.deepEqual(p.incompatible.map((x) => x.plugin_id), [3]);
|
||||
});
|
||||
|
||||
test('version label and index', () => {
|
||||
assert.equal(versionLabel(u()), 'v1.0.0 → v1.1.0');
|
||||
const idx = indexUpdates([u({ plugin_id: 7, slug: 'x' })]);
|
||||
assert.equal(idx.get('7'), idx.get('x'));
|
||||
});
|
||||
|
||||
test('minutesSince', () => {
|
||||
const now = Date.parse('2026-01-01T00:10:00Z');
|
||||
assert.equal(minutesSince('2026-01-01T00:00:00Z', now), 10);
|
||||
assert.equal(minutesSince('2026-01-01T00:20:00Z', now), 0);
|
||||
assert.equal(minutesSince('nope', now), null);
|
||||
assert.equal(minutesSince(null, now), null);
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
Activity, Gamepad2, LayoutGrid, Package, Plug, ServerCog, ShieldCheck, Sparkles,
|
||||
} from 'lucide-react';
|
||||
import { t } from '@/i18n/t';
|
||||
|
||||
// Catalog model: normalises registry + built-in entries into one card shape.
|
||||
|
||||
export const CATEGORIES = ['ai', 'games', 'monitoring', 'security', 'deployment', 'integration', 'ui', 'utility'];
|
||||
|
||||
export const CATEGORY_ICONS = {
|
||||
ai: Sparkles,
|
||||
games: Gamepad2,
|
||||
monitoring: Activity,
|
||||
security: ShieldCheck,
|
||||
deployment: ServerCog,
|
||||
integration: Plug,
|
||||
ui: LayoutGrid,
|
||||
utility: Package,
|
||||
};
|
||||
|
||||
export const titleCase = (value = '') => {
|
||||
const cleaned = String(value || 'utility').replace(/[-_]/g, ' ');
|
||||
return cleaned
|
||||
.split(' ')
|
||||
.filter(Boolean)
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
||||
.join(' ');
|
||||
};
|
||||
|
||||
export const getCategoryIcon = (category) => CATEGORY_ICONS[category] || Package;
|
||||
|
||||
// A first-party ("by ServerKit") entry is one authored by ServerKit or one whose
|
||||
// manifest explicitly opts in via `first_party`. Case-insensitive on author.
|
||||
export const isFirstParty = (author, source = {}) => {
|
||||
if (source && source.first_party) return true;
|
||||
return String(author || '').trim().toLowerCase() === 'serverkit';
|
||||
};
|
||||
|
||||
// Union of categories actually present across the merged catalog, ordered by the
|
||||
// canonical CATEGORIES list first, then any extras alphabetically (stable, deduped).
|
||||
export const deriveCatalogCategories = (entries) => {
|
||||
const present = new Set(entries.map((entry) => entry.category || 'utility'));
|
||||
const known = CATEGORIES.filter((item) => present.has(item));
|
||||
const extra = [...present].filter((item) => !CATEGORIES.includes(item)).sort();
|
||||
return [...known, ...extra];
|
||||
};
|
||||
|
||||
export const getRegistryCatalogEntry = (entry) => ({
|
||||
key: `registry:${entry.slug}`,
|
||||
source: 'registry',
|
||||
sourceLabel: 'Registry',
|
||||
sourceDetail: 'Remote registry package',
|
||||
installKey: entry.slug,
|
||||
displayName: entry.display_name || entry.slug,
|
||||
description: entry.description || t('app.marketplace.noDescriptionProvided', 'No description provided.'),
|
||||
category: entry.category || 'utility',
|
||||
version: entry.version || '0.0.0',
|
||||
author: entry.author,
|
||||
firstParty: isFirstParty(entry.author, entry),
|
||||
trust: entry.trust || 'unreviewed',
|
||||
review: entry.review || null,
|
||||
// Release-signature state from the index: `signed` means the
|
||||
// entry carries an ed25519 signature the panel verifies at install;
|
||||
// `publisherTrusted` means the named key is pinned by this panel.
|
||||
signed: Boolean(entry.signature),
|
||||
publisherTrusted: Boolean(entry.publisher_trusted),
|
||||
publisherKeyId: entry.publisher_key_id || null,
|
||||
icon: entry.icon || null,
|
||||
logo: entry.logo || null,
|
||||
repo: entry.repo || entry.homepage || null,
|
||||
screenshots: Array.isArray(entry.screenshots) ? entry.screenshots : [],
|
||||
permissions: Array.isArray(entry.permissions) ? entry.permissions : [],
|
||||
configSchema: entry.config_schema && typeof entry.config_schema === 'object' ? entry.config_schema : null,
|
||||
extensionType: 'registry',
|
||||
installed: Boolean(entry.installed),
|
||||
status: entry.status,
|
||||
featured: Boolean(entry.featured),
|
||||
featureScore: Number(entry.feature_score) || 0,
|
||||
});
|
||||
|
||||
// Source badge tint: built-in is 'warning', registry is 'info'.
|
||||
export const sourceBadgeVariant = (source) => {
|
||||
if (source === 'local') return 'warning';
|
||||
if (source === 'registry') return 'info';
|
||||
return 'outline';
|
||||
};
|
||||
|
||||
|
||||
export const getLocalCatalogEntry = (builtin) => {
|
||||
const manifest = builtin.manifest || {};
|
||||
|
||||
return {
|
||||
key: `local:${builtin.slug}`,
|
||||
source: 'local',
|
||||
sourceLabel: 'Built-in',
|
||||
sourceDetail: 'Bundled with ServerKit',
|
||||
installKey: builtin.slug,
|
||||
displayName: manifest.display_name || builtin.slug,
|
||||
description: manifest.description || t('app.marketplace.bundledExtension', 'Bundled extension.'),
|
||||
category: manifest.category || 'utility',
|
||||
version: manifest.version || '0.0.0',
|
||||
author: manifest.author,
|
||||
firstParty: isFirstParty(manifest.author, manifest),
|
||||
icon: manifest.icon || null,
|
||||
logo: manifest.logo || null,
|
||||
screenshots: Array.isArray(manifest.screenshots) ? manifest.screenshots : [],
|
||||
permissions: Array.isArray(manifest.permissions) ? manifest.permissions : [],
|
||||
configSchema: manifest.config_schema && typeof manifest.config_schema === 'object' ? manifest.config_schema : null,
|
||||
extensionType: 'built-in',
|
||||
installed: Boolean(builtin.installed),
|
||||
status: builtin.status,
|
||||
featured: Boolean(manifest.featured),
|
||||
featureScore: Number(manifest.feature_score) || 0,
|
||||
};
|
||||
};
|
||||
|
||||
export const catalogEntryMatches = (entry, search, category) => {
|
||||
if (category && entry.category !== category) return false;
|
||||
|
||||
const query = search.trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
|
||||
return [
|
||||
entry.displayName,
|
||||
entry.description,
|
||||
entry.category,
|
||||
entry.author,
|
||||
entry.sourceLabel,
|
||||
].some((value) => String(value || '').toLowerCase().includes(query));
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
// Pure helpers over the GET /plugins/updates payload (no React, no DOM).
|
||||
|
||||
// An update the operator can act on: newer version exists AND this panel can run it.
|
||||
export const isUpdatable = (u) => Boolean(u && u.update_available && u.compatible !== false);
|
||||
|
||||
export const countUpdatable = (updates) => (updates || []).filter(isUpdatable).length;
|
||||
|
||||
// ready: one-click safe (Update all runs these); review: needs the operator's
|
||||
// acknowledgment, so only ever updated one at a time; incompatible: newer
|
||||
// version exists but can't run here. Entries without an update are dropped.
|
||||
export function partitionUpdates(updates) {
|
||||
const out = { ready: [], review: [], incompatible: [] };
|
||||
for (const u of updates || []) {
|
||||
if (!u || !u.update_available) continue;
|
||||
if (u.compatible === false) out.incompatible.push(u);
|
||||
else if (u.requires_ack) out.review.push(u);
|
||||
else out.ready.push(u);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const versionLabel = (u) => `v${u.installed_version} → v${u.available_version}`;
|
||||
|
||||
// Lookup by plugin id and slug so a caller can match whichever it has.
|
||||
export function indexUpdates(updates) {
|
||||
const map = new Map();
|
||||
for (const u of updates || []) {
|
||||
if (u.plugin_id != null) map.set(String(u.plugin_id), u);
|
||||
if (u.slug) map.set(u.slug, u);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// Whole minutes since `checkedAt` (ISO string); null when unknown.
|
||||
export function minutesSince(checkedAt, now = Date.now()) {
|
||||
const ms = Date.parse(checkedAt);
|
||||
return Number.isNaN(ms) ? null : Math.max(0, Math.floor((now - ms) / 60000));
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Puzzle, PackageCheck, Download, ChefHat } from 'lucide-react';
|
||||
import { Puzzle, PackageCheck, Download, ChefHat, ArrowUpCircle } from 'lucide-react';
|
||||
|
||||
// Shared sub-nav for the Extensions page group (Extensions / Installed /
|
||||
// Recipes / Downloads). Rendered in each page's <PageTopbar tabs={MARKET_TABS}> �?" the
|
||||
// top-bar layout replaces the old sidebar sub-menu (see docs/REDESIGN_MAP.md
|
||||
// A6 dec. 3). Installed is a real route (/extensions/installed) so it deep-links.
|
||||
// Shared sub-nav for the Extensions page group (Library / Installed / Updates /
|
||||
// Recipes / Downloads). Rendered by TabGroupLayout in the shared top bar. Installed
|
||||
// and Updates are real routes so they deep-link. `badge: 'updates'` is resolved
|
||||
// to a count by TabGroupLayout; `iconOnlyNarrow` shows only the active tab's label on phones so
|
||||
// every tab (and the Updates badge) fits without falling into "More".
|
||||
export const MARKET_TABS = [
|
||||
{ to: '/extensions', labelKey: 'common.labels.extensions', label: 'Extensions', end: true, icon: <Puzzle size={15} /> },
|
||||
{ to: '/extensions/installed', labelKey: 'app.marketTabs.installed', label: 'Installed', icon: <PackageCheck size={15} /> },
|
||||
{ to: '/extensions/recipes', labelKey: 'app.marketTabs.recipes', label: 'Recipes', icon: <ChefHat size={15} /> },
|
||||
{ to: '/downloads', labelKey: 'app.marketTabs.downloads', label: 'Downloads', icon: <Download size={15} /> },
|
||||
{ to: '/extensions', labelKey: 'app.marketTabs.library', label: 'Library', end: true, icon: <Puzzle size={15} />, iconOnlyNarrow: true },
|
||||
{ to: '/extensions/installed', labelKey: 'app.marketTabs.installed', label: 'Installed', icon: <PackageCheck size={15} />, iconOnlyNarrow: true },
|
||||
{ to: '/extensions/updates', labelKey: 'app.marketTabs.updates', label: 'Updates', icon: <ArrowUpCircle size={15} />, badge: 'updates', iconOnlyNarrow: true },
|
||||
{ to: '/extensions/recipes', labelKey: 'app.marketTabs.recipes', label: 'Recipes', icon: <ChefHat size={15} />, iconOnlyNarrow: true },
|
||||
{ to: '/downloads', labelKey: 'app.marketTabs.downloads', label: 'Downloads', icon: <Download size={15} />, iconOnlyNarrow: true },
|
||||
];
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useState } from 'react';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import { t } from '@/i18n/t';
|
||||
import { partitionUpdates } from './extensionUpdates';
|
||||
|
||||
// "Update all": sequentially applies every ready (compatible, no-ack) update.
|
||||
// Failures are skipped and counted; entries needing review are NEVER
|
||||
// acknowledged here — they are reported so the operator updates them one by one.
|
||||
export function useUpdateAll(updates, onDone) {
|
||||
const toast = useToast();
|
||||
const [progress, setProgress] = useState(null); // { done, total } while running
|
||||
const { ready, review } = partitionUpdates(updates);
|
||||
|
||||
const run = async () => {
|
||||
if (progress || ready.length === 0) return;
|
||||
const batch = ready;
|
||||
let ok = 0;
|
||||
let failed = 0;
|
||||
let needReview = review.length;
|
||||
setProgress({ done: 0, total: batch.length });
|
||||
for (let i = 0; i < batch.length; i += 1) {
|
||||
try {
|
||||
await api.updatePlugin(batch[i].plugin_id);
|
||||
ok += 1;
|
||||
} catch (err) {
|
||||
if (err.status === 409 && err.data?.requires_acknowledgment) needReview += 1;
|
||||
else failed += 1;
|
||||
}
|
||||
setProgress({ done: i + 1, total: batch.length });
|
||||
}
|
||||
setProgress(null);
|
||||
await onDone();
|
||||
const msg = t('app.marketplace.updateAllSummary', '{{ok}} updated · {{review}} need review · {{failed}} failed', { ok, review: needReview, failed });
|
||||
if (failed || needReview) toast.warning(msg); else toast.success(msg);
|
||||
};
|
||||
|
||||
return { run, progress, readyCount: ready.length, reviewCount: review.length };
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { useToast } from '@/contexts/useToast.js';
|
||||
import { useOperations } from '@/contexts/OperationsContext';
|
||||
import formatBytes from '@/utils/formatBytes';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
/**
|
||||
* Curated "safe" disk reclaim. Shows what a fresh measurement says can be
|
||||
@@ -95,7 +96,7 @@ const DiskReclaimModal = ({ open, onClose }) => {
|
||||
)}
|
||||
>
|
||||
<p className="sk-modal__subtitle">
|
||||
{t('app.diskReclaim.onlyReviewedSafeCandidatesAreOffered', 'Only reviewed-safe cleanup is offered: upgrade snapshots beyond the newest one, abandoned update staging, oversized logs, package caches, old journal entries and Docker build cache. Nothing here touches your services or databases.')}
|
||||
{t('app.diskReclaim.onlyReviewedSafeCandidatesAreOfferedShort', 'Only reviewed-safe cleanup is offered.')} <InfoTip>{t('app.diskReclaim.onlyReviewedSafeCandidatesAreOffered', 'Only reviewed-safe cleanup is offered: upgrade snapshots beyond the newest one, abandoned update staging, oversized logs, package caches, old journal entries and Docker build cache. Nothing here touches your services or databases.')}</InfoTip>
|
||||
</p>
|
||||
|
||||
{loading ? (
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useOperations } from '@/contexts/OperationsContext';
|
||||
import DiskReclaimModal from './DiskReclaimModal';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import { formatDateTime } from '@/utils/intl';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
|
||||
// The fleet sweep fans out across agents over the network, so it is a job
|
||||
@@ -249,7 +250,7 @@ const DoctorPanel = () => {
|
||||
</div>
|
||||
|
||||
<p className="doctor-panel__blurb">
|
||||
{t('app.doctorPanel.oneSweepAcrossManagedConfigurationDrift', 'One sweep across managed configuration drift, core services, certificates, disk headroom and the database. Nothing is repaired automatically; every fix is a button you press.')}
|
||||
{t('app.doctorPanel.sweepShort', 'One sweep, no automatic repairs.')} <InfoTip>{t('app.doctorPanel.oneSweepAcrossManagedConfigurationDrift', 'One sweep across managed configuration drift, core services, certificates, disk headroom and the database. Nothing is repaired automatically; every fix is a button you press.')}</InfoTip>
|
||||
{report?.ran_at && <span className="doctor-panel__ranat"> {t('app.doctorPanel.lastRun', 'Last run')} {formatRanAt(report.ran_at)}.</span>}
|
||||
</p>
|
||||
|
||||
@@ -304,7 +305,7 @@ const DoctorPanel = () => {
|
||||
</div>
|
||||
|
||||
<p className="doctor-panel__blurb">
|
||||
{t('app.doctorPanel.theSameHealthSweepAcrossEvery', 'The same health sweep across every paired server. It runs as a background job because it talks to each agent over the network; a server that is offline keeps its last known findings instead of dropping out.')}
|
||||
{t('app.doctorPanel.fleetSweepShort', 'Health sweep across every paired server.')} <InfoTip>{t('app.doctorPanel.theSameHealthSweepAcrossEvery', 'The same health sweep across every paired server. It runs as a background job because it talks to each agent over the network; a server that is offline keeps its last known findings instead of dropping out.')}</InfoTip>
|
||||
{fleet?.ran_at && <span className="doctor-panel__ranat"> {t('app.doctorPanel.lastSweep', 'Last sweep')} {formatRanAt(fleet.ran_at)}.</span>}
|
||||
</p>
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { monitorStateOf } from './monitorShared';
|
||||
import { usePolling } from '../../hooks/usePolling';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
const POLL_MS = 15000;
|
||||
const FEED_LIMIT = 9;
|
||||
@@ -85,7 +86,7 @@ export default function MonitorsSummary({ refreshKey = 0 }) {
|
||||
</Button>
|
||||
</div>
|
||||
<p className="mon-panel-hint">
|
||||
{t('app.monitorsSummary.everythingBelowDescribesTheMachinesServerkit', 'Everything below describes the servers ServerKit runs on. Add a monitor to watch a website, an API endpoint, a database port or a WordPress site and get an incident when it stops answering.')}
|
||||
{t('app.monitorsSummary.everythingBelowDescribesTheMachinesServerkitShort', 'Below: the servers ServerKit runs on.')} <InfoTip>{t('app.monitorsSummary.everythingBelowDescribesTheMachinesServerkit', 'Everything below describes the servers ServerKit runs on. Add a monitor to watch a website, an API endpoint, a database port or a WordPress site and get an incident when it stops answering.')}</InfoTip>
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { classifyAlertMetric, describeAlert, formatReading } from '../alertCopy.js';
|
||||
|
||||
// Minimal i18next stand-in: default string + {{var}} interpolation.
|
||||
const t = (_key, fallback, vars = {}) => fallback.replace(/{{(\w+)}}/g, (_, k) => vars[k]);
|
||||
const text = (alert) => JSON.stringify(describeAlert(t, alert));
|
||||
|
||||
test('classifies health signals apart from threshold metrics', () => {
|
||||
assert.deepEqual(classifyAlertMetric('offline'), { kind: 'offline' });
|
||||
assert.deepEqual(classifyAlertMetric('svc:mysql'), { kind: 'service', service: 'mysql' });
|
||||
assert.deepEqual(classifyAlertMetric('cpu'), { kind: 'threshold' });
|
||||
});
|
||||
|
||||
test('offline and service alerts never claim a limit or render placeholders', () => {
|
||||
const offline = describeAlert(t, { metric: 'offline', value: null, threshold: null, subject: 'web-1' });
|
||||
assert.equal(offline.title, 'web-1 is offline');
|
||||
const service = describeAlert(t, { metric: 'svc:mysql', value: null, threshold: null, subject: 'web-1' });
|
||||
assert.equal(service.title, 'mysql is down on web-1');
|
||||
assert.equal(service.detail, 'mysql is not running');
|
||||
for (const s of [text({ metric: 'offline', subject: 'x' }), text({ metric: 'svc:a', subject: 'x' })]) {
|
||||
assert.doesNotMatch(s, /null|undefined|—|over limit/);
|
||||
}
|
||||
});
|
||||
|
||||
test('threshold alerts include the reading when present and omit it when not', () => {
|
||||
const full = describeAlert(t, { metric: 'cpu', value: 93.456, threshold: 90, subject: 'db' });
|
||||
assert.equal(full.title, 'CPU % over limit on db');
|
||||
assert.equal(full.detail, 'CPU % 93.5 of 90 limit');
|
||||
const bare = describeAlert(t, { metric: 'disk', value: null, threshold: null, subject: 'db' });
|
||||
assert.equal(bare.detail, 'Disk %');
|
||||
assert.doesNotMatch(text({ metric: 'memory', subject: 'db' }), /null|undefined|—/);
|
||||
});
|
||||
|
||||
test('unknown or missing metric falls back to a neutral title', () => {
|
||||
assert.equal(describeAlert(t, { metric: undefined, subject: 'db' }).title, 'Alert on db');
|
||||
assert.equal(formatReading('x'), null);
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { METRIC_LABELS } from './fleetMetrics.js';
|
||||
|
||||
// Plain-language title/detail for a metric alert. The backend's `metric` is
|
||||
// either a threshold metric (cpu, memory, disk, network_*) or a health signal
|
||||
// with no reading at all: `offline` (server stopped reporting) and
|
||||
// `svc:<name>` (a watched service is down). Only the first kind has a value and
|
||||
// limit, so only it may talk about going "over limit".
|
||||
const SERVICE_PREFIX = 'svc:';
|
||||
|
||||
export function classifyAlertMetric(metric) {
|
||||
if (metric === 'offline') return { kind: 'offline' };
|
||||
if (typeof metric === 'string' && metric.startsWith(SERVICE_PREFIX)) {
|
||||
return { kind: 'service', service: metric.slice(SERVICE_PREFIX.length) || null };
|
||||
}
|
||||
return { kind: 'threshold' };
|
||||
}
|
||||
|
||||
export function formatReading(value, digits = 1) {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value.toFixed(digits) : null;
|
||||
}
|
||||
|
||||
export function metricLabel(metric) {
|
||||
return METRIC_LABELS[metric] || metric || null;
|
||||
}
|
||||
|
||||
// `t` is i18next's translate function (injected so this stays testable).
|
||||
export function describeAlert(t, { metric, value, threshold, subject }) {
|
||||
const { kind, service } = classifyAlertMetric(metric);
|
||||
if (kind === 'offline') {
|
||||
return {
|
||||
title: t('app.alertCopy.offlineTitle', '{{subject}} is offline', { subject }),
|
||||
detail: t('app.alertCopy.offlineDetail', 'Stopped reporting'),
|
||||
};
|
||||
}
|
||||
if (kind === 'service') {
|
||||
return service
|
||||
? {
|
||||
title: t('app.alertCopy.serviceDownTitle', '{{service}} is down on {{subject}}', { service, subject }),
|
||||
detail: t('app.alertCopy.serviceDownDetail', '{{service}} is not running', { service }),
|
||||
}
|
||||
: {
|
||||
title: t('app.alertCopy.serviceDownAnyTitle', 'A service is down on {{subject}}', { subject }),
|
||||
detail: t('app.alertCopy.serviceDownAnyDetail', 'Service not running'),
|
||||
};
|
||||
}
|
||||
const label = metricLabel(metric);
|
||||
const reading = formatReading(value);
|
||||
const limit = formatReading(threshold, 0);
|
||||
if (!label) {
|
||||
return { title: t('app.alertCopy.genericTitle', 'Alert on {{subject}}', { subject }), detail: '' };
|
||||
}
|
||||
let detail = label;
|
||||
if (reading && limit) {
|
||||
detail = t('app.alertCopy.readingOfLimit', '{{metric}} {{reading}} of {{limit}} limit', { metric: label, reading, limit });
|
||||
} else if (reading) {
|
||||
detail = t('app.alertCopy.readingOnly', '{{metric}} {{reading}}', { metric: label, reading });
|
||||
}
|
||||
return {
|
||||
title: t('app.alertCopy.overLimitTitle', '{{metric}} over limit on {{subject}}', { metric: label, subject }),
|
||||
detail,
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
const DEFAULT_TEMPLATE = 'pr-{pr_number}.{app_domain}';
|
||||
|
||||
@@ -154,7 +155,7 @@ const PreviewList = ({ appId }) => {
|
||||
<div>
|
||||
<h3>{t('app.previewList.prPreviewEnvironments', 'PR preview environments')}</h3>
|
||||
<p className="preview-settings__hint">
|
||||
{t('app.previewList.genericSupport', 'Generic previews support local Git-backed Dockerfile and container-buildpack apps with nginx. Compose, remote targets and host-command builds are not supported. Configure preview DNS to point at this server.')}
|
||||
{t('app.previewList.genericSupportShort', 'Git-backed Dockerfile and buildpack apps.')} <InfoTip>{t('app.previewList.genericSupport', 'Generic previews support local Git-backed Dockerfile and container-buildpack apps with nginx. Compose, remote targets and host-command builds are not supported. Configure preview DNS to point at this server.')}</InfoTip>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useState, useEffect, useMemo, useId } from 'react';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import { useConfirm } from '@/hooks/useConfirm';
|
||||
@@ -447,7 +448,8 @@ const FirewallTab = () => {
|
||||
|
||||
return (
|
||||
<div className="firewall-tab">
|
||||
{partialError && <ErrorState compact error={partialError} onRetry={loadData} />}
|
||||
{/* With no firewall installed the rules/blocked reads fail as a side effect; the call to action below already says so. */}
|
||||
{partialError && status?.any_installed && <ErrorState compact error={partialError} onRetry={loadData} />}
|
||||
{!status?.any_installed ? (
|
||||
<EmptyState
|
||||
icon={Shield}
|
||||
@@ -684,7 +686,8 @@ const FirewallTab = () => {
|
||||
)}
|
||||
</InfoList>
|
||||
<p className="sec-hint">
|
||||
{t('app.firewallTab.stopsAppContainersFromReachingThe', 'Stops service containers from reaching the cloud metadata endpoint, preventing SSRF attacks from stealing instance credentials.')}
|
||||
{t('app.firewallTab.blocksMetadataAccess', 'Blocks container access to cloud metadata.')}
|
||||
<InfoTip>{t('app.firewallTab.stopsAppContainersFromReachingThe', 'Stops service containers from reaching the cloud metadata endpoint, preventing SSRF attacks from stealing instance credentials.')}</InfoTip>
|
||||
</p>
|
||||
</SharedCardContent>
|
||||
</SharedCard>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import { useConfirm } from '../../hooks/useConfirm';
|
||||
@@ -435,8 +436,9 @@ const CloudflaredTab = ({ serverId, serverStatus }) => {
|
||||
) : (
|
||||
<div className="cloudflared-login-prompt">
|
||||
<p>
|
||||
{t('app.cloudflaredTab.cloudflareNeedsYouToAuthoriseThis', 'Cloudflare needs you to authorise this agent once. Click')}{' '}
|
||||
<strong>{t('app.cloudflaredTab.login', 'Login')}</strong> {t('app.cloudflaredTab.belowWeLlStartTheOauth', "below. We'll start the OAuth flow on the server and surface the URL for you to open in your browser. Once you authorise, the agent picks up the cert.pem automatically and the rest of this tab unlocks.")}
|
||||
{t('app.cloudflaredTab.authoriseOnce', 'Authorise this agent with Cloudflare once.')}{' '}
|
||||
<InfoTip>{t('app.cloudflaredTab.cloudflareNeedsYouToAuthoriseThis', 'Cloudflare needs you to authorise this agent once. Click')}{' '}
|
||||
<strong>{t('app.cloudflaredTab.login', 'Login')}</strong> {t('app.cloudflaredTab.belowWeLlStartTheOauth', "below. We'll start the OAuth flow on the server and surface the URL for you to open in your browser. Once you authorise, the agent picks up the cert.pem automatically and the rest of this tab unlocks.")}</InfoTip>
|
||||
</p>
|
||||
<Button onClick={handleStartLogin}>{t('app.cloudflaredTab.loginToCloudflare', 'Login to Cloudflare')}</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useState, useEffect } from 'react';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import { useConfirm } from '../../hooks/useConfirm';
|
||||
@@ -148,7 +149,7 @@ const ServerDockerTab = ({ serverId, serverStatus, server }) => {
|
||||
<EmptyState
|
||||
icon={Container}
|
||||
title={t('app.serverDockerTab.dockerNotReachableFromThisAgent', 'Docker not reachable from this agent')}
|
||||
description={t('app.serverDockerTab.theAgentConnectedButCouldNot', 'The agent connected but could not talk to a Docker daemon. Make sure Docker is running on the host (and the agent user is in the docker group on Linux), then click Refresh on the Overview tab to re-probe capabilities.')}
|
||||
description={<>{t('app.serverDockerTab.agentCannotReachDocker', 'Agent cannot reach a Docker daemon.')} <InfoTip>{t('app.serverDockerTab.theAgentConnectedButCouldNot', 'The agent connected but could not talk to a Docker daemon. Make sure Docker is running on the host (and the agent user is in the docker group on Linux), then click Refresh on the Overview tab to re-probe capabilities.')}</InfoTip></>}
|
||||
/>
|
||||
<ul className="docker-empty-state__causes">
|
||||
<li>{t('app.serverDockerTab.dockerDesktopDockerdIsNotRunning', 'Docker Desktop / dockerd is not running on the host')}</li>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import FavoriteStar from '@/components/FavoriteStar';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import { StatusDot } from '../ds';
|
||||
import { serverStatusKind } from './serverDetailData';
|
||||
|
||||
// Header meta: [status dot] [(i) with endpoint + ID] [star]. Everything the
|
||||
// header used to spell out lives behind the (i).
|
||||
export default function ServerHeaderMeta({ server }) {
|
||||
const { t } = useTranslation();
|
||||
const status = server.status || 'pending';
|
||||
const endpoint = server.hostname || server.ip_address || t('app.serverDetail.noEndpointConfigured', 'No endpoint configured');
|
||||
return (
|
||||
<>
|
||||
<StatusDot kind={serverStatusKind(status)} label={status.charAt(0).toUpperCase() + status.slice(1)} />
|
||||
<InfoTip size="md" title={t('app.serverDetail.details', 'Server details')}>
|
||||
<dl className="server-detail-info">
|
||||
<dt>{t('common.labels.status', 'Status')}</dt>
|
||||
<dd>{status}</dd>
|
||||
<dt>{t('app.serverDetail.endpoint', 'Endpoint')}</dt>
|
||||
<dd>{endpoint}</dd>
|
||||
<dt>{t('app.serverDetail.serverId', 'ID')}</dt>
|
||||
<dd className="server-detail-info__id">
|
||||
<code>{server.id}</code>
|
||||
<CopyButton value={String(server.id)} label={t('app.serverDetail.copyId', 'Copy ID')} />
|
||||
</dd>
|
||||
</dl>
|
||||
</InfoTip>
|
||||
<FavoriteStar type="server" id={server.id} path={`/servers/${server.id}`} label={server.name} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
import { Info, RefreshCw, Save } from 'lucide-react';
|
||||
import api from '../../services/api';
|
||||
import Modal from '../Modal';
|
||||
@@ -123,7 +124,7 @@ export default function ServerRestorePointsTab({ serverId }) {
|
||||
|
||||
<div className="server-restore-points__scope-note">
|
||||
<Info size={17} />
|
||||
<p>{t('app.serverRestorePoints.scopeNote', 'Remote restore points currently cover service environment variables stored by ServerKit. Secret values are masked and cannot be recovered. Shared variable groups and host-level cron, firewall, DNS, and Nginx are not included.')}</p>
|
||||
<p>{t('app.serverRestorePoints.scopeNoteShort', 'Covers service environment variables only.')} <InfoTip>{t('app.serverRestorePoints.scopeNote', 'Remote restore points currently cover service environment variables stored by ServerKit. Secret values are masked and cannot be recovered. Shared variable groups and host-level cron, firewall, DNS, and Nginx are not included.')}</InfoTip></p>
|
||||
</div>
|
||||
|
||||
{appsLoading && (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -153,7 +154,7 @@ const SurveyTab = ({ serverId, serverStatus, server }) => {
|
||||
<EmptyState
|
||||
icon={FileSearch}
|
||||
title={t('app.surveyTab.surveyNotAvailable', 'Survey not available')}
|
||||
description={t('app.surveyTab.thisAgentDoesnTSupportThe', "This agent doesn't support the read-only survey yet. Upgrade the agent to enable Observe mode. It maps what's running on the server without changing anything.")}
|
||||
description={<>{t('app.surveyTab.upgradeAgentForSurvey', 'Upgrade the agent to enable Observe mode.')} <InfoTip>{t('app.surveyTab.thisAgentDoesnTSupportThe', "This agent doesn't support the read-only survey yet. Upgrade the agent to enable Observe mode. It maps what's running on the server without changing anything.")}</InfoTip></>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,11 @@ import { statusKind } from '../ds/status.js';
|
||||
// Server connection states ride the shared vocabulary.
|
||||
export const serverStatusKind = (status) => statusKind(status);
|
||||
|
||||
// The backend names an unpaired server "Pending pairing (<short id>)"
|
||||
// (api/servers.py _placeholder_name); the id suffix is noise in a heading.
|
||||
const PLACEHOLDER_NAME = /^Pending pairing \(.*\)$/;
|
||||
export const isPlaceholderServerName = (name) => PLACEHOLDER_NAME.test(name ?? '');
|
||||
|
||||
export const PRESET_LABELS = {
|
||||
'* * * * *': 'Every minute',
|
||||
'*/5 * * * *': 'Every 5 minutes',
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { isPlaceholderServerName } from './serverDetailData.js';
|
||||
|
||||
test('backend placeholder names are detected', () => {
|
||||
assert.equal(isPlaceholderServerName('Pending pairing (342ade51)'), true);
|
||||
});
|
||||
|
||||
test('real names are left alone', () => {
|
||||
assert.equal(isPlaceholderServerName('web-01'), false);
|
||||
assert.equal(isPlaceholderServerName('Pending pairing'), false);
|
||||
assert.equal(isPlaceholderServerName(undefined), false);
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import api from '../../services/api';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '../../contexts/useToast.js';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Opt-in PgBouncer beside an installed PostgreSQL. Renders only
|
||||
// for PostgreSQL installs. Apps keep the direct connection unless they switch
|
||||
@@ -56,10 +57,10 @@ export default function PoolerCard({ app }) {
|
||||
/>
|
||||
</div>
|
||||
<p className="pooler__hint">
|
||||
{t('app.pooler.hint', 'Runs PgBouncer in transaction mode beside this database, so many client connections share a few server connections. Services opt in by referencing pooledUrl instead of connectionString.')}
|
||||
{t('app.pooler.hintShort', 'PgBouncer shares a few server connections.')} <InfoTip>{t('app.pooler.hint', 'Runs PgBouncer in transaction mode beside this database, so many client connections share a few server connections. Services opt in by referencing pooledUrl instead of connectionString.')}</InfoTip>
|
||||
</p>
|
||||
<p className="pooler__tradeoff">
|
||||
{t('app.pooler.tradeoff', 'Transaction pooling breaks session features: prepared statements in some drivers, LISTEN/NOTIFY, advisory locks and session SET. Services keep the direct connection unless they switch.')}
|
||||
{t('app.pooler.tradeoffShort', 'Transaction pooling breaks session features.')} <InfoTip>{t('app.pooler.tradeoff', 'Transaction pooling breaks session features: prepared statements in some drivers, LISTEN/NOTIFY, advisory locks and session SET. Services keep the direct connection unless they switch.')}</InfoTip>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -46,6 +46,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Card as SharedCard } from '@/components/ui/card';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import { formatDate } from '@/utils/intl';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// Grouped left sub-nav for the service Settings tab — mirrors the WordPress
|
||||
// detail page's settings layout: a group label per section with
|
||||
@@ -838,7 +839,7 @@ const ManifestSection = ({ app }) => {
|
||||
) : (
|
||||
<div className="svc-manifest__empty">
|
||||
<p className="hint">
|
||||
{t('app.settingsTab.thisProjectIsNotManagedBy', 'This project is not managed by a')} <code>serverkit.yaml</code> {t('app.settingsTab.manifestAManifestLetsYouDeclare', 'manifest. A manifest lets you declare services, domains, databases and environment requirements in one file so ServerKit can create and reconcile them for you.')}
|
||||
{t('app.settingsTab.thisProjectIsNotManagedBy', 'This project is not managed by a')} <code>serverkit.yaml</code> {t('app.settingsTab.manifestShort', 'manifest.')} <InfoTip>{t('app.settingsTab.manifestAManifestLetsYouDeclare', 'manifest. A manifest lets you declare services, domains, databases and environment requirements in one file so ServerKit can create and reconcile them for you.')}</InfoTip>
|
||||
</p>
|
||||
<p className="hint">
|
||||
<Link to="/docs/SERVERKIT_YAML.md">{t('app.settingsTab.learnAboutServerkitYaml', 'Learn about serverkit.yaml')}</Link>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useToast } from '../../contexts/useToast.js';
|
||||
import { useConfirm } from '@/hooks/useConfirm';
|
||||
import { formatRelativeShort } from '@/utils/intl';
|
||||
import { toastError } from '@/utils/errorMessage';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
|
||||
// A/B slot deploys. Shows which slot serves, which one is the
|
||||
// standby and for how long it stays warm, with the instant switch back. When
|
||||
@@ -144,7 +145,7 @@ export default function SlotsCard({ app }) {
|
||||
) : (
|
||||
<div className="slots-card__off">
|
||||
<p className="slots-card__hint">
|
||||
{t('app.slots.explain', 'A deploy boots the new release beside the live one, checks that it answers, then switches traffic over. A release that fails never replaces the working one, and the previous release stays ready for an instant switch back.')}
|
||||
{t('app.slots.explainShort', 'Boot, check, then switch traffic over.')} <InfoTip>{t('app.slots.explain', 'A deploy boots the new release beside the live one, checks that it answers, then switches traffic over. A release that fails never replaces the working one, and the previous release stays ready for an instant switch back.')}</InfoTip>
|
||||
</p>
|
||||
{state.eligibility.eligible ? (
|
||||
<p className="slots-card__hint">
|
||||
|
||||
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user