ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Let proxied sites long-cache fingerprinted assets
Juan Denise688b7b5c3c4
diff --git a/backend/app/api/app_attachments.py b/backend/app/api/app_attachments.pyindex b62741a8..134b068a 100644--- a/backend/app/api/app_attachments.py+++ b/backend/app/api/app_attachments.py@@ -131,3 +131,20 @@ def get_hints(app_id):if app is None or not ResourceGrantService.can_access_app(get_current_user(), app):raise NotFoundError('Application not found')return jsonify({'hints': BottleneckHintsService.hints(app)})+++# ==================== IMMUTABLE ASSETS (plan 86 §B2) ====================++@app_attachments_bp.route('/<int:app_id>/immutable-assets', methods=['PUT'])+@developer_required+def set_immutable_assets(app_id):+ """Long-cache fingerprinted assets (``app.3f9a2c1d.js``) in the vhost.+ Off by default: the panel cannot know an app's asset layout."""+ from app.services.site_domain_service import SiteDomainService+ app = AppAttachmentService.live_app(app_id)+ if app is None or not ResourceGrantService.can_edit_app(get_current_user(), app):+ raise NotFoundError('Application not found')+ data = request.get_json(silent=True) or {}+ if not isinstance(data.get('enabled'), bool):+ raise ValidationError("'enabled' must be true or false")+ return jsonify(SiteDomainService.set_immutable_assets(app, data['enabled']))diff --git a/backend/app/models/application.py b/backend/app/models/application.pyindex a22fbc8d..67072c0b 100644--- a/backend/app/models/application.py+++ b/backend/app/models/application.py@@ -116,6 +116,8 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model):micro_cache_ttl = db.Column(db.Integer, nullable=True)# Opt-in PgBouncer sidecar for a PostgreSQL engine app (plan 86 §D1).pooler_enabled = db.Column(db.Boolean, nullable=True)+ # Long-cache fingerprinted assets in the vhost (plan 86 §B2).+ immutable_assets = db.Column(db.Boolean, nullable=True)# Environment linkingenvironment_type = db.Column(db.String(20), default='standalone') # 'production', 'development', 'staging', 'standalone'@@ -236,6 +238,7 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model):'micro_cache_enabled': bool(self.micro_cache_enabled),'micro_cache_ttl': self.micro_cache_ttl,'pooler_enabled': bool(self.pooler_enabled),+ 'immutable_assets': bool(self.immutable_assets),'environment_type': self.environment_type,'linked_app_id': self.linked_app_id,'shared_config': self._json_read('shared_config', None),diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.pyindex 29015980..3381383c 100644--- a/backend/app/services/nginx_service.py+++ b/backend/app/services/nginx_service.py@@ -409,6 +409,21 @@ log_format serverkit_timed '$remote_addr - $remote_user [$time_local] "$request"('brotli_types', COMPRESSION_TYPES),)+ # ==================== IMMUTABLE ASSETS (plan 86 §B2) ====================+ # Opt-in, proxied sites only: a fingerprinted asset (a hash in its name)+ # never changes, so the browser may keep it a year. Off by default because+ # the panel cannot know an app's asset layout. The hash must be 8+ chars+ # after a '.' or '-' AND contain a digit, so `app-settings.js` is never+ # pinned; a hash with no digit is simply not long-cached (the safe miss).+ IMMUTABLE_ASSET_PATTERN = (+ r'[.-](?=[A-Za-z0-9_]*[0-9])[A-Za-z0-9_]{8,}'+ r'\.(?:js|mjs|css|map|woff2?|ttf|otf|png|jpe?g|gif|svg|webp|avif|ico)$'+ )+ # One Cache-Control header: `expires` would emit its own max-age header+ # next to this one, and clients read either.+ IMMUTABLE_ASSET_HEADERS = ''' add_header Cache-Control "public, max-age=31536000, immutable";+'''+# ==================== MICRO-CACHE (task #21) ====================# Opt-in per-site micro-cache: a very short (10s) full-page cache in front# of proxied/PHP sites, with hard bypasses for anything personalized.@@ -629,6 +644,7 @@ location /p/ {{upstream: str = None,micro_cache: bool = False,micro_cache_ttl: Optional[int] = None,+ immutable_assets: bool = False,wordpress_protection: bool = False) -> Dict:"""Render the vhost config for a site to a string — no side effects.@@ -696,6 +712,9 @@ location /p/ {{else:return {'success': False, 'error': f'Unknown app type: {app_type}'}+ if immutable_assets:+ config = cls._with_immutable_assets(config, app_type)+if micro_cache:# Inject before the SSL wrap so the redirect server block (which# also carries a server_name line) never receives cache directives.@@ -756,6 +775,23 @@ location /p/ {{except Exception as e:return {'success': False, 'error': str(e)}+ @classmethod+ def _with_immutable_assets(cls, config: str, app_type: str) -> str:+ """Add a regex location for fingerprinted assets to a proxied vhost:+ the same proxying as ``location /`` plus a one-year immutable cache.+ Appended after ``location /`` (a matching regex location wins over the+ ``/`` prefix wherever it sits) so the micro-cache injection still+ anchors on the real ``location /``."""+ if (app_type or '').lower() not in ('flask', 'django', 'python', 'docker', 'remote'):+ return config+ match = re.search(r'^ location / \{\n(.*?)^ \}\n', config, re.MULTILINE | re.DOTALL)+ if not match:+ return config+ block = ('\n # ServerKit: fingerprinted assets never change (plan 86 §B2)\n'+ f' location ~* "{cls.IMMUTABLE_ASSET_PATTERN}" {{\n'+ + match.group(1) + cls.IMMUTABLE_ASSET_HEADERS + ' }\n')+ return config[:match.end()] + block + config[match.end():]+@classmethoddef _with_micro_cache(cls, config: str, app_type: str,ttl: Optional[int] = None) -> str:@@ -1001,6 +1037,7 @@ location /p/ {{ssl_cert: str = None, ssl_key: str = None,upstream: str = None, micro_cache: bool = False,micro_cache_ttl: Optional[int] = None,+ immutable_assets: bool = False,wordpress_protection: bool = False) -> Dict:"""Create a new site configuration.@@ -1014,7 +1051,7 @@ location /p/ {{name, app_type, domains, root_path=root_path, port=port,php_version=php_version, ssl_cert=ssl_cert, ssl_key=ssl_key,upstream=upstream, micro_cache=micro_cache,- micro_cache_ttl=micro_cache_ttl,+ micro_cache_ttl=micro_cache_ttl, immutable_assets=immutable_assets,wordpress_protection=wordpress_protection,)if not rendered.get('success'):diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.pyindex 61ed39fd..1fc04e20 100644--- a/backend/app/services/site_domain_service.py+++ b/backend/app/services/site_domain_service.py@@ -493,7 +493,8 @@ class SiteDomainService:# an enabled cache must never show up as config drift.base = dict(name=app.name, domains=domains, ssl_cert=ssl_cert, ssl_key=ssl_key,micro_cache=bool(getattr(app, 'micro_cache_enabled', False)),- micro_cache_ttl=getattr(app, 'micro_cache_ttl', None))+ micro_cache_ttl=getattr(app, 'micro_cache_ttl', None),+ immutable_assets=bool(getattr(app, 'immutable_assets', False)))# Reverse-proxy to a local container/app port.if t in ('docker', 'wordpress'):if not app.port:@@ -553,6 +554,24 @@ class SiteDomainService:return cls._vhost_create_kwargs(app, domains, ssl_cert, ssl_key, force_type)+ @classmethod+ def set_immutable_assets(cls, app, enabled):+ """Save the fingerprinted-asset caching flag and republish the vhost+ through the same path as every other vhost setting (plan 86 §B2), so+ drift detection renders the same file."""+ from app import db+ app.immutable_assets = bool(enabled)+ db.session.commit()+ applied, warning = False, None+ if app.live_domains:+ result = cls.write_app_vhost(app)+ warning = result.get('warning')+ applied = result.get('nginx') is not None and not warning+ body = {'immutable_assets': bool(app.immutable_assets), 'applied': applied}+ if warning:+ body['warning'] = warning+ return body+@classmethoddef write_app_vhost(cls, app, force_type=None):"""(Re)write and enable the host-nginx vhost publishing ``app`` at everydiff --git a/backend/migrations/versions/104_immutable_assets.py b/backend/migrations/versions/104_immutable_assets.pynew file mode 100644index 00000000..6ad041ac--- /dev/null+++ b/backend/migrations/versions/104_immutable_assets.py@@ -0,0 +1,19 @@+"""Opt-in long caching of fingerprinted assets per app (plan 86 §B2). NULL = off."""+from alembic import op+import sqlalchemy as sa++revision = '104_immutable_assets'+down_revision = '103_pooler_enabled'+branch_labels = None+depends_on = None+++def upgrade():+ inspector = sa.inspect(op.get_bind())+ # Add-if-missing: the pre-alembic schema sync may already have added it.+ if 'immutable_assets' not in {c['name'] for c in inspector.get_columns('applications')}:+ op.add_column('applications', sa.Column('immutable_assets', sa.Boolean, nullable=True))+++def downgrade():+ op.drop_column('applications', 'immutable_assets')diff --git a/backend/tests/test_immutable_assets.py b/backend/tests/test_immutable_assets.pynew file mode 100644index 00000000..6b0b1de1--- /dev/null+++ b/backend/tests/test_immutable_assets.py@@ -0,0 +1,75 @@+"""Opt-in long caching of fingerprinted assets (plan 86 §B2). The real-nginx+half (hashed names come back immutable, look-alikes do not) is in+test_real_nginx_vhost_syntax.py."""+import re++import pytest++from app import db+from app.models.domain import Domain+from app.services.nginx_service import NginxService+from app.services.site_domain_service import SiteDomainService+from tests.factories import make_application+++def _render(**kw):+ return NginxService.render_site_config('shop', domains=['shop.lvh.me'], **kw)['config']+++def test_off_by_default():+ assert 'immutable' not in _render(app_type='docker', port=8300)+++def test_the_block_proxies_like_location_root_and_pins_the_asset():+ cfg = _render(app_type='docker', port=8300, immutable_assets=True)+ block = cfg[cfg.index('location ~* "'):]+ assert 'proxy_pass http://127.0.0.1:8300;' in block+ assert 'add_header Cache-Control "public, max-age=31536000, immutable";' in block+ assert 'expires' not in block, 'a second Cache-Control header would conflict'+ assert cfg.index(' location / {') < cfg.index('location ~* "')+++def test_micro_cache_still_anchors_on_location_root():+ cfg = _render(app_type='docker', port=8300, immutable_assets=True, micro_cache=True)+ root = cfg[cfg.index(' location / {'):cfg.index('location ~* "')]+ assert 'proxy_cache serverkit_microcache;' in root+ assert cfg.count('proxy_cache serverkit_microcache;') == 1++[email protected]('app_type,kw', [('static', {'root_path': '/srv/x'}),+ ('php', {'root_path': '/srv/x'})])+def test_only_proxied_sites_get_it(app_type, kw):+ assert 'immutable' not in _render(app_type=app_type, immutable_assets=True, **kw)++[email protected]('path,pinned', [+ ('/assets/index-DQK8aLC1.js', True),+ ('/static/js/main.3f2a9b1c.chunk.js', False), # hash not right before the extension+ ('/static/css/main.3f2a9b1c.css', True),+ ('/fonts/inter-4f8b2c1d.woff2', True),+ ('/assets/app-settings.js', False),+ ('/assets/abcdefgh.js', False), # 8 letters, no digit: not a hash+ ('/assets/logo.svg', False),+ ('/app.js', False),+])+def test_the_pattern(path, pinned):+ assert bool(re.search(NginxService.IMMUTABLE_ASSET_PATTERN, path, re.I)) is pinned+++def test_the_flag_rides_the_shared_vhost_kwargs(app):+ site = make_application(db, name='assets-kw', port=8300)+ db.session.add(Domain(name='assets-kw.lvh.me', application_id=site.id, is_primary=True))+ site.immutable_assets = True+ db.session.commit()+ kwargs, _warn = SiteDomainService.app_vhost_kwargs(site)+ assert kwargs['immutable_assets'] is True+++def test_api(client, auth_headers, monkeypatch, app):+ site = make_application(db, name='assets-api', port=8300)+ monkeypatch.setattr(SiteDomainService, 'write_app_vhost',+ classmethod(lambda cls, a, force_type=None: {'nginx': {'success': True}}))+ url = f'/api/v1/apps/{site.id}/immutable-assets'+ resp = client.put(url, json={'enabled': True}, headers=auth_headers)+ assert resp.status_code == 200 and resp.get_json()['immutable_assets'] is True+ assert client.put(url, json={'enabled': 1}, headers=auth_headers).status_code == 400diff --git a/backend/tests/test_real_nginx_vhost_syntax.py b/backend/tests/test_real_nginx_vhost_syntax.pyindex 7604786c..7997aa1e 100644--- a/backend/tests/test_real_nginx_vhost_syntax.py+++ b/backend/tests/test_real_nginx_vhost_syntax.py@@ -113,6 +113,9 @@ def _render(**kwargs):('docker-micro-cache', dict(name='fast', app_type='docker',domains=['fast.example.com'], port=8004,micro_cache=True)),+ ('docker-immutable-assets', dict(name='assets', app_type='docker',+ domains=['assets.example.com'], port=8006,+ micro_cache=True, immutable_assets=True)),('php-micro-cache', dict(name='fastphp', app_type='php',domains=['fastphp.example.com'],root_path='/var/www/fastphp', micro_cache=True,@@ -166,3 +169,51 @@ def test_compression_snippet_round_trips_through_real_nginx(tmp_path, stock_httpcapture_output=True, text=True)assert proc.returncode == 0, f'{snippet}\n{proc.stderr}'assert 'gzip_types' in snippet or 'gzip_types' in stock_http+++def test_only_fingerprinted_assets_are_pinned_by_real_nginx(tmp_path):+ """Serve through the generated vhost (plan 86 §B2): hashed names come back+ immutable, look-alikes without a hash do not."""+ import socket+ import time+ import urllib.request++ def free_port():+ with socket.socket() as s:+ s.bind(('127.0.0.1', 0))+ return s.getsockname()[1]++ upstream_port, listen_port = free_port(), free_port()+ www = tmp_path / 'www'+ (www / 'assets').mkdir(parents=True)+ names = {+ 'assets/index-DQK8aLC1.js': True, # Vite+ 'assets/main.3f2a9b1c.css': True, # webpack+ 'assets/app-settings.js': False, # a dash, but no hash+ 'assets/logo.svg': False,+ 'app.js': False,+ }+ for name in names:+ (www / name).write_text('x')+ upstream = subprocess.Popen(['python3', '-m', 'http.server', str(upstream_port),+ '--bind', '127.0.0.1'], cwd=www,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ config = _render(name='assets', app_type='docker', domains=['assets.example.com'],+ port=upstream_port, immutable_assets=True)+ config = config.replace('listen 80;', f'listen {listen_port};')+ proc = _nginx_t(tmp_path, config)+ assert proc.returncode == 0, proc.stderr+ wrapper = str(tmp_path / 'nginx.conf')+ subprocess.run([NGINX, '-c', wrapper], check=True, capture_output=True)+ try:+ time.sleep(0.5)+ for name, pinned in names.items():+ req = urllib.request.Request(f'http://127.0.0.1:{listen_port}/{name}',+ headers={'Host': 'assets.example.com'})+ with urllib.request.urlopen(req, timeout=5) as resp:+ headers = resp.headers.get_all('Cache-Control') or []+ assert len(headers) <= 1, (name, headers) # one policy, not two+ assert ('immutable' in ''.join(headers)) is pinned, (name, headers)+ finally:+ subprocess.run([NGINX, '-c', wrapper, '-s', 'stop'], capture_output=True)+ upstream.terminate()diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.mdindex 27c52fe9..635b9e44 100644--- a/docs/API_SURFACE.md+++ b/docs/API_SURFACE.md@@ -1289,6 +1289,7 @@ Regenerate (backend/):- `PUT /apps/{app_id}/backup-policy`- `PUT /apps/{app_id}/env/{key}`- `PUT /apps/{app_id}/environment`+- `PUT /apps/{app_id}/immutable-assets`- `PUT /apps/{app_id}/micro-cache`- `PUT /apps/{app_id}/pooler`- `PUT /apps/{app_id}/previews/settings`diff --git a/frontend/src/components/apps/MicroCachePanel.jsx b/frontend/src/components/apps/MicroCachePanel.jsxindex 893b9c0f..618f63c0 100644--- a/frontend/src/components/apps/MicroCachePanel.jsx+++ b/frontend/src/components/apps/MicroCachePanel.jsx@@ -12,6 +12,9 @@ import { useTranslation } from 'react-i18next';// Must match NginxService.MICROCACHE_TTL_DEFAULT / MICROCACHE_TTL_MAX.const TTL_DEFAULT = 10;const TTL_MAX = 300;+// App types whose vhost proxies to the app — the only ones the fingerprinted+// asset rule applies to (NginxService._with_immutable_assets).+const PROXIED_TYPES = ['docker', 'flask', 'django', 'python', 'remote'];// Micro-cache panel (task #21, plan 86 §B3) — opt-in nginx page cache per// site. The backend rewrites the site's vhost with the cache directives plus@@ -27,6 +30,8 @@ const MicroCachePanel = ({ app, onChanged }) => {const [saving, setSaving] = useState(false);const [purging, setPurging] = useState(false);const [hitRatio, setHitRatio] = useState(null);+ const [immutable, setImmutable] = useState(!!app.immutable_assets);+ const proxied = PROXIED_TYPES.includes(app.app_type);useEffect(() => {if (!enabled) return undefined;@@ -78,6 +83,19 @@ const MicroCachePanel = ({ app, onChanged }) => {}}+ async function handleImmutable(next) {+ setImmutable(next);+ try {+ const data = await api.setImmutableAssets(app.id, next);+ if (data.warning) toast.warning(data.warning);+ else toast.success(t('app.microCachePanel.assetCachingSaved', 'Asset caching saved.'));+ onChanged?.();+ } catch (err) {+ setImmutable(!next);+ toast.error(err.message);+ }+ }+async function handlePurge() {if (!await confirm({title: t('app.microCachePanel.clearMicroCache', 'Clear micro-cache'),@@ -124,6 +142,24 @@ const MicroCachePanel = ({ app, onChanged }) => {</div></div>+ {proxied && (+ <div className="settings-row">+ <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.')}+ </span>+ </div>+ <div className="settings-control">+ <Switch+ checked={immutable}+ onCheckedChange={handleImmutable}+ aria-label={t('app.microCachePanel.longCacheAssets', 'Long-cache fingerprinted assets')}+ />+ </div>+ </div>+ )}+{enabled && (<><div className="settings-row">diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 46507a2d..fd257985 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -3269,6 +3269,7 @@"workers": "Workers"},"microCachePanel": {+ "assetCachingSaved": "Asset caching saved.","cacheLifetime": "Cache lifetime (seconds)","cacheLifetimeHint": "How long a page is served from the cache before the app is asked again (1–{{max}}). Longer means fewer requests reach the app, and changes take longer to show.","cacheLifetimeSaved": "Cache lifetime saved.",@@ -3283,6 +3284,8 @@"failedToUpdateMicroCache": "Failed to update micro-cache","hitRatio": "Hit ratio (24 h)","hitRatioHint": "Share of cacheable requests answered from the cache. Bypassed requests are not counted.",+ "longCacheAssets": "Long-cache fingerprinted assets",+ "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.","meansThePageCameFromThe": "means the page came from the cache,","microCache": "Micro-cache","microCacheCleared": "Micro-cache cleared",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 350eeab0..084c24f0 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -3027,7 +3027,10 @@"clearing": "Borrando…","hitRatio": "Tasa de aciertos (24 h)","hitRatioHint": "Proporción de solicitudes cacheables respondidas desde la caché. Las solicitudes que evitan la caché no cuentan.",- "noCachedTrafficYet": "Aún no hay tráfico en caché"+ "noCachedTrafficYet": "Aún no hay tráfico en caché",+ "assetCachingSaved": "Caché de recursos guardada.",+ "longCacheAssets": "Caché larga de recursos con huella",+ "longCacheAssetsHint": "Los navegadores guardan un año los archivos cuyo nombre lleva un hash de contenido (app.3f9a2c1d.js). Actívalo solo si tu build nombra así los recursos: un archivo que cambie sin cambiar de nombre quedaría desactualizado."},"migrationHistoryTab": {"aDatabaseBackupIsCreatedFirst": "Primero se crea una copia de seguridad de la base de datos y luego el esquema se actualiza de {{value}} a {{value2}}.",diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.jsindex 5ffeb200..5e11b06e 100644--- a/frontend/src/services/api/apps.js+++ b/frontend/src/services/api/apps.js@@ -569,3 +569,8 @@ export async function setAppPooler(appId, enabled) {export async function getAppHints(appId) {return this.request(`/apps/${appId}/hints`);}++// Long-cache fingerprinted assets in the vhost (plan 86 §B2).+export async function setImmutableAssets(appId, enabled) {+ return this.request(`/apps/${appId}/immutable-assets`, { method: 'PUT', body: { enabled } });+}