Files
port-ui/app/app.py

199 lines
6.0 KiB
Python
Raw Permalink Normal View History

import logging
2025-01-08 14:59:36 +01:00
import os
2025-07-05 20:08:00 +02:00
import requests
import yaml
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
from flask import Flask, current_app, make_response, render_template, request, url_for
from markupsafe import Markup
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
from werkzeug.middleware.proxy_fix import ProxyFix
try:
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
from app.utils import i18n
feat(assets): probe-first resolver + SPOT for IMAGE_NAME/PORT + README screenshot Probe-first asset resolution (regression fix) --------------------------------------------- cache_manager.cache_file() returned either a relative cache path (success) or None (failure). The previous app.py fallback asset['cache'] = cached or asset['source'] mixed both types into one field, which the template wrapped in url_for('static', ...) regardless — producing broken /static/https://file.infinito.nexus/.../logo.png URLs whenever the source couldn't be downloaded. - New app/utils/asset_resolver.py: HEAD-probes the URL (3 s timeout, image/* content type). On hit, embed directly via a new external_url field — no download required. On miss, fall back to cache_manager.cache_file. If that also fails, expose the source URL via external_url so the browser shows the alt text instead of an empty src. - app.py exposes an asset_src(asset) context processor that picks external_url first, then url_for('static', cache), so the template never wraps an absolute URL in a static prefix. - Templates (base, navigation, card) switch to asset_src(...) and gate the card image branch on cache or external_url. - 16 unit tests cover every probe/cache/fallback branch; one live integration test exercises the canonical https://file.infinito.nexus/assets/img/logo.png to prove the probe-first path works end-to-end (cache dir stays empty). - config.sample.yaml: new Infinito.Nexus card driven by the same canonical asset URL. Single source of truth for IMAGE_NAME and PORT ---------------------------------------------- - env.example is now the only place the literal values live. - Makefile and docker-compose.yml reference \$(IMAGE_NAME) / \${IMAGE_NAME:?…} (same for PORT); no defaults, no silent fallbacks. - New make env / make config bootstrap .env / app/config.yaml from their checked-in templates. Idempotent. - All container-using targets depend on the two bootstrap targets so a fresh checkout runs in a single invocation. - Recipes source .env at recipe-execution time so they pick up a freshly bootstrapped .env in the same make invocation. README ------ - Screenshot added under the title. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 12:19:15 +02:00
from app.utils.asset_resolver import asset_src, resolve_asset_cache
from app.utils.cache_manager import CacheManager
from app.utils.compute_card_classes import compute_card_classes
from app.utils.configuration_resolver import ConfigurationResolver
except ImportError: # pragma: no cover - supports running from the app/ directory.
feat(assets): probe-first resolver + SPOT for IMAGE_NAME/PORT + README screenshot Probe-first asset resolution (regression fix) --------------------------------------------- cache_manager.cache_file() returned either a relative cache path (success) or None (failure). The previous app.py fallback asset['cache'] = cached or asset['source'] mixed both types into one field, which the template wrapped in url_for('static', ...) regardless — producing broken /static/https://file.infinito.nexus/.../logo.png URLs whenever the source couldn't be downloaded. - New app/utils/asset_resolver.py: HEAD-probes the URL (3 s timeout, image/* content type). On hit, embed directly via a new external_url field — no download required. On miss, fall back to cache_manager.cache_file. If that also fails, expose the source URL via external_url so the browser shows the alt text instead of an empty src. - app.py exposes an asset_src(asset) context processor that picks external_url first, then url_for('static', cache), so the template never wraps an absolute URL in a static prefix. - Templates (base, navigation, card) switch to asset_src(...) and gate the card image branch on cache or external_url. - 16 unit tests cover every probe/cache/fallback branch; one live integration test exercises the canonical https://file.infinito.nexus/assets/img/logo.png to prove the probe-first path works end-to-end (cache dir stays empty). - config.sample.yaml: new Infinito.Nexus card driven by the same canonical asset URL. Single source of truth for IMAGE_NAME and PORT ---------------------------------------------- - env.example is now the only place the literal values live. - Makefile and docker-compose.yml reference \$(IMAGE_NAME) / \${IMAGE_NAME:?…} (same for PORT); no defaults, no silent fallbacks. - New make env / make config bootstrap .env / app/config.yaml from their checked-in templates. Idempotent. - All container-using targets depend on the two bootstrap targets so a fresh checkout runs in a single invocation. - Recipes source .env at recipe-execution time so they pick up a freshly bootstrapped .env in the same make invocation. README ------ - Screenshot added under the title. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 12:19:15 +02:00
from utils.asset_resolver import asset_src, resolve_asset_cache
from utils.cache_manager import CacheManager
from utils.compute_card_classes import compute_card_classes
from utils.configuration_resolver import ConfigurationResolver
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
from utils import i18n
TRANSLATED_SECTIONS = ("cards", "company", "navigation", "platform")
2025-07-05 10:55:32 +02:00
logging.basicConfig(level=logging.DEBUG)
FLASK_ENV = os.getenv("FLASK_ENV", "production")
FLASK_HOST = os.getenv("FLASK_HOST", "127.0.0.1")
FLASK_PORT = int(os.getenv("FLASK_PORT", os.getenv("PORT", 5000)))
print(f"Starting app on {FLASK_HOST}:{FLASK_PORT}, FLASK_ENV={FLASK_ENV}")
2025-01-08 14:59:36 +01:00
2025-01-09 14:27:07 +01:00
# Initialize the CacheManager
cache_manager = CacheManager()
2025-01-09 14:27:07 +01:00
# Clear cache on startup
cache_manager.clear_cache()
2025-01-08 14:59:36 +01:00
def load_config(app):
2025-07-01 23:28:25 +02:00
"""Load and resolve the configuration from config.yaml."""
with open("config.yaml", "r", encoding="utf-8") as handle:
config = yaml.safe_load(handle)
2025-07-05 20:08:00 +02:00
if config.get("nasa_api_key"):
app.config["NASA_API_KEY"] = config["nasa_api_key"]
resolver = ConfigurationResolver(config)
resolver.resolve_links()
app.config.update(resolver.get_config())
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
app.config["TRANSLATED_CONFIG"] = {}
i18n.clear_catalogs()
2025-01-08 14:59:36 +01:00
2025-07-01 23:28:25 +02:00
def cache_icons_and_logos(app):
feat(assets): probe-first resolver + SPOT for IMAGE_NAME/PORT + README screenshot Probe-first asset resolution (regression fix) --------------------------------------------- cache_manager.cache_file() returned either a relative cache path (success) or None (failure). The previous app.py fallback asset['cache'] = cached or asset['source'] mixed both types into one field, which the template wrapped in url_for('static', ...) regardless — producing broken /static/https://file.infinito.nexus/.../logo.png URLs whenever the source couldn't be downloaded. - New app/utils/asset_resolver.py: HEAD-probes the URL (3 s timeout, image/* content type). On hit, embed directly via a new external_url field — no download required. On miss, fall back to cache_manager.cache_file. If that also fails, expose the source URL via external_url so the browser shows the alt text instead of an empty src. - app.py exposes an asset_src(asset) context processor that picks external_url first, then url_for('static', cache), so the template never wraps an absolute URL in a static prefix. - Templates (base, navigation, card) switch to asset_src(...) and gate the card image branch on cache or external_url. - 16 unit tests cover every probe/cache/fallback branch; one live integration test exercises the canonical https://file.infinito.nexus/assets/img/logo.png to prove the probe-first path works end-to-end (cache dir stays empty). - config.sample.yaml: new Infinito.Nexus card driven by the same canonical asset URL. Single source of truth for IMAGE_NAME and PORT ---------------------------------------------- - env.example is now the only place the literal values live. - Makefile and docker-compose.yml reference \$(IMAGE_NAME) / \${IMAGE_NAME:?…} (same for PORT); no defaults, no silent fallbacks. - New make env / make config bootstrap .env / app/config.yaml from their checked-in templates. Idempotent. - All container-using targets depend on the two bootstrap targets so a fresh checkout runs in a single invocation. - Recipes source .env at recipe-execution time so they pick up a freshly bootstrapped .env in the same make invocation. README ------ - Screenshot added under the title. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 12:19:15 +02:00
"""Resolve every icon/logo/favicon to either a local cache path or
an external URL (see ``resolve_asset_cache``)."""
2025-07-01 23:28:25 +02:00
for card in app.config["cards"]:
feat(assets): probe-first resolver + SPOT for IMAGE_NAME/PORT + README screenshot Probe-first asset resolution (regression fix) --------------------------------------------- cache_manager.cache_file() returned either a relative cache path (success) or None (failure). The previous app.py fallback asset['cache'] = cached or asset['source'] mixed both types into one field, which the template wrapped in url_for('static', ...) regardless — producing broken /static/https://file.infinito.nexus/.../logo.png URLs whenever the source couldn't be downloaded. - New app/utils/asset_resolver.py: HEAD-probes the URL (3 s timeout, image/* content type). On hit, embed directly via a new external_url field — no download required. On miss, fall back to cache_manager.cache_file. If that also fails, expose the source URL via external_url so the browser shows the alt text instead of an empty src. - app.py exposes an asset_src(asset) context processor that picks external_url first, then url_for('static', cache), so the template never wraps an absolute URL in a static prefix. - Templates (base, navigation, card) switch to asset_src(...) and gate the card image branch on cache or external_url. - 16 unit tests cover every probe/cache/fallback branch; one live integration test exercises the canonical https://file.infinito.nexus/assets/img/logo.png to prove the probe-first path works end-to-end (cache dir stays empty). - config.sample.yaml: new Infinito.Nexus card driven by the same canonical asset URL. Single source of truth for IMAGE_NAME and PORT ---------------------------------------------- - env.example is now the only place the literal values live. - Makefile and docker-compose.yml reference \$(IMAGE_NAME) / \${IMAGE_NAME:?…} (same for PORT); no defaults, no silent fallbacks. - New make env / make config bootstrap .env / app/config.yaml from their checked-in templates. Idempotent. - All container-using targets depend on the two bootstrap targets so a fresh checkout runs in a single invocation. - Recipes source .env at recipe-execution time so they pick up a freshly bootstrapped .env in the same make invocation. README ------ - Screenshot added under the title. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 12:19:15 +02:00
icon = card.get("icon")
if icon:
resolve_asset_cache(icon, cache_manager)
2025-07-09 22:20:58 +02:00
feat(assets): probe-first resolver + SPOT for IMAGE_NAME/PORT + README screenshot Probe-first asset resolution (regression fix) --------------------------------------------- cache_manager.cache_file() returned either a relative cache path (success) or None (failure). The previous app.py fallback asset['cache'] = cached or asset['source'] mixed both types into one field, which the template wrapped in url_for('static', ...) regardless — producing broken /static/https://file.infinito.nexus/.../logo.png URLs whenever the source couldn't be downloaded. - New app/utils/asset_resolver.py: HEAD-probes the URL (3 s timeout, image/* content type). On hit, embed directly via a new external_url field — no download required. On miss, fall back to cache_manager.cache_file. If that also fails, expose the source URL via external_url so the browser shows the alt text instead of an empty src. - app.py exposes an asset_src(asset) context processor that picks external_url first, then url_for('static', cache), so the template never wraps an absolute URL in a static prefix. - Templates (base, navigation, card) switch to asset_src(...) and gate the card image branch on cache or external_url. - 16 unit tests cover every probe/cache/fallback branch; one live integration test exercises the canonical https://file.infinito.nexus/assets/img/logo.png to prove the probe-first path works end-to-end (cache dir stays empty). - config.sample.yaml: new Infinito.Nexus card driven by the same canonical asset URL. Single source of truth for IMAGE_NAME and PORT ---------------------------------------------- - env.example is now the only place the literal values live. - Makefile and docker-compose.yml reference \$(IMAGE_NAME) / \${IMAGE_NAME:?…} (same for PORT); no defaults, no silent fallbacks. - New make env / make config bootstrap .env / app/config.yaml from their checked-in templates. Idempotent. - All container-using targets depend on the two bootstrap targets so a fresh checkout runs in a single invocation. - Recipes source .env at recipe-execution time so they pick up a freshly bootstrapped .env in the same make invocation. README ------ - Screenshot added under the title. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 12:19:15 +02:00
resolve_asset_cache(app.config["company"]["logo"], cache_manager)
resolve_asset_cache(app.config["platform"]["favicon"], cache_manager)
resolve_asset_cache(app.config["platform"]["logo"], cache_manager)
2025-07-01 23:28:25 +02:00
2025-01-08 14:59:36 +01:00
2025-07-01 23:28:25 +02:00
# Initialize Flask app
app = Flask(__name__)
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
app.jinja_options = {**app.jinja_options, "autoescape": True}
fix(app): stop trusting X-Forwarded-For, and pin what the audit found ProxyFix defaults x_for to 1, so ProxyFix(app.wsgi_app, x_proto=1) never disabled it: request.remote_addr and the access log were forgeable by any client that reached the app directly. It is x_for=0 now, asserted rather than assumed. A mutation audit over the change set reverted 196 deliberate behaviours and found 47 that no test noticed. This closes the ones that carry damage: - apod_background lost its key check, its transport guard, its status guard and its media-type check without a single test failing. Each one turns a slow or unhappy NASA into a 500 on every page. - Untrusted values reached innerHTML through window.I18N, which the translation backend writes, and the modal's click handlers stacked so a later click opened an earlier popup's URL. - The sync tool could ask for HTML instead of text, translate from "auto" instead of English, run without a timeout, store an empty translation that marks the string done for good, abandon 28 languages because one could not be written, and report success after reaching nothing. - Neither the lint target, the CI jobs, the vendored RTL stylesheet, the documented environment keys, nor any of the four hardenings in scripts/run-e2e.sh was observed by anything. Three of the new tests passed for the wrong reason on their first cut — a mock that answered None whether or not the guard existed, a raise_for_status that was never called, a string that stayed in the file after the mutation. The audit found those too; all 24 reverts now fail. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 10:02:54 +02:00
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=0, x_proto=1)
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
def trusted_hosts(raw):
"""Parse a comma-separated host list, or None when nothing is configured.
Args:
raw: the ``TRUSTED_HOSTS`` value, possibly empty.
"""
hosts = [host.strip() for host in raw.split(",") if host.strip()]
return hosts or None
app.config["TRUSTED_HOSTS"] = trusted_hosts(os.getenv("TRUSTED_HOSTS", ""))
2025-07-01 23:28:25 +02:00
# Load configuration and cache assets on startup
load_config(app)
cache_icons_and_logos(app)
2025-07-07 19:14:29 +02:00
@app.context_processor
def utility_processor():
def include_svg(path):
full_path = os.path.join(current_app.root_path, "static", path)
2025-07-07 19:14:29 +02:00
try:
with open(full_path, "r", encoding="utf-8") as handle:
svg = handle.read()
# Trusted local SVG asset shipped with the application package.
return Markup(svg) # nosec B704
except OSError:
return ""
feat(assets): probe-first resolver + SPOT for IMAGE_NAME/PORT + README screenshot Probe-first asset resolution (regression fix) --------------------------------------------- cache_manager.cache_file() returned either a relative cache path (success) or None (failure). The previous app.py fallback asset['cache'] = cached or asset['source'] mixed both types into one field, which the template wrapped in url_for('static', ...) regardless — producing broken /static/https://file.infinito.nexus/.../logo.png URLs whenever the source couldn't be downloaded. - New app/utils/asset_resolver.py: HEAD-probes the URL (3 s timeout, image/* content type). On hit, embed directly via a new external_url field — no download required. On miss, fall back to cache_manager.cache_file. If that also fails, expose the source URL via external_url so the browser shows the alt text instead of an empty src. - app.py exposes an asset_src(asset) context processor that picks external_url first, then url_for('static', cache), so the template never wraps an absolute URL in a static prefix. - Templates (base, navigation, card) switch to asset_src(...) and gate the card image branch on cache or external_url. - 16 unit tests cover every probe/cache/fallback branch; one live integration test exercises the canonical https://file.infinito.nexus/assets/img/logo.png to prove the probe-first path works end-to-end (cache dir stays empty). - config.sample.yaml: new Infinito.Nexus card driven by the same canonical asset URL. Single source of truth for IMAGE_NAME and PORT ---------------------------------------------- - env.example is now the only place the literal values live. - Makefile and docker-compose.yml reference \$(IMAGE_NAME) / \${IMAGE_NAME:?…} (same for PORT); no defaults, no silent fallbacks. - New make env / make config bootstrap .env / app/config.yaml from their checked-in templates. Idempotent. - All container-using targets depend on the two bootstrap targets so a fresh checkout runs in a single invocation. - Recipes source .env at recipe-execution time so they pick up a freshly bootstrapped .env in the same make invocation. README ------ - Screenshot added under the title. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 12:19:15 +02:00
def template_asset_src(asset):
return asset_src(asset, lambda filename: url_for("static", filename=filename))
return dict(include_svg=include_svg, asset_src=template_asset_src)
2025-07-07 19:14:29 +02:00
2025-01-08 14:59:36 +01:00
@app.before_request
def reload_config_in_dev():
2025-07-01 23:28:25 +02:00
"""Reload config and recache icons before each request in development mode."""
2025-01-09 12:20:57 +01:00
if FLASK_ENV == "development":
load_config(app)
2025-07-01 23:28:25 +02:00
cache_icons_and_logos(app)
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
def translated_config(lang):
"""Return the configuration sections translated into ``lang``, memoized.
The memo is dropped by ``load_config``, so a development reload picks up
edited content on the next request.
"""
memo = app.config["TRANSLATED_CONFIG"]
if lang not in memo:
source = {section: app.config[section] for section in TRANSLATED_SECTIONS}
memo[lang] = i18n.translate_tree(source, lang)
return memo[lang]
def apod_background():
"""Return today's NASA APOD image URL, or None when unavailable."""
2025-07-05 20:08:00 +02:00
api_key = app.config.get("NASA_API_KEY")
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
if not api_key:
return None
try:
2025-07-05 20:08:00 +02:00
resp = requests.get(
"https://api.nasa.gov/planetary/apod",
params={"api_key": api_key},
timeout=10,
2025-07-05 20:08:00 +02:00
)
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
except requests.RequestException:
logging.warning("APOD lookup failed", exc_info=True)
return None
if not resp.ok:
return None
data = resp.json()
return data.get("url") if data.get("media_type") == "image" else None
def render_index(lang):
"""Render the index page in ``lang``."""
config = translated_config(lang)
cards = config["cards"]
lg_classes, md_classes = compute_card_classes(cards)
2025-07-05 20:08:00 +02:00
2025-03-18 14:10:30 +01:00
return render_template(
"pages/index.html.j2",
cards=cards,
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
company=config["company"],
navigation=config["navigation"],
platform=config["platform"],
2025-03-18 14:10:30 +01:00
lg_classes=lg_classes,
2025-07-05 20:08:00 +02:00
md_classes=md_classes,
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
apod_bg=apod_background(),
lang=lang,
lang_dir=i18n.direction(lang),
languages=i18n.LANGUAGES,
ui_strings=i18n.ui_strings(lang),
t=lambda source: i18n.catalog(lang).get(source, source),
2025-03-18 14:10:30 +01:00
)
2025-01-08 14:59:36 +01:00
feat(i18n): serve every page in 30 languages The interface ships translated; page content stays English until a LibreTranslate instance fills app/i18n/content/ through make i18n. A string without a catalogue entry falls back to its English source, so a half-filled catalogue degrades instead of breaking. Translation runs after ConfigurationResolver.resolve_links(), on a copy. resolve_links matches by the `name` field, so translating it beforehand would break every `link:` reference in the configuration. negotiate() normalises to the primary subtag itself. Werkzeug's best_match returns an exact match before it considers a primary-tag fallback, so the Chrome default `de-DE,en;q=0.8` resolves to English there. "/" carries Vary: Accept-Language, without which a shared cache pins the first visitor's language for everyone. The route rule lists the known codes as a converter argument. A bare "/<lang>/" answers /robots.txt and /favicon.ico with a permanently cacheable 308 to their trailing-slash form. Templates gain lang, dir, the RTL stylesheet, a canonical URL and 30 hreflang alternates. Those are the first external URLs in this app: ProxyFix takes the scheme from X-Forwarded-Proto so they do not claim http:// behind a TLS-terminating proxy, X-Forwarded-Host stays untrusted because nginx passes a client-supplied one through, and TRUSTED_HOSTS lets Flask reject a forged Host outright. Flask only autoescapes .html/.htm/.xml/.xhtml/.svg, so every *.html.j2 template interpolated configuration raw. Enabling it changes two lines of the shipped page, both an apostrophe. read_catalog degrades an unreadable catalogue to English rather than serving a 500, and drops non-string entries that would otherwise render as "42". i18n_sync writes atomically, never overwrites an existing entry, refuses to touch a catalogue it could not parse, and leaves the file alone when a run translated nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:02:35 +02:00
@app.route("/")
def index():
"""Render the index page in the language the browser asks for."""
response = make_response(render_index(i18n.negotiate(request.accept_languages)))
response.headers["Vary"] = "Accept-Language"
return response
@app.route(f"/<any({','.join(i18n.LANGUAGES)}):lang>/")
def localized_index(lang):
"""Render the index page in an explicitly requested language."""
return render_index(lang)
2025-01-08 14:59:36 +01:00
if __name__ == "__main__":
app.run(
debug=(FLASK_ENV == "development"),
host=FLASK_HOST,
port=FLASK_PORT,
use_reloader=False,
)