The core speaks English only; every other language is a kind: "translation" plugin
(translation-<lang>; the French one is translation-fr in ai-agent-plugins, seeded once at start).
- plugins: kind translation (typed_manifest.parse_translation: lang, name, englishName, flag,
locale, promptLine, ui/backend JSON dictionaries — strict, operator-only, in the fingerprint);
a top-level "languages" field on any plugin (default ["en"]) shown on its page; seeding takes
translation-*; plugins/translations.py reads the enabled ones (first by id wins a code).
- core/i18n: tr / langs / localized / clean_pref / effective_lang read the installed
translations; a pick whose translation is gone reads English and is kept; browserLang records
any base code. core/i18n_fr.py and FRENCH_LINE are gone (language_line = the plugin's promptLine).
- The owner picks a language too (users.json ownerLang, PUT /api/me {lang}; English by default).
- Public GET /api/i18n/languages and /api/i18n/{lang} (ETag/304), guest host and sign-in included.
- Coverage: backend/core/i18n_keys/{ui,backend}.json (kept by the two i18n tests,
UPDATE_I18N_KEYS=1); a translation's page shows translated / missing / stale / placeholder
mismatches.
- Frontend: frontend/src/i18n/fr removed; the dictionary comes from the hub, cached in
localStorage and revalidated in the background (first boot in a language waits <= 4 s, any
failure is English); Lang is a string; number/currency style from the translation's locale;
LanguageSelect lists English + installed translations (hidden when none); Settings → Plugins
has a Translations kind (tab, catalog filter, group) and a Translation section with the
missing-strings count; mock is English only.
- Tests: test_i18n.py rewritten on a made-up translation; i18n_testkit.speaking() for the
tests that need a second language. authz golden, openapi.json + src/generated regenerated;
docs/plugins.md (Translations), CLAUDE.md, i18n README, docs/settings.md.
Changelog
- Added: languages are plugins — Settings → Plugins → Translations; the owner can pick a language.
- Changed: French moved to the translation-fr plugin (seeded at start: nothing changes for guests).
- Removed: the core's built-in French dictionaries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
135 lines
6.5 KiB
Python
135 lines
6.5 KiB
Python
"""The Content-Security-Policy on the app shell and on the sandbox frame page
|
|
(core/csp.py, main.py's static route) — docs/security.md, the 2026-11-15 pass.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import base64
|
|
import hashlib
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import tempfile
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
STATIC = TMP / "static"
|
|
(STATIC / "assets").mkdir(parents=True)
|
|
REPO = pathlib.Path(__file__).resolve().parent.parent
|
|
THEME = "\n try { document.documentElement.classList.add('dark'); } catch (e) {}\n "
|
|
(STATIC / "index.html").write_text(
|
|
'<!doctype html><html lang="en"><head><title>Claude Agent</title>'
|
|
'<meta name="apple-mobile-web-app-title" content="ai-agent" />'
|
|
f"<script>{THEME}</script>"
|
|
'<script type="module" crossorigin src="/assets/index-abc.js"></script>'
|
|
'</head><body><div id="root"></div></body></html>')
|
|
(STATIC / "assets" / "index-abc.js").write_text("console.log(1)")
|
|
(STATIC / "sandbox-frame.html").write_text(
|
|
(REPO / "frontend" / "public" / "sandbox-frame.html").read_text())
|
|
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"SECURITY_LOG_PATH": TMP / "sec.jsonl", "SECURITY_STATE_PATH": TMP / "sec.json",
|
|
"PROJECTS_DIR": TMP / "projects", "STATIC_DIR": STATIC,
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "guest.example.test",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
(TMP / "projects").mkdir(parents=True)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from core import csp # noqa: E402
|
|
|
|
CSP = "content-security-policy"
|
|
THEME_HASH = "'sha256-" + base64.b64encode(hashlib.sha256(THEME.encode()).digest()).decode() + "'"
|
|
SHELL = f"script-src 'self' {THEME_HASH}; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
|
|
|
|
|
|
class Shell(unittest.TestCase):
|
|
def setUp(self):
|
|
self.owner = TestClient(main.app, base_url="https://admin.example.test")
|
|
self.guest = TestClient(main.app, base_url="https://guest.example.test")
|
|
|
|
def test_the_shell_allows_its_own_scripts_and_the_builds_inline_one(self):
|
|
for path in ("/", "/index.html", "/settings/security", "/c/0190-not-a-file"):
|
|
r = self.owner.get(path)
|
|
self.assertEqual(r.status_code, 200, path)
|
|
self.assertEqual(r.headers[CSP], SHELL, path)
|
|
# nothing that would let an injected script or a javascript: URL run
|
|
for loose in ("unsafe-inline", "unsafe-eval", "data:", "blob:", "*"):
|
|
self.assertNotIn(loose, r.headers[CSP])
|
|
|
|
def test_the_guest_shell_gets_the_same_policy(self):
|
|
from i18n_testkit import speaking
|
|
with speaking("fr"): # a translation for the guest's browser is installed
|
|
r = self.guest.get("/", headers={"Accept-Language": "fr"})
|
|
self.assertEqual(r.headers[CSP], SHELL)
|
|
self.assertIn('<html lang="fr"', r.text) # still the guest's page
|
|
self.assertIn(THEME, r.text) # the hashed script, untouched
|
|
self.assertEqual(self.guest.get("/login").headers[CSP], SHELL)
|
|
|
|
def test_the_policy_follows_a_new_build(self):
|
|
index = STATIC / "index.html"
|
|
old = index.read_text()
|
|
try:
|
|
index.write_text(old.replace("add('dark')", "add('light')"))
|
|
os.utime(index, ns=(index.stat().st_atime_ns, index.stat().st_mtime_ns + 10**9))
|
|
now = self.owner.get("/").headers[CSP]
|
|
self.assertNotEqual(now, SHELL)
|
|
self.assertEqual(now, csp.shell_policy(index.read_text()))
|
|
finally:
|
|
index.write_text(old)
|
|
os.utime(index, ns=(index.stat().st_atime_ns, index.stat().st_mtime_ns + 2 * 10**9))
|
|
self.assertEqual(self.owner.get("/").headers[CSP], SHELL)
|
|
|
|
def test_only_inline_scripts_are_hashed(self):
|
|
self.assertEqual(csp.script_hashes('<script src="/a.js"></script><script type="module" '
|
|
'crossorigin src="/b.js"></script><script> </script>'), [])
|
|
self.assertEqual(csp.script_hashes(f"<SCRIPT>{THEME}</SCRIPT><script>{THEME}</script>"),
|
|
[THEME_HASH])
|
|
# a browser hashes the text after newline normalisation
|
|
self.assertEqual(csp.script_hashes(f"<script>{THEME.replace(chr(10), chr(13) + chr(10))}</script>"),
|
|
[THEME_HASH])
|
|
# the source index.html has exactly the one bootstrap script
|
|
real = (REPO / "frontend" / "index.html").read_text()
|
|
self.assertEqual(len(csp.script_hashes(real)), 1)
|
|
|
|
def test_other_static_files_are_left_alone(self):
|
|
r = self.owner.get("/assets/index-abc.js")
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertNotIn(CSP, r.headers)
|
|
self.assertIn("immutable", r.headers["cache-control"])
|
|
|
|
|
|
class SandboxFrame(unittest.TestCase):
|
|
def test_the_frame_page_is_an_opaque_origin_whoever_loads_it(self):
|
|
for base in ("https://admin.example.test", "https://guest.example.test"):
|
|
r = TestClient(main.app, base_url=base).get("/sandbox-frame.html")
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertIn("text/html", r.headers["content-type"])
|
|
policy = r.headers[CSP]
|
|
self.assertTrue(policy.startswith("sandbox allow-scripts"), policy)
|
|
self.assertNotIn("allow-same-origin", policy)
|
|
self.assertIn("frame-ancestors 'self'", policy)
|
|
self.assertNotIn("script-src", policy) # the author's scripts run there
|
|
self.assertIn('self.origin !== "null"', r.text)
|
|
|
|
def test_header_and_iframe_attribute_carry_the_same_flags(self):
|
|
ts = (REPO / "frontend" / "src" / "lib" / "sandboxFrame.ts").read_text()
|
|
m = re.search(r'export const SANDBOX = "([^"]+)"', ts)
|
|
self.assertIsNotNone(m)
|
|
self.assertEqual(m.group(1), csp.SANDBOX_FLAGS)
|
|
self.assertIn(f'"/{csp.SANDBOX_FRAME}"', ts)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|