nomadro/scripts/harden_admin_cache_com.py
Eric 308974bf5e Harden platform upgrade: ops admin, live config, shared service proxy, and smoke deploys.
Ship Operations console polish, PocketBase social fixtures, and portal join-leads without local DBs or probe scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 01:20:55 +08:00

32 lines
1.7 KiB
Python

"""Keep admin HTML fresh and content-hashed assets cacheable on .com."""
import runpy
import shlex
from datetime import datetime, timezone
client = runpy.run_path('apps/admin/deploy/_upload_next_us.py')['connect']()
path = '/etc/nginx/sites-available/admin.nomadro.com.conf'
try:
with client.open_sftp() as sftp:
with sftp.open(path) as handle:
original = handle.read().decode()
updated = original.replace(
'location /assets/ { try_files $uri =404; expires 30d; }',
'location /assets/ { try_files $uri =404; add_header Cache-Control "public, max-age=31536000, immutable" always; add_header X-Content-Type-Options "nosniff" always; }')
updated = updated.replace(
'location / { try_files $uri $uri/ /index.html; }',
'location / { try_files $uri $uri/ /index.html; add_header Cache-Control "no-cache, must-revalidate" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; }')
if updated == original:
print('Cache policy already installed')
else:
backup = path + '.backup-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
with sftp.open(backup, 'w') as handle: handle.write(original)
with sftp.open(path, 'w') as handle: handle.write(updated)
_, output, error = client.exec_command('nginx -t && systemctl reload nginx')
code = output.channel.recv_exit_status()
if code:
with sftp.open(path, 'w') as handle: handle.write(original)
raise RuntimeError(error.read().decode())
print('Admin cache policy deployed; backup', backup)
finally:
client.close()