398 lines
16 KiB
Python
398 lines
16 KiB
Python
"""Application factory for the Simple Blog CMS."""
|
|
|
|
import os
|
|
import secrets
|
|
import tempfile
|
|
import time
|
|
from datetime import datetime, timedelta
|
|
|
|
from flask import (
|
|
Flask,
|
|
abort,
|
|
current_app,
|
|
flash,
|
|
g,
|
|
redirect,
|
|
render_template,
|
|
request,
|
|
session,
|
|
url_for,
|
|
)
|
|
from itsdangerous import URLSafeTimedSerializer
|
|
from . import auth
|
|
from .db import _slugify, get_db, init_db, parse_date, split_tags
|
|
from .markdown import render_markdown
|
|
from .analytics import (
|
|
classify_source,
|
|
client_ip,
|
|
country_flag,
|
|
is_bot,
|
|
parse_user_agent,
|
|
record_visit,
|
|
)
|
|
|
|
|
|
APP_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
|
|
def _env_flag(name, default=False):
|
|
"""Read a boolean environment flag (1/true/yes/on)."""
|
|
value = os.environ.get(name)
|
|
if value is None:
|
|
return default
|
|
return value.strip().lower() in ("1", "true", "yes", "on")
|
|
|
|
|
|
def _title_for_path(path):
|
|
"""Return a human-friendly page title for tracking, looked up from the DB."""
|
|
db = get_db()
|
|
slug = path.split("/", 2)[-1] if "/" in path else ""
|
|
if path == "/":
|
|
row = db.execute("SELECT value FROM settings WHERE key='site_title'").fetchone()
|
|
return (row[0] if row else "") or "Home"
|
|
if not slug:
|
|
return ""
|
|
if path.startswith("/post/"):
|
|
row = db.execute("SELECT title FROM posts WHERE slug=?", (slug,)).fetchone()
|
|
return row[0] if row else ""
|
|
if path.startswith("/p/"):
|
|
row = db.execute("SELECT title FROM pages WHERE slug=?", (slug,)).fetchone()
|
|
return row[0] if row else ""
|
|
if path.startswith("/category/"):
|
|
row = db.execute("SELECT name FROM categories WHERE slug=?", (slug,)).fetchone()
|
|
return row[0] if row else ""
|
|
if path.startswith("/tag/"):
|
|
return slug.replace("-", " ").title()
|
|
if path == "/search":
|
|
return "Search"
|
|
return ""
|
|
|
|
|
|
def create_app():
|
|
app = Flask(__name__)
|
|
# The real key is resolved in _load_auth_bootstrap(): an env-provided secret
|
|
# is used when it is long and not a known placeholder, otherwise a random
|
|
# secret is generated once and stored in the DB. Sessions are therefore
|
|
# never signed with a publicly known key.
|
|
app.config["SECRET_KEY"] = None
|
|
# Flag emoji for country codes, used by the analytics dashboards.
|
|
app.jinja_env.filters["country_flag"] = country_flag
|
|
# Turn the stored comma-separated tags into (name, slug) pairs so templates
|
|
# can link every tag to its public tag page.
|
|
app.jinja_env.filters["tag_list"] = lambda raw: [
|
|
{"name": name, "slug": _slugify(name)} for name in split_tags(raw)
|
|
]
|
|
app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 * 1024 # 64 MB (raised: image uploads were hitting werkzeug's 413 REQUEST ENTITY TOO LARGE at the old 8 MB cap)
|
|
|
|
# --- Session cookie hardening ---------------------------------------
|
|
# HttpOnly keeps the session cookie away from JavaScript; SameSite=Lax
|
|
# blocks cross-site POSTs (CSRF) while keeping normal navigation working.
|
|
# Cookies are marked Secure when the site is served over HTTPS; set
|
|
# BLOG_SECURE_COOKIES=1 behind a TLS-terminating reverse proxy.
|
|
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
|
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
|
app.config["SESSION_COOKIE_SECURE"] = _env_flag("BLOG_SECURE_COOKIES")
|
|
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(
|
|
seconds=auth.session_absolute_seconds()
|
|
)
|
|
app.config["SESSION_REFRESH_EACH_REQUEST"] = True
|
|
|
|
# --- Login management -------------------------------------------------
|
|
# Templates and static assets live at the project root (sibling of the blog
|
|
# package), so point both folders there explicitly.
|
|
app.template_folder = os.path.join(APP_ROOT, "templates")
|
|
app.static_folder = os.path.join(APP_ROOT, "static")
|
|
|
|
# Opt-in proxy awareness: behind a TLS-terminating reverse proxy set
|
|
# BLOG_TRUST_PROXY=1 so request.remote_addr, request.is_secure and the
|
|
# URLs Flask generates reflect the client/protocol instead of the proxy.
|
|
if _env_flag("BLOG_TRUST_PROXY"):
|
|
from werkzeug.middleware.proxy_fix import ProxyFix
|
|
|
|
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
|
|
|
|
@app.teardown_appcontext
|
|
def close_db(_exc=None):
|
|
db = g.pop("db", None)
|
|
if db is not None:
|
|
db.close()
|
|
|
|
with app.app_context():
|
|
init_db()
|
|
_seed_defaults()
|
|
auth.ensure_session_secret(app)
|
|
auth.ensure_admin_credentials(app)
|
|
|
|
from .public import bp as public_bp
|
|
from .admin import bp as admin_bp
|
|
|
|
app.register_blueprint(public_bp)
|
|
app.register_blueprint(admin_bp, url_prefix="/admin")
|
|
|
|
# --- Session lifetime -------------------------------------------------
|
|
# Expire idle/absolute-timeout sessions and invalidate them when the admin
|
|
# password has changed since the login. Registered first so every later
|
|
# hook (and every view) sees an already-validated session.
|
|
@app.before_request
|
|
def _enforce_session_lifetime():
|
|
auth.refresh_session()
|
|
|
|
@app.before_request
|
|
def _sync_custom_css():
|
|
# Keep the served custom.css in sync with the saved DB settings. The
|
|
# appearance editor writes this file on save, but a container/image
|
|
# rebuild restores the committed default template (losing your colors).
|
|
# Regenerating from the DB on every request guarantees your theme always
|
|
# applies -- even after a rebuild wipes this generated file. Only writes
|
|
# when a saved theme exists so we never clobber an existing file.
|
|
try:
|
|
custom_css = get_db().execute(
|
|
"SELECT value FROM settings WHERE key='custom_css'"
|
|
).fetchone()[0] or ""
|
|
except Exception:
|
|
return
|
|
if not custom_css:
|
|
return
|
|
css_dir = os.path.join(APP_ROOT, "static", "css")
|
|
css_path = os.path.join(css_dir, "custom.css")
|
|
try:
|
|
# Read with newline="" so a CRLF-saved theme stays distinct, then
|
|
# compare after normalising both sides. Text-mode reads turn CRLF
|
|
# into LF, so a theme saved with Windows line endings never matched:
|
|
# the file was rewritten on EVERY request, and a concurrent /static/
|
|
# read could catch it truncated. That dropped the theme's
|
|
# `.posts-grid` rule and the layout fell back to the default 2
|
|
# columns (intermittently, depending on navigation timing).
|
|
with open(css_path, "r", encoding="utf-8", newline="") as handle:
|
|
current = handle.read()
|
|
if current == custom_css or (
|
|
current.replace("\r\n", "\n") == custom_css.replace("\r\n", "\n")
|
|
):
|
|
return
|
|
except OSError:
|
|
pass
|
|
try:
|
|
os.makedirs(css_dir, exist_ok=True)
|
|
# Write then atomically replace: readers see either the old CSS or
|
|
# the new CSS, never a half-written stylesheet.
|
|
fd, tmp_path = tempfile.mkstemp(
|
|
dir=css_dir, prefix=".custom-", suffix=".css"
|
|
)
|
|
try:
|
|
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
handle.write(custom_css)
|
|
os.replace(tmp_path, css_path)
|
|
finally:
|
|
if os.path.exists(tmp_path):
|
|
os.remove(tmp_path)
|
|
except Exception:
|
|
return
|
|
|
|
# --- Visitor analytics (tracking) -------------------------------------
|
|
# Capture an anonymous visitor identity on first contact and record a visit
|
|
# for every public content page. Only the opaque `visitor_id` cookie is used;
|
|
# no personal data is stored. Admin pages and static assets are never tracked.
|
|
VISITOR_COOKIE_AGE = 60 * 60 * 24 * 365 # 1 year
|
|
|
|
class _Tracking:
|
|
def __init__(self, request):
|
|
self.request = request
|
|
self.is_new = True
|
|
cookie_val = request.cookies.get("visitor_id")
|
|
if cookie_val:
|
|
self.visitor_id = cookie_val
|
|
self.is_new = False
|
|
else:
|
|
self.visitor_id = secrets.token_hex(16)
|
|
browser, os_name, device = parse_user_agent(
|
|
request.headers.get("User-Agent", "")
|
|
)
|
|
referer, referrer_domain, source = classify_source(
|
|
request.headers.get("Referer", "")
|
|
)
|
|
self.visitor = {
|
|
"visitor_id": self.visitor_id,
|
|
"browser": browser,
|
|
"os": os_name,
|
|
"device": device,
|
|
"referrer": referer,
|
|
"referrer_domain": referrer_domain,
|
|
"source": source,
|
|
}
|
|
self.page_path = request.path
|
|
self.title = _title_for_path(request.path)
|
|
# Used once to resolve the visitor's approximate location (the IP
|
|
# itself is never persisted). ProxyFix supplies the real client
|
|
# address when BLOG_TRUST_PROXY is enabled.
|
|
# Behind Docker's port mapping / a LAN reverse proxy the peer is a
|
|
# private address, so the forwarding headers supply the real one.
|
|
self.ip = client_ip(
|
|
request.remote_addr,
|
|
request.headers,
|
|
_env_flag("BLOG_TRUST_PROXY"),
|
|
)
|
|
|
|
@app.before_request
|
|
def _tracking_before():
|
|
if getattr(g, "_track", None) is not None:
|
|
return
|
|
path = request.path
|
|
# Track only public content; never the admin area or static assets.
|
|
if path.startswith("/admin/") or path.startswith("/static/"):
|
|
return
|
|
if request.method != "GET":
|
|
return
|
|
# Crawlers, monitors and CLI fetchers would otherwise dominate the
|
|
# analytics tables.
|
|
if is_bot(request.headers.get("User-Agent", "")):
|
|
return
|
|
g._track = _Tracking(request)
|
|
|
|
@app.after_request
|
|
def _tracking_after(resp):
|
|
track = getattr(g, "_track", None)
|
|
if track is None:
|
|
return resp
|
|
# Only successful page loads count: 404s from link scanners used to
|
|
# create a visitor row for every bogus URL they probed.
|
|
if resp.status_code != 200:
|
|
return resp
|
|
record_visit(track.visitor, track.page_path, track.title, ip=track.ip)
|
|
if track.is_new:
|
|
resp.set_cookie(
|
|
"visitor_id",
|
|
track.visitor_id,
|
|
max_age=VISITOR_COOKIE_AGE,
|
|
path="/",
|
|
httponly=True,
|
|
)
|
|
return resp
|
|
|
|
# --- Static asset caching --------------------------------------------
|
|
# This app is a subpath (/admin/*) and serves large JS bundles. Flask's default
|
|
# static route uses ETag-based conditional requests, so the browser revalidates
|
|
# (HTTP 304) and can serve a STALE cached copy that never loads the real file.
|
|
# Force no-store on every /static/ response so assets are always downloaded fresh;
|
|
# combined with a one-time cache clear this removes stale-editor problems permanently.
|
|
@app.after_request
|
|
def force_no_static_cache(resp):
|
|
if request.path.startswith("/static/"):
|
|
resp.headers["Cache-Control"] = "no-store"
|
|
# Authenticated pages must never be cached by a shared cache or the
|
|
# browser back button after logout.
|
|
elif request.path.startswith("/admin/"):
|
|
resp.headers["Cache-Control"] = "no-store, private"
|
|
return resp
|
|
|
|
# --- Security headers -------------------------------------------------
|
|
@app.after_request
|
|
def _security_headers(resp):
|
|
resp.headers.setdefault("X-Content-Type-Options", "nosniff")
|
|
resp.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
|
|
# strict-origin-when-cross-origin is the browser default: cross-origin
|
|
# requests still get the site origin. "same-origin" stripped the Referer
|
|
# entirely, which OpenStreetMap's tile usage policy forbids — its tile
|
|
# servers answered the analytics map with a 403 "Access blocked" tile.
|
|
resp.headers.setdefault(
|
|
"Referrer-Policy", "strict-origin-when-cross-origin"
|
|
)
|
|
if request.is_secure:
|
|
resp.headers.setdefault(
|
|
"Strict-Transport-Security", "max-age=31536000; includeSubDomains"
|
|
)
|
|
return resp
|
|
|
|
@app.context_processor
|
|
def expose_helpers():
|
|
session.setdefault("csrf_token", secrets.token_hex(16))
|
|
db = get_db()
|
|
# One query for every setting the templates need (this was five
|
|
# separate round trips per request) plus one for the nav pages.
|
|
settings = {
|
|
row["key"]: row["value"] or ""
|
|
for row in db.execute("SELECT key, value FROM settings").fetchall()
|
|
}
|
|
pages = db.execute(
|
|
"SELECT id, slug, title FROM pages WHERE published = 1 "
|
|
"ORDER BY position, id"
|
|
).fetchall()
|
|
# Defensive against a missing row so an un-seeded DB still renders.
|
|
try:
|
|
comments_enabled = bool(int(settings.get("comments_enabled") or "1"))
|
|
except ValueError:
|
|
comments_enabled = True
|
|
|
|
# Badge count for the admin nav: comments waiting for moderation. Kept
|
|
# defensive so a not-yet-migrated DB still renders every page.
|
|
try:
|
|
pending_comments = db.execute(
|
|
"SELECT COUNT(*) FROM comments WHERE status = 'pending'"
|
|
).fetchone()[0]
|
|
except Exception:
|
|
pending_comments = 0
|
|
|
|
def preview_url(post):
|
|
"""Signed, expiring link to view an unpublished post."""
|
|
token = URLSafeTimedSerializer(
|
|
current_app.config["SECRET_KEY"], salt="post-preview"
|
|
).dumps(int(post["id"]))
|
|
return url_for("public.preview", pid=post["id"], token=token)
|
|
|
|
return {
|
|
# Real year (this was hardcoded to 2026 in the footer).
|
|
"current_year": lambda: datetime.now().year,
|
|
# Render time of this page, used by the comment form's bot traps.
|
|
"now_ts": int(time.time()),
|
|
"csrf_token": session.get("csrf_token"),
|
|
"parse_date": parse_date,
|
|
"render_markdown": render_markdown,
|
|
# Exposed so public templates (base.html) can render the admin-uploaded
|
|
# header image and load custom CSS without each route passing them.
|
|
"header_image": settings.get("header_image", ""),
|
|
"custom_css": settings.get("custom_css", ""),
|
|
# Published content pages, in display order — drives the top nav and
|
|
# is what the admin Pages manager edits.
|
|
"pages": pages,
|
|
"site_title": settings.get("site_title") or "My Blog",
|
|
"site_tagline": settings.get("site_tagline", ""),
|
|
# Default search/social description, editable from Appearance. Pages
|
|
# can override it with a meta_description template block.
|
|
"meta_description": settings.get("meta_description", ""),
|
|
"pending_comments": pending_comments,
|
|
"preview_url": preview_url,
|
|
# Whether the public comment system is switched on (toggleable from
|
|
# the admin Appearance page) and whether an admin is signed in (used
|
|
# to let logged-in users delete their own comments).
|
|
"comments_enabled": comments_enabled,
|
|
"logged_in": auth.is_logged_in(),
|
|
}
|
|
|
|
return app
|
|
|
|
|
|
def _seed_defaults():
|
|
from .db import _utcnow
|
|
|
|
db = get_db()
|
|
db.execute(
|
|
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
|
|
("site_title", "My Blog"),
|
|
)
|
|
db.execute(
|
|
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
|
|
("site_tagline", "Thoughts on tech, self-hosting and life."),
|
|
)
|
|
db.execute(
|
|
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
|
|
("meta_description", ""),
|
|
)
|
|
db.execute(
|
|
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
|
|
("header_image", ""),
|
|
)
|
|
db.execute(
|
|
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
|
|
("custom_css", ""),
|
|
)
|
|
db.commit()
|