Fichiers
loksi/mobile/android/loksi.py
T
Aleop 1c39f76f96 Loksi 2026.10.0 : source correspondante des quatre applis
Export du dépôt interne d'Aleop, révision 0936ea1 (fichiers publiés identiques à e46bc12).
Paquets construits depuis cette source :
- Android : AAB 2026.10.0, code 4
- iPhone : archive 2026.10.0 (18)
- Bureau : macOS universel build 13, Windows build 14, MSIX build 15
- Extensions Chrome, Edge et Firefox : 2026.10.0.3
2026-10-12 17:04:06 +02:00

1719 lignes
100 KiB
Python

#!/usr/bin/env python3
"""Application Android Loksi, adaptée de bitwarden/android. GPL-3.0-only.
Sources amont épinglées dans ../upstream.json. Aucune modification du SDK, de la
cryptographie ni des flux d'authentification : seulement identité, choix du serveur,
écrans d'accueil, liens, ressources et signature.
Usage, depuis n'importe où :
loksi.py fetch archives amont et sources du SDK, empreintes vérifiées
loksi.py sdk SDK Android recompilé depuis sdk-internal, publié dans ~/.m2
loksi.py keys clé de signature debug Loksi, générée en aveugle hors de Git
loksi.py prepare sources Android réextraites puis adaptées
loksi.py build APK fdroid debug signé Loksi, copié dans ../dist/android
loksi.py verify contrôles de l'APK produit, avec canaris
loksi.py upload-key clé d'envoi Google Play, générée en aveugle hors de Git
loksi.py release AAB fdroid release (Play) et APK release d'essai, signés par la clé d'envoi
loksi.py tests tests unitaires app liés à l'adaptation, échecs attendus listés
loksi.py install nouvelle installation (données effacées) sur l'AVD loksi-api36, lancée
"""
import hashlib
import importlib.util
import json
import os
import re
import secrets
import shutil
import subprocess
import sys
import tarfile
import zipfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
MOBILE = HERE.parent
REPO = MOBILE.parent
CACHE = MOBILE / ".cache"
DIST = MOBILE / "dist" / "android"
REPORTS = MOBILE / "reports"
UPSTREAM = json.loads((MOBILE / "upstream.json").read_text())
CONFIG = UPSTREAM["android"]
# Version de Bitwarden adaptée, affichée dans À propos (« Basé sur Bitwarden 2026.9.0 »).
UPSTREAM_VERSION = re.fullmatch(r"v(\d+\.\d+\.\d+)-bwpm", CONFIG["tag"]).group(1)
SERVER = UPSTREAM["server"]
SRC = CACHE / "android-src"
SDK_SRC = CACHE / "sdk-internal-android"
KEYS = Path(os.environ.get("LOKSI_ANDROID_KEYS", Path.home() / ".config/loksi/android"))
ANDROID_HOME = Path(os.environ.get("ANDROID_HOME", Path.home() / "Library/Android/sdk"))
APPLICATION_ID = CONFIG["application_id"]
DEBUG_ID = APPLICATION_ID + ".dev"
COMMERCIAL = re.compile(r"bitwarden-commercial|bitwarden-pam|bitwarden-sm|commercial-marker")
AVD = "loksi-api36"
# Textes et marqueur communs aux deux applis : ios/loksi.py fait foi (décisions de Romain
# du 29/09/2026), l'Android les reprend tels quels.
_spec = importlib.util.spec_from_file_location("loksi_ios", MOBILE / "ios/loksi.py")
IOS = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(IOS)
# Pas de serveur par défaut : loksi.aleop.eu est le coffre d'Aleop, pas celui des clients.
# Tant que rien n'est saisi, l'app vise ce marqueur .invalid, jamais résolu (RFC 6761).
UNSET_SERVER = IOS.UNSET_SERVER
# Chaînes où « Bitwarden » reste. Relevé du 29/09/2026 sur l'APK : aucune n'est affichée
# par l'app Loksi. Le centre d'aide, son invitation et le renvoi de l'enregistreur de vols
# sont passés en Loksi avec les pages d'aide du site. L'invitation aux courriels de Bitwarden
# est sur l'écran d'inscription, que Loksi n'atteint plus. Toutes les autres servent à
# l'app Authenticator ou aux formats d'import, jamais affichées ici. Le reste désigne
# l'application ou le coffre et passe en Loksi, dont le serveur non reconnu, l'app web de
# l'abonnement, l'export vers une autre app et les applications de confiance des passkeys.
KEEP_STRINGS = {
# Écran d'inscription, inaccessible dans Loksi.
"get_emails_from_bitwarden_for_announcements_advices_and_research_opportunities_unsubscribe_any_time",
# Jamais référencées par l'app : Authenticator, formats d'import, carte de téléchargement.
"bitwarden_authenticator", "import_format_label_bitwarden_json", "import_bitwarden_unsupported_format",
"go_to_bitwarden_com_download_to_integrate_bitwarden_into_browser",
"learn_more_about_using_passkeys_with_bitwarden", "secure_your_accounts_with_bitwarden_authenticator",
"learn_more_about_how_to_use_bitwarden_authenticator_on_the_help_center", "data_backup_message",
"download_bitwarden_card_title", "sync_with_bitwarden_app", "shared_codes_error", "sync_with_the_bitwarden_app",
"copy_to_bitwarden_vault", "save_to_bitwarden", "choose_save_location_message", "account_synced_from_bitwarden_app",
}
def run(command, **kwargs):
print("+", " ".join(str(c) for c in command), flush=True)
return subprocess.run([str(c) for c in command], check=True, **kwargs)
def sha256(path):
digest = hashlib.sha256()
with open(path, "rb") as handle:
for block in iter(lambda: handle.read(1 << 20), b""):
digest.update(block)
return digest.hexdigest()
DASHES = re.compile("[\u2013\u2014]")
GENERATOR_SCREEN = "app/src/main/kotlin/com/x8bit/bitwarden/ui/tools/feature/generator/GeneratorScreen.kt"
# Textes de l'amont avec un tiret cadratin, relevés le 09/10/2026 sur la fiche Play
# (« A\u2014Z » du générateur) puis dans les chaînes : règle d'écriture d'Aleop, aucun
# tiret cadratin ni demi-cadratin nulle part dans l'app.
DASH_FIXES = {
"values-fr-rFR/strings.xml": [
("bout à bout</annotation> \u2014 à vous de choisir\u00a0!",
"bout à bout</annotation>, à vous de choisir\u00a0!"),
("peuvent être enregistrés \u2014 jamais d\\\'informations",
"peuvent être enregistrés, mais jamais d\\\'informations"),
("ou continuez \u2014 la mise à jour", "ou continuez : la mise à jour"),
],
"values/strings.xml": [
("one long word</annotation>\u2014your choice!", "one long word</annotation>. Your choice!"),
("may be logged\u2014never sensitive", "may be logged, but never sensitive"),
],
}
def french_fixes():
"""Traductions françaises de l'amont restées en anglais, et tirets cadratins. « Okay »
vu le 09/10/2026 sur le bouton du dialogue de saisie automatique, en ajoutant un
identifiant. Seul le français change : les autres langues gardent leur traduction."""
replace_once(SRC / STRINGS / "values-fr-rFR/strings.xml",
'<string name="okay">Okay</string>', '<string name="okay">OK</string>')
for name, pairs in DASH_FIXES.items():
for old, new in pairs:
replace_once(SRC / STRINGS / name, old, new)
for case in ("A", "a"):
replace_once(SRC / GENERATOR_SCREEN, f'label = "{case}\u2014{case.translate(str.maketrans("Aa", "Zz"))}",',
f'label = "{case}-{case.translate(str.maketrans("Aa", "Zz"))}",')
# Contrôle, avec son canari : un texte qui en porte un doit être vu.
if not DASHES.search("x \u2014 y") or not DASHES.search("x \u2013 y"):
raise RuntimeError("Contrôle des tirets aveugle")
for path in (SRC / STRINGS / "values-fr-rFR/strings.xml", SRC / STRINGS / "values/strings.xml",
SRC / STRINGS / "values/strings_non_localized.xml", SRC / GENERATOR_SCREEN):
found = DASHES.findall(path.read_text())
if found:
raise RuntimeError(f"Tiret cadratin restant : {path.relative_to(SRC)} ({len(found)})")
def replace_once(path, old, new, count=1):
value = path.read_text()
if value.count(old) != count:
raise RuntimeError(f"Point d'adaptation amont modifié : {path.relative_to(SRC)} "
f"({value.count(old)} au lieu de {count})")
path.write_text(value.replace(old, new))
def java_home():
home = subprocess.run(["/usr/libexec/java_home", "-v", CONFIG["toolchain"]["jdk"]],
capture_output=True, text=True, check=True).stdout.strip()
# java_home -v retombe en silence sur une autre version si la bonne manque :
# on lit la version réelle. Vérifié le 28/09/2026, -v 17 rend un JDK 26.
version = subprocess.run([home + "/bin/java", "-version"], capture_output=True, text=True).stderr
if f'version "{CONFIG["toolchain"]["jdk"]}.' not in version:
raise RuntimeError(f"JDK {CONFIG['toolchain']['jdk']} introuvable, java_home rend : {home}")
return home
def tool_env():
rustup = "/opt/homebrew/opt/rustup/bin"
env = dict(os.environ, JAVA_HOME=java_home(), ANDROID_HOME=str(ANDROID_HOME),
ANDROID_NDK_HOME=str(ANDROID_HOME / "ndk" / CONFIG["toolchain"]["ndk"]),
LOKSI_ANDROID_KEYS=str(KEYS),
PATH=os.pathsep.join([rustup, str(Path.home() / ".cargo/bin"), os.environ["PATH"]]))
env.pop("GITHUB_TOKEN", None)
return env
def fetch():
CACHE.mkdir(exist_ok=True)
archive = CACHE / "android.tar.gz"
if not archive.exists():
run(["curl", "-fsSL", "-o", archive, CONFIG["archive_url"]])
if sha256(archive) != CONFIG["archive_sha256"]:
raise RuntimeError("Archive Android amont incorrecte : SHA-256 différent")
for key, name in (("url", "Raleway-wght.ttf"), ("italic_url", "Raleway-Italic-wght.ttf")):
font = CACHE / name
if not font.exists():
run(["curl", "-fsSL", "-o", font, UPSTREAM["font"][key]])
if sha256(font) != UPSTREAM["font"][key.replace("url", "sha256")]:
raise RuntimeError(f"{name} incorrecte : SHA-256 différent")
sdk = CONFIG["sdk"]
if not SDK_SRC.exists():
# Clone git au commit exact, sur une branche main : la publication amont lit
# la branche pour nommer l'artefact (sdk-android sur main, sdk-android.dev
# ailleurs) et git rev-parse HEAD pour sa description.
SDK_SRC.mkdir()
run(["git", "init", "-q"], cwd=SDK_SRC)
run(["git", "fetch", "-q", "--depth", "1", sdk["source_repository"], sdk["source_commit"]], cwd=SDK_SRC)
run(["git", "checkout", "-q", "-B", "main", "FETCH_HEAD"], cwd=SDK_SRC)
head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=SDK_SRC, capture_output=True, text=True).stdout.strip()
if head != sdk["source_commit"]:
raise RuntimeError(f"sdk-internal au mauvais commit : {head}")
dirty = subprocess.run(["git", "status", "--porcelain", "--untracked-files=no"], cwd=SDK_SRC,
capture_output=True, text=True).stdout
if dirty.strip():
raise RuntimeError("sdk-internal modifié localement :\n" + dirty)
print(f"Sources vérifiées : android {CONFIG['tag']}, sdk-internal {head}")
def sdk_tree(env, features=()):
command = ["rustup", "run", CONFIG["sdk"]["rust_toolchain"], "cargo", "tree", "-p", "bitwarden-uniffi",
"--target", "aarch64-linux-android", "-e", "normal", "--prefix", "none"]
for feature in features:
command += ["-F", feature]
output = subprocess.run(command, cwd=SDK_SRC, env=env, capture_output=True, text=True, check=True).stdout
return sorted(set(output.splitlines()))
def sdk():
fetch()
env = tool_env()
tree = sdk_tree(env)
if any(COMMERCIAL.search(line) for line in tree):
raise RuntimeError("Crate sous licence Bitwarden dans le graphe du SDK")
# Canari : la même commande, fonctionnalité commerciale forcée, DOIT en trouver.
if not any(COMMERCIAL.search(line) for line in sdk_tree(env, ["bitwarden-pm/bitwarden-license"])):
raise RuntimeError("Canari du graphe SDK muet : le contrôle ne voit rien")
REPORTS.mkdir(exist_ok=True)
(REPORTS / "android-sdk-crates.txt").write_text("\n".join(tree) + "\n")
toolchain = CONFIG["sdk"]["rust_toolchain"]
run(["rustup", "run", toolchain, "cargo", "ndk", "-t", "arm64-v8a", "-P", str(CONFIG["toolchain"]["min_sdk"]),
"build", "-p", "bitwarden-uniffi", "--release"], cwd=SDK_SRC, env=env)
kotlin = SDK_SRC / "crates/bitwarden-uniffi/kotlin"
libs = kotlin / "sdk/src/main/jniLibs/arm64-v8a"
libs.mkdir(parents=True, exist_ok=True)
library = libs / "libbitwarden_uniffi.so"
shutil.copy2(SDK_SRC / "target/aarch64-linux-android/release/libbitwarden_uniffi.so", library)
run(["rustup", "run", toolchain, "bash", "./build-schemas.sh"], cwd=kotlin, env=env)
(kotlin / "local.properties").write_text(f"sdk.dir={ANDROID_HOME}\n")
run(["./gradlew", "--no-daemon", "sdk:publishToMavenLocal", "-Pversion=LOCAL"], cwd=kotlin, env=env)
aar = Path.home() / ".m2/repository/com/bitwarden/sdk-android/LOCAL/sdk-android-LOCAL.aar"
if not aar.is_file():
raise RuntimeError(f"AAR du SDK absent : {aar}")
with zipfile.ZipFile(aar) as archive:
embedded = archive.read("jni/arm64-v8a/libbitwarden_uniffi.so")
if hashlib.sha256(embedded).hexdigest() != sha256(library):
raise RuntimeError("La bibliothèque de l'AAR n'est pas celle qui vient d'être compilée")
report = {"sdk_internal_commit": CONFIG["sdk"]["source_commit"], "crates": len(tree),
"libbitwarden_uniffi_arm64_sha256": sha256(library), "aar_sha256": sha256(aar)}
(REPORTS / "android-sdk.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
# Clés de signature Loksi, hors de Git (droits 700 et 600). debug : APK d'essai. upload : clé
# d'envoi Google Play (Play App Signing garde la clé de signature finale chez Google), RSA
# 4096 valable 30 ans, Play exige une validité au-delà de 2033. Le mot de passe est écrit en
# aveugle dans son fichier et n'en sort jamais : keytool, jarsigner et apksigner le lisent
# par :file, aucun argument ne le porte, aucun message d'erreur brut n'est affiché.
SIGNING = {
"debug": {"alias": "loksi-debug", "keysize": "3072", "dname": "CN=Loksi debug, O=Aleop, C=FR"},
"upload": {"alias": "loksi-upload", "keysize": "4096", "dname": "CN=Loksi, O=Aleop, C=FR"},
}
def make_key(kind):
KEYS.mkdir(parents=True, exist_ok=True)
os.chmod(KEYS, 0o700)
password, store = KEYS / f"{kind}.pass", KEYS / f"{kind}.p12"
if not store.exists():
try:
fd = os.open(password, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as handle:
handle.write(secrets.token_urlsafe(32))
keytool = Path(java_home()) / "bin/keytool"
result = subprocess.run([keytool, "-genkeypair", "-keystore", store, "-storetype", "PKCS12",
"-alias", SIGNING[kind]["alias"], "-keyalg", "RSA",
"-keysize", SIGNING[kind]["keysize"], "-validity", "10950",
"-dname", SIGNING[kind]["dname"],
"-storepass:file", password, "-keypass:file", password],
capture_output=True)
if result.returncode:
raise RuntimeError("keytool a échoué")
os.chmod(store, 0o600)
except Exception as error: # le message brut pourrait citer un argument
sys.exit(f"Génération de la clé {kind} interrompue : {type(error).__name__}")
print("SHA-256 du fichier de mot de passe :", sha256(password))
print("Certificat SHA-256 :", certificate_digest(kind))
def keys():
"""Clé debug Loksi."""
make_key("debug")
def upload_key():
"""Clé d'envoi Google Play. À sauvegarder hors du poste : sans elle, il faut demander à
Google de la réinitialiser."""
make_key("upload")
def certificate_digest(kind="debug"):
keytool = Path(java_home()) / "bin/keytool"
result = subprocess.run([keytool, "-J-Duser.language=en", "-list", "-v", "-keystore", KEYS / f"{kind}.p12",
"-storetype", "PKCS12", "-alias", SIGNING[kind]["alias"],
"-storepass:file", KEYS / f"{kind}.pass"],
capture_output=True, text=True)
match = re.search(r"SHA[- ]?256:\s*([0-9A-F:]{95})", result.stdout)
if result.returncode or not match:
raise RuntimeError(f"Empreinte du certificat {kind} illisible")
return match.group(1).replace(":", "").lower()
def adapt_strings():
changed = 0
english = SRC / "ui/src/main/res/values/strings.xml"
names = set(re.findall(r'<string name="([^"]+)"', english.read_text()))
names |= set(re.findall(r'<string name="([^"]+)"', (SRC / "ui/src/main/res/values/strings_non_localized.xml").read_text()))
missing = sorted(KEEP_STRINGS - names)
if missing:
raise RuntimeError("Chaînes amont renommées : " + ", ".join(missing))
pattern = re.compile(r'(<string name="([^"]+)"[^>]*>)(.*?)(</string>)', re.S)
for path in sorted((SRC / "ui/src/main/res").glob("values*/strings*.xml")):
text = path.read_text()
def rename(match):
nonlocal changed
if match.group(2) in KEEP_STRINGS or "Bitwarden" not in match.group(3):
return match.group(0)
changed += 1
return match.group(1) + match.group(3).replace("Bitwarden", "Loksi") + match.group(4)
text = pattern.sub(rename, text)
def rename_plural(match):
nonlocal changed
if match.group(2) in KEEP_STRINGS or "Bitwarden" not in match.group(3):
return match.group(0)
changed += 1
return match.group(1) + match.group(3).replace("Bitwarden", "Loksi") + match.group(4)
path.write_text(re.sub(r'(<plurals name="([^"]+)"[^>]*>)(.*?)(</plurals>)', rename_plural, text, flags=re.S))
for variant, name in (("main", "Loksi"), ("release", "Loksi"), ("beta", "Loksi Beta")):
path = SRC / f"app/src/{variant}/res/values/strings_non_localized.xml"
value = path.read_text()
new, count = re.subn(r'(<string name="app_name" translatable="false">)[^<]*(</string>)',
r"\g<1>" + name + r"\g<2>", value)
if count != 1:
raise RuntimeError(f"app_name amont modifié : {variant}")
path.write_text(new)
if changed < 50:
raise RuntimeError(f"Seulement {changed} chaînes renommées, l'amont a changé")
return changed
# Palette Loksi, même correspondance que l'iOS et le coffre web
# (habillage user.vaultwarden.scss.hbs de Loksi web) : le bleu Bitwarden devient le
# navy en clair et le cyan en sombre, les fonds teintés #E5EEF9 et #0A3D58. Neutres,
# couleurs d'état, badges et illustrations restent amont.
THEME = "ui/src/main/kotlin/com/bitwarden/ui/platform/theme/color/ColorScheme.kt"
# Primitives employées dans un seul mode (relevé le 29/09/2026 sur le tag) : blue500
# en clair (texte, boutons, bordures), blue400 en sombre, blue100 en clair (fonds teintés).
PRIMITIVES = {"blue100": ("DBE5F6", "E5EEF9"), "blue400": ("65ABFF", "009CDE"), "blue500": ("175DDC", "003087")}
# Emplois de blue500 en sombre et fond d'alerte clair : repris un par un.
SCHEME_USES = [
("dark", " navActiveAccent = PrimitiveColors.blue500,", " navActiveAccent = Color(color = 0xFF0A3D58),"),
("dark", " outline = PrimitiveColors.blue500,", " outline = PrimitiveColors.blue400,"),
("light", " alert = PrimitiveColors.blue700,", " alert = Color(color = 0xFF002260),"),
]
# Couples premier plan sur fond à tenir au-dessus du seuil WCAG AA, après correspondance.
CONTRAST = [("text.interaction", "background.primary", 4.5), ("text.interaction", "background.secondary", 4.5),
("filledButton.foreground", "filledButton.background", 4.5),
("outlineButton.foreground", "background.secondary", 4.5),
("icon.secondary", "icon.navActiveAccent", 3.0), ("text.reversed", "background.alert", 4.5)]
def luminance(value):
def linear(c):
c /= 255
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
r, g, b = (int(value[i:i + 2], 16) for i in (0, 2, 4))
return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)
def scheme_colors(text):
"""Couleur de chaque rôle (section.champ) des schémas clair et sombre."""
primitives = dict(re.findall(r"val (\w+): Color = Color\(color = 0xFF([0-9A-F]{6})\)", text))
roles = {}
for mode in ("dark", "light"):
block = text.split(f"val {mode}BitwardenColorScheme")[1].split("\n)\n")[0]
section = None
for line in block.splitlines():
opened = re.match(r"\s+(\w+) = BitwardenColorScheme\.\w+\($", line)
if opened:
section = opened.group(1)
continue
value = re.match(r"\s+(\w+) = (?:PrimitiveColors\.(\w+)|Color\(color = 0xFF([0-9A-F]{6})\)),$", line)
if value and section:
roles[(mode, f"{section}.{value.group(1)}")] = primitives.get(value.group(2)) or value.group(3)
return roles
def adapt_colors():
path = SRC / THEME
text = path.read_text()
for name, (old, new) in PRIMITIVES.items():
line = f" val {name}: Color = Color(color = 0xFF{old})"
if text.count(line) != 1:
raise RuntimeError(f"Primitive amont modifiée : {name}")
text = text.replace(line, f" val {name}: Color = Color(color = 0xFF{new})")
for mode, old, new in SCHEME_USES:
head, rest = text.split(f"val {mode}BitwardenColorScheme")
block, tail = rest.split("\n)\n", 1)
if block.count(old) != 1:
raise RuntimeError(f"Emploi amont modifié ({mode}) : {old.strip()}")
text = head + f"val {mode}BitwardenColorScheme" + block.replace(old, new) + "\n)\n" + tail
path.write_text(text)
roles = scheme_colors(text)
if len(roles) < 100:
raise RuntimeError(f"Schéma de couleurs illisible : {len(roles)} rôles")
# Canari : l'amont contient bien un couple sous 4,5:1, que le calcul doit voir.
upstream = scheme_colors(tarfile.open(CACHE / "android.tar.gz").extractfile(
f"android-{CONFIG['tag'].lstrip('v')}/{THEME}").read().decode())
ratios = {}
for colors in (upstream, roles):
for fore, back, minimum in CONTRAST:
for mode in ("light", "dark"):
a, b = sorted((luminance(colors[(mode, fore)]), luminance(colors[(mode, back)])))
ratios[(colors is roles, fore, back, mode)] = ((b + 0.05) / (a + 0.05), minimum)
if all(r >= m for (loksi, *_), (r, m) in ratios.items() if not loksi):
raise RuntimeError("Canari de contraste muet : l'amont passe partout")
failing = [f"{f} sur {b} ({m}) : {r:.2f}" for (loksi, f, b, m), (r, minimum) in ratios.items()
if loksi and r < minimum]
if failing:
raise RuntimeError("Contrastes insuffisants : " + ", ".join(failing))
for (loksi, f, b, m), (r, _) in sorted(ratios.items()):
if loksi:
print(f" contraste {f} sur {b} ({m}) : {r:.2f}")
return len(PRIMITIVES) + len(SCHEME_USES)
# DM Sans remplacée par la police Loksi (instances de Raleway, ios/fonts.py) sous les
# noms de ressource amont : Typography.kt et ses deux voisins restent intacts. Le
# fichier medium sert des styles déclarés en 600 : il reçoit le 600. L'amont Android
# n'emploie aucune italique, il n'en embarque pas.
FONTS = {"dm_sans_regular": "Loksi-Regular", "dm_sans_medium": "Loksi-SemiBold",
"dm_sans_semi_bold": "Loksi-SemiBold", "dm_sans_bold": "Loksi-Bold"}
def adapt_fonts():
out = CACHE / "android-fonts"
if out.exists():
shutil.rmtree(out)
python = CACHE / "venv/bin/python"
run([python, MOBILE / "ios/fonts.py", CACHE / "Raleway-wght.ttf", CACHE / "Raleway-Italic-wght.ttf", out])
fonts = SRC / "ui/src/main/res/font"
upstream = sorted(p.stem for p in fonts.glob("dm_sans_*.ttf"))
if upstream != sorted(FONTS):
raise RuntimeError(f"Polices amont inattendues : {upstream}")
for resource, instance in FONTS.items():
shutil.copy2(out / f"{instance}.ttf", fonts / f"{resource}.ttf")
return len(FONTS)
APP = "app/src/main/kotlin/com/x8bit/bitwarden"
STRINGS = "ui/src/main/res"
ENV_EXTENSIONS = "data/src/main/kotlin/com/bitwarden/data/repository/util/EnvironmentUrlDataJsonExtensions.kt"
def android_text(value):
"""Valeur de ressource Android : XML échappé, apostrophes et guillemets protégés."""
value = value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
return value.replace("\\", "\\\\").replace("'", "\\'").replace('"', '\\"').replace("\n", "\\n")
def language(path):
"""fr pour values-fr-rFR, en pour le défaut et toutes les autres langues."""
return "fr" if path.parent.name == "values-fr-rFR" else "en"
def set_strings(texts, required=("values", "values-fr-rFR")):
"""Remplace la valeur des chaînes {nom: {fr, en}} dans chaque langue qui les porte.
Le défaut et le français doivent toutes les porter : une langue qui en manque retombe
sur le défaut, donc sur l'anglais Loksi."""
replaced = 0
for path in sorted((SRC / STRINGS).glob("values*/strings.xml")):
text = path.read_text()
for name, messages in texts.items():
pattern = re.compile(r'(<string name="' + name + r'"[^>]*>)(.*?)(</string>)', re.S)
value = android_text(messages[language(path)])
text, count = pattern.subn(lambda m: m.group(1) + value + m.group(3), text)
if count > 1 or (count == 0 and path.parent.name in required):
raise RuntimeError(f"{name} : {count} dans {path.parent.name}")
replaced += count
path.write_text(text)
return replaced
def add_strings(texts):
"""Chaînes propres à Loksi, en anglais par défaut et en français."""
for folder in ("values", "values-fr-rFR"):
path = SRC / STRINGS / folder / "strings.xml"
text = path.read_text()
lines = ""
for name, messages in texts.items():
if f'name="{name}"' in text:
raise RuntimeError(f"Chaîne Loksi déjà présente dans l'amont : {name}")
lines += f' <string name="{name}">{android_text(messages[language(path)])}</string>\n'
if text.count("</resources>") != 1:
raise RuntimeError(f"Fin de ressources amont modifiée : {folder}")
path.write_text(text.replace("</resources>", lines + "</resources>"))
def unset_server():
"""Aucun serveur quand rien n'est enregistré : le marqueur, présenté comme « adresse à
saisir ». La restriction gérée baseEnvironmentUrl (MDM), le compte actif et le choix de
l'utilisateur passent avant, comme en amont."""
host = UNSET_SERVER.split("://", 1)[1]
replace_once(SRC / ENV_EXTENSIONS,
" this?.toEnvironmentUrls() ?: Environment.Prod.Us",
" this?.toEnvironmentUrls()\n"
" ?: Environment.SelfHosted(environmentUrlData = EnvironmentUrlDataJson(base = LOKSI_UNSET_SERVER))\n"
"\n"
"/**\n"
" * Loksi: host of the address that stands for \"no vault address entered yet\". The .invalid\n"
" * domain is reserved and never resolves: no server is contacted.\n"
" */\n"
f"const val LOKSI_UNSET_HOST: String = {json.dumps(host)}\n"
"\n"
"/**\n"
" * Loksi: no default server, this address stands for \"not entered yet\".\n"
" */\n"
"const val LOKSI_UNSET_SERVER: String = \"https://$LOKSI_UNSET_HOST\"\n"
"\n"
"/**\n"
" * Loksi: whether no vault address has been entered yet.\n"
" */\n"
"val EnvironmentUrlDataJson.isLoksiUnset: Boolean\n"
" get() = base == LOKSI_UNSET_SERVER")
# Le test amont du défaut suit le nouveau défaut, il n'est pas désactivé.
replace_once(SRC / "data/src/test/kotlin/com/bitwarden/data/repository/util/EnvironmentUrlsDataJsonExtensionsTest.kt",
""" fun `toEnvironmentUrlsOrDefault should convert null types to US values`() {
assertEquals(
Environment.Prod.Us,""",
""" fun `toEnvironmentUrlsOrDefault should convert null types to the Loksi unset marker`() {
assertEquals(
Environment.SelfHosted(environmentUrlData = EnvironmentUrlDataJson(base = LOKSI_UNSET_SERVER)),""")
# Choix du serveur : pas de bitwarden.com, bitwarden.eu ni auto-hébergé, le client saisit
# l'adresse de son coffre. « Connexion sur » affiche cette adresse et ouvre directement la
# saisie ; sans adresse, « Continuer » ouvre la saisie. Demande de Romain le 29/09/2026,
# comme iOS. Les régions restent dans le code amont.
def server_entry():
selector = SRC / APP / "ui/platform/components/dropdown/EnvironmentSelector.kt"
replace_once(selector, " onClick = { shouldShowDialog = !shouldShowDialog },\n",
" // Loksi: no region list, the vault address is entered directly.\n"
" onClick = { onOptionSelected(Environment.Type.SELF_HOSTED) },\n")
replace_once(selector, " isHelpEnabled: Boolean = true,\n) {",
" isHelpEnabled: Boolean = true,\n selectedLabel: String? = null,\n) {")
replace_once(selector, " * @param isHelpEnabled Indicates if the help button should be available.\n",
" * @param isHelpEnabled Indicates if the help button should be available.\n"
" * @param selectedLabel Loksi: the server address shown instead of the region name.\n")
replace_once(selector, " text = selectedOption.displayLabel(),",
" text = selectedLabel ?: selectedOption.displayLabel(),")
screen = SRC / APP / "ui/auth/feature/landing/LandingScreen.kt"
replace_once(screen, "import com.bitwarden.data.repository.model.Environment\n",
"import com.bitwarden.data.repository.model.Environment\n"
"import com.bitwarden.data.repository.util.LOKSI_UNSET_HOST\n")
replace_once(screen, " selectedOption = state.selectedEnvironmentType,\n",
" selectedOption = state.selectedEnvironmentType,\n"
" selectedLabel = state.selectedEnvironmentLabel\n"
" .takeUnless { it == LOKSI_UNSET_HOST }\n"
" ?: stringResource(id = BitwardenString.loksi_vault_address_to_enter),\n")
model = SRC / APP / "ui/auth/feature/landing/LandingViewModel.kt"
replace_once(model, "import com.bitwarden.data.repository.model.Environment\n",
"import com.bitwarden.data.repository.model.Environment\n"
"import com.bitwarden.data.repository.util.isLoksiUnset\n")
replace_once(model, """ private fun handleContinueButtonClicked() {
if (""", """ private fun handleContinueButtonClicked() {
if (environmentRepository.environment.environmentUrlData.isLoksiUnset) {
// Loksi: no vault address yet, ask for it first.
sendEvent(LandingEvent.NavigateToEnvironment)
return
}
if (""")
environment = SRC / APP / "ui/auth/feature/environment/EnvironmentViewModel.kt"
replace_once(environment, "import com.bitwarden.data.repository.model.Environment\n",
"import com.bitwarden.data.repository.model.Environment\n"
"import com.bitwarden.data.repository.util.isLoksiUnset\n")
# Le marqueur « pas encore saisi » s'affiche comme un champ vide.
replace_once(environment, " is Environment.SelfHosted -> environment.environmentUrlData\n",
" is Environment.SelfHosted -> environment.environmentUrlData\n"
" .takeUnless { it.isLoksiUnset }\n"
" ?: EnvironmentUrlDataJson(base = \"\")\n")
names = {"SelfHostedEnvironment": "self_hosted_environment",
"SelfHostedEnvironmentFooter": "self_hosted_environment_footer"}
return set_strings({name: IOS.SERVER_STRINGS[key] for key, name in names.items()})
# Nom ou adresse du coffre (décision de Romain du 04/10/2026, même règle que l'extension,
# extensions/loksi-coffre.ts) : un nom de 2 à 20 caractères donne https://<nom>.loksi.fr,
# sinon une adresse complète en https. Avant d'enregistrer, /api/config doit répondre
# « Vaultwarden », sinon « Aucun coffre Loksi ne répond à cette adresse ». La logique vit
# dans android/kotlin/LoksiVault.kt, copié dans le module data et testé seul
# (LoksiVaultTest.kt, canaris compris). Tant que rien n'est saisi, « Pas encore client ?
# Découvrir Loksi » mène à la page produit.
LOKSI_PRODUCT = "https://www.aleop.eu/loksi/"
LOKSI_KOTLIN = {"LoksiVault.kt": "data/src/main/kotlin/com/bitwarden/data/repository/util/LoksiVault.kt",
"LoksiVaultTest.kt": "data/src/test/kotlin/com/bitwarden/data/repository/util/LoksiVaultTest.kt"}
VAULT_TEXTS = {
"loksi_vault_name_or_address": {"fr": "Nom ou adresse de votre coffre", "en": "Name or address of your vault"},
"loksi_vault_placeholder": {"fr": "ex. mon-entreprise", "en": "e.g. my-company"},
"loksi_vault_address_invalid": {
"fr": "Saisissez le nom de votre coffre, choisi à la commande : 2 à 20 minuscules ou chiffres, "
"un tiret possible. Ou une adresse complète qui commence par https://.",
"en": "Enter the name of your vault, chosen when ordering: 2 to 20 lowercase letters or digits, "
"a hyphen allowed. Or a full address starting with https://.",
},
"loksi_not_a_vault": {
"fr": "Aucun coffre Loksi ne répond à cette adresse. Vérifiez le nom auprès de votre administrateur.",
"en": "No Loksi vault answers at this address. Check the name with your administrator.",
},
"loksi_discover_loksi": {"fr": "Pas encore client ? Découvrir Loksi", "en": "Not a customer yet? Discover Loksi"},
}
# Aide sous le champ : celle de l'extension, qui montre le nom et l'adresse obtenue.
VAULT_FOOTER = {
"fr": "Saisissez le nom de votre coffre, par exemple mon-entreprise pour https://mon-entreprise.loksi.fr, "
"ou son adresse complète. Votre administrateur vous le donne.",
"en": "Enter the name of your vault, for example my-company for https://my-company.loksi.fr, "
"or its full address. Your administrator gives it to you.",
}
def vault_name_entry():
for name, relative in LOKSI_KOTLIN.items():
target = SRC / relative
if target.exists():
raise RuntimeError(f"Fichier Loksi déjà présent dans l'amont : {relative}")
shutil.copy2(HERE / "kotlin" / name, target)
model = SRC / APP / "ui/auth/feature/environment/EnvironmentViewModel.kt"
replace_once(model, "import com.bitwarden.data.repository.util.isLoksiUnset\n",
"import com.bitwarden.data.repository.util.isLoksiUnset\n"
"import com.bitwarden.data.repository.util.isLoksiVault\n"
"import com.bitwarden.data.repository.util.loksiVaultAddress\n")
replace_once(model, """ private fun handleSaveClickAction() {
val urlsAreAllNullOrValid = listOf(""", """ private fun handleSaveClickAction() {
// Loksi: a vault name gives https://<name>.loksi.fr, a full address must be https,
// and a Vaultwarden must answer on /api/config before anything is saved.
val loksiBase = loksiVaultAddress(state.serverUrl)
if (loksiBase == null) {
showErrorDialog(message = BitwardenString.loksi_vault_address_invalid.asText())
return
}
viewModelScope.launch {
if (isLoksiVault(loksiBase)) {
mutableStateFlow.update { it.copy(serverUrl = loksiBase) }
saveLoksiEnvironment()
} else {
showErrorDialog(message = BitwardenString.loksi_not_a_vault.asText())
}
}
}
private fun saveLoksiEnvironment() {
val urlsAreAllNullOrValid = listOf(""")
screen = SRC / APP / "ui/auth/feature/environment/EnvironmentScreen.kt"
replace_once(screen, """ label = stringResource(id = BitwardenString.server_url),
value = state.serverUrl,
placeholder = "ex. https://bitwarden.company.com",""",
""" label = stringResource(id = BitwardenString.loksi_vault_name_or_address),
value = state.serverUrl,
placeholder = stringResource(id = BitwardenString.loksi_vault_placeholder),""")
landing = SRC / APP / "ui/auth/feature/landing/LandingScreen.kt"
replace_once(landing, "import androidx.compose.ui.text.style.TextAlign\n",
"import androidx.compose.ui.text.style.TextAlign\nimport androidx.core.net.toUri\n")
replace_once(landing, "import com.bitwarden.ui.platform.components.button.BitwardenTextButton\n",
"import com.bitwarden.ui.platform.components.button.BitwardenTextButton\n"
"import com.bitwarden.ui.platform.composition.LocalIntentManager\n")
replace_once(landing, """ .standardHorizontalMargin()
.fillMaxWidth(),
)
Spacer(modifier = Modifier.height(height = 8.dp))
""", f""" .standardHorizontalMargin()
.fillMaxWidth(),
)
if (state.selectedEnvironmentLabel == LOKSI_UNSET_HOST) {{
// Loksi: no vault entered yet, a link for whoever is not a customer yet.
val loksiIntentManager = LocalIntentManager.current
BitwardenTextButton(
label = stringResource(id = BitwardenString.loksi_discover_loksi),
onClick = {{ loksiIntentManager.launchUri("{LOKSI_PRODUCT}".toUri()) }},
modifier = Modifier
.standardHorizontalMargin()
.fillMaxWidth(),
)
}}
Spacer(modifier = Modifier.height(height = 8.dp))
""")
add_strings(VAULT_TEXTS)
return set_strings({"self_hosted_environment_footer": VAULT_FOOTER})
# Pas de création de compte dans l'app : un compte Loksi est créé par l'administrateur de
# l'entreprise (invitation ou SSO). Décision de Romain le 29/09/2026, comme iOS, quel que
# soit le réglage d'inscription du serveur.
def hide_registration():
welcome = SRC / APP / "ui/auth/feature/welcome/WelcomeScreen.kt"
replace_once(welcome, """ AnimatedVisibility(
visible = state.allowCreateAccount,
label = "CreateAccountAnimatedVisibility",
) {
BitwardenFilledButton(
label = stringResource(id = BitwardenString.create_account),
onClick = onCreateAccountClick,
modifier = Modifier
.standardHorizontalMargin(medium = HORIZONTAL_MARGIN_MEDIUM)
.fillMaxWidth()
.testTag("ChooseAccountCreationButton"),
)
}
BitwardenOutlinedButton(
label = stringResource(id = BitwardenString.log_in_verb),""", """ BitwardenFilledButton(
label = stringResource(id = BitwardenString.log_in_verb),""")
landing = SRC / APP / "ui/auth/feature/landing/LandingScreen.kt"
replace_once(landing, """ AnimatedVisibility(
visible = state.allowCreateAccount,
label = "CreateAccountAnimatedVisibility",
) {
Column {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.standardHorizontalMargin()
.fillMaxWidth()
.wrapContentHeight(),
) {
Text(
text = stringResource(id = BitwardenString.new_to_bitwarden),
style = BitwardenTheme.typography.bodyMedium,
color = BitwardenTheme.colorScheme.text.secondary,
)
BitwardenTextButton(
label = stringResource(id = BitwardenString.create_an_account),
onClick = onCreateAccountClick,
modifier = Modifier
.testTag("CreateAccountLabel"),
)
}
Spacer(modifier = Modifier.height(height = 8.dp))
}
}
""", """ Text(
text = stringResource(id = BitwardenString.loksi_account_created_by_administrator),
textAlign = TextAlign.Center,
style = BitwardenTheme.typography.bodyMedium,
color = BitwardenTheme.colorScheme.text.secondary,
modifier = Modifier
.standardHorizontalMargin()
.fillMaxWidth(),
)
Spacer(modifier = Modifier.height(height = 8.dp))
""")
add_strings({"loksi_account_created_by_administrator": IOS.ADMIN_MESSAGE,
"loksi_vault_address_to_enter": IOS.VAULT_ADDRESS_TO_ENTER, **contact_texts(),
"loksi_origin_notice": ORIGIN_NOTICE})
# Carrousel d'accueil : les textes Loksi d'iOS, validés par Romain le 29/09/2026, français
# pour fr et anglais pour toutes les autres langues. Une seule retouche : Face ID n'existe
# pas sur Android, la page 2 parle du déverrouillage biométrique.
CAROUSEL_KEYS = {
"IntroCarouselPage1Title": "security_prioritized", "IntroCarouselPage1Message": "welcome_message_1",
"IntroCarouselPage2Title": "quick_and_easy_login", "IntroCarouselPage2Message": "welcome_message_2",
"IntroCarouselPage3Title": "level_up_your_logins", "IntroCarouselPage3Message": "welcome_message_3",
"IntroCarouselPage4Title": "your_data_when_and_where_you_need_it", "IntroCarouselPage4Message": "welcome_message_4",
}
ANDROID_PAGE_2 = {"fr": "Le déverrouillage biométrique et le remplissage automatique ouvrent vos comptes sans rien taper.",
"en": "Biometric unlock and autofill open your accounts without typing anything."}
def adapt_carousel():
texts = {}
for ios_key, name in CAROUSEL_KEYS.items():
texts[name] = {language: IOS.CAROUSEL[language][ios_key] for language in ("fr", "en")}
if any("Face ID" in texts["welcome_message_2"][language] for language in ("fr", "en")):
texts["welcome_message_2"] = ANDROID_PAGE_2
else:
raise RuntimeError("Carrousel iOS changé : la retouche Face ID de la page 2 est à revoir")
return set_strings(texts)
# Mention d'origine d'À propos, validée par Romain le 30/09/2026, la même sur tous les
# clients Loksi (brand/README.md, « Le nom Bitwarden ») : modification par Aleop, GPL v3,
# non-affiliation, puis l'avis de copyright amont, gardé comme la GPL l'impose. Français
# pour fr, anglais pour les autres langues. L'année vient de l'amont (Year.now).
ORIGIN_NOTICE = {
"fr": "Loksi, par Aleop. Application Bitwarden® modifiée par Aleop, sous licence GPL v3. "
"Aleop n'est pas affilié à Bitwarden Inc.\nBasé sur Bitwarden " + UPSTREAM_VERSION +
".\n© Bitwarden Inc. 2015-%1$d",
"en": "Loksi, by Aleop. Bitwarden® app modified by Aleop, under the GPL v3. "
"Aleop is not affiliated with Bitwarden Inc.\nBased on Bitwarden " + UPSTREAM_VERSION +
".\n© Bitwarden Inc. 2015-%1$d",
}
def adapt_about():
replace_once(SRC / APP / "ui/platform/feature/settings/about/AboutViewModel.kt",
'copyrightInfo = "© Bitwarden Inc. 2015-${Year.now(clock).value}".asText(),',
'copyrightInfo = BitwardenString.loksi_origin_notice.asText(Year.now(clock).value),')
# Entrées vers une offre ou une app Bitwarden sans équivalent Loksi : retirées plutôt que
# renommées (brand/README.md, « Le nom Bitwarden », 29/09/2026). La page produit de Send, et
# la synchronisation avec l'app Bitwarden Authenticator, qui ne reconnaît que la signature
# de Bitwarden. Visible dès Android 12, relevé le 29/09/2026.
def remove_bitwarden_offers():
replace_once(SRC / APP / "ui/tools/feature/send/SendScreen.kt", """ OverflowMenuItemData(
text = stringResource(id = BitwardenString.about_send),
onClick = { viewModel.trySendAction(SendAction.AboutSendClick) },
isExternalLink = true,
),
""", "")
replace_once(SRC / APP / "ui/platform/feature/settings/accountsecurity/AccountSecurityViewModel.kt",
" shouldShowEnableAuthenticatorSync = isBuildVersionAtLeast(Build.VERSION_CODES.S),\n",
" // Loksi: no sync with the Bitwarden Authenticator app.\n"
" shouldShowEnableAuthenticatorSync = false,\n")
# Aide et confidentialité : les pages Loksi du site (vitrine, 29/09/2026), adresses dans
# upstream.json, android.links, les mêmes qu'iOS.
# Après un import : le compte se gère sur le coffre web de l'entreprise, pas sur bitwarden.com.
# Même texte qu'iOS.
MANAGE_ACCOUNT_TEXT = {"fr": "Connectez-vous au coffre web de votre entreprise pour gérer votre compte et vos paramètres.",
"en": "Log in to your company's web vault to manage your account and settings."}
# Textes qui citent bitwarden.com sans qu'aucun écran de Loksi ne les affiche : formats
# d'import d'Authenticator, carte de téléchargement, dialogue des organisations retiré.
UNUSED_BITWARDEN_COM = {"go_to_bitwarden_com_download_to_integrate_bitwarden_into_browser",
"required_information_missing_message", "file_could_not_be_processed_message",
"learn_about_organizations_description_long"}
PRIVACY_TEXT = {"fr": "Consultez notre politique de confidentialité sur aleop.eu.",
"en": "Check out our privacy policy on aleop.eu."}
def adapt_links():
about = SRC / APP / "ui/platform/feature/settings/about/AboutScreen.kt"
for old, key in (("https://bitwarden.com/help", "help"), ("https://bitwarden.com/privacy", "privacy"),
("https://bitwarden.com/help/flight-recorder", "help")):
replace_once(about, f'intentManager.launchUri("{old}".toUri())',
f'intentManager.launchUri("{CONFIG["links"][key]}".toUri())')
# L'enregistreur de vols renvoie au centre d'aide Loksi, depuis son propre écran aussi.
replace_once(SRC / APP / "ui/platform/feature/settings/flightrecorder/FlightRecorderScreen.kt",
'intentManager.launchUri(uri = "https://bitwarden.com/help/flight-recorder".toUri())',
f'intentManager.launchUri(uri = "{CONFIG["links"]["help"]}".toUri())')
# « En savoir plus sur les organisations » ouvrait bitwarden.com : ligne retirée, comme iOS.
replace_once(about, """ BitwardenExternalLinkRow(
text = stringResource(id = BitwardenString.learn_org),
onConfirmClick = onLearnAboutOrgsClick,
dialogTitle = stringResource(id = BitwardenString.continue_to_x, "bitwarden.com"),
dialogMessage = stringResource(
id = BitwardenString.learn_about_organizations_description_long,
),
withDivider = false,
cardStyle = CardStyle.Middle(),
modifier = Modifier
.standardHorizontalMargin()
.fillMaxWidth()
.testTag(tag = "LearnAboutOrganizationsRow"),
)
""", "")
return set_strings({"privacy_policy_description_long": PRIVACY_TEXT,
"log_in_at_bitwarden_com_to_easily_manage_your_account": MANAGE_ACCOUNT_TEXT})
# Tutoriel d'import : l'anglais et le français affichent l'adresse réelle du coffre web
# (%1$s), plusieurs traductions ont vault.bitwarden.com en dur. Elles reprennent l'anglais.
def import_tutorial_address():
name = "on_your_computer_open_a_new_browser_tab_and_go_to_vault_bitwarden_com"
pattern = re.compile(r'(<string name="' + name + r'">)(.*?)(</string>)', re.S)
english = pattern.search((SRC / STRINGS / "values/strings.xml").read_text()).group(2)
if "%1$s" not in english or "bitwarden" in english.lower():
raise RuntimeError(f"{name} : texte anglais amont modifié")
fixed = 0
for path in sorted((SRC / STRINGS).glob("values-*/strings.xml")):
text = path.read_text()
match = pattern.search(text)
if match and "vault.bitwarden.com" in match.group(2):
path.write_text(text[:match.start(2)] + english + text[match.end(2):])
fixed += 1
if not fixed:
raise RuntimeError(f"{name} : aucune traduction en dur, l'amont a changé")
return fixed
# « Nous contacter » dans À propos : un courriel au support, la protection des données
# citée dans le dialogue. Demande de Romain le 30/09/2026. Adresse loksi@aleop.eu, boîte
# partagée (03/10/2026) : support@aleop.eu, l'entrée du support client, rejette les inconnus. Même confirmation que les
# lignes voisines, qui ouvrent aussi une app externe.
def contact_texts():
links = CONFIG["links"]
return {
"loksi_contact_us": {"fr": "Nous contacter", "en": "Contact us"},
"loksi_contact_us_title": {"fr": "Écrire au support ?", "en": "Email support?"},
"loksi_contact_us_message": {
"fr": f"Votre messagerie s'ouvre avec un courriel pour {links['support']}. "
f"Pour la protection des données, écrivez à {links['dpo']}.",
"en": f"Your email app opens with a message to {links['support']}. "
f"For data protection, write to {links['dpo']}.",
},
"loksi_source_code": {"fr": "Code source", "en": "Source code"},
"loksi_source_code_title": {"fr": "Ouvrir le code source ?", "en": "Open the source code?"},
"loksi_source_code_message": {
"fr": "Loksi est un logiciel libre sous licence GPL v3. Son code source est publié "
"sur sources.gitsi.dev.",
"en": "Loksi is free software under the GPL v3 licence. Its source code is published "
"on sources.gitsi.dev.",
},
}
def add_contact_row():
replace_once(SRC / APP / "ui/platform/feature/settings/about/AboutScreen.kt", """ .testTag(tag = "PrivacyPolicyRow"),
)
""", f""" .testTag(tag = "PrivacyPolicyRow"),
)
// Loksi: contact row, an email to the support.
val loksiIntentManager = LocalIntentManager.current
BitwardenExternalLinkRow(
text = stringResource(id = BitwardenString.loksi_contact_us),
onConfirmClick = {{ loksiIntentManager.launchUri("mailto:{CONFIG['links']['support']}".toUri()) }},
dialogTitle = stringResource(id = BitwardenString.loksi_contact_us_title),
dialogMessage = stringResource(id = BitwardenString.loksi_contact_us_message),
withDivider = false,
cardStyle = CardStyle.Middle(),
modifier = Modifier
.standardHorizontalMargin()
.fillMaxWidth()
.testTag(tag = "LoksiContactUsRow"),
)
// Loksi: source code row, the GPL v3 corresponding source (added 12/10/2026).
BitwardenExternalLinkRow(
text = stringResource(id = BitwardenString.loksi_source_code),
onConfirmClick = {{ loksiIntentManager.launchUri("{CONFIG['links']['source']}".toUri()) }},
dialogTitle = stringResource(id = BitwardenString.loksi_source_code_title),
dialogMessage = stringResource(id = BitwardenString.loksi_source_code_message),
withDivider = false,
cardStyle = CardStyle.Middle(),
modifier = Modifier
.standardHorizontalMargin()
.fillMaxWidth()
.testTag(tag = "LoksiSourceCodeRow"),
)
""")
def dex_literal(value):
"""Chaîne telle que la table des dex la range : longueur, octets, zéro final. Elle ne
trouve que la chaîne exacte, pas une adresse plus longue qui la contient."""
data = value.encode()
if len(data) > 127:
raise ValueError("chaîne trop longue pour ce contrôle")
return bytes([len(data)]) + data + b"\0"
# Numérotation des applis Loksi et Klepsi, règle de Romain du 06/10/2026, la même sur tous
# les clients : version affichée AAAA.M.n sans zéro devant, n à 0 pour la première sortie
# du mois ; numéro de build entier qui monte à chaque AAB, au-dessus de tous ceux déjà
# inscrits dans l'historique de upstream.json (Google refuse un code déjà reçu ou plus
# petit). La version de Bitwarden passe dans À propos, à côté de la mention d'origine.
VERSION_NAME = re.compile(r"(20\d\d)\.([1-9]|1[0-2])\.(0|[1-9]\d*)")
def check_version(name, code, used_codes):
"""Refuse une version hors règle, ou un code qui ne dépasse pas tous les codes déjà pris."""
if not VERSION_NAME.fullmatch(name):
raise ValueError(f"Version {name!r} hors règle AAAA.M.n, sans zéro devant")
if not isinstance(code, int) or isinstance(code, bool) or code < 1:
raise ValueError(f"Numéro de build {code!r} : entier positif attendu")
previous = [c for c in used_codes if c != code]
if previous and code <= max(previous):
raise ValueError(f"Numéro de build {code} : il doit dépasser {max(previous)}, déjà pris")
def used_codes():
"""Codes Android inscrits dans l'historique de mobile/upstream.json, commits compris."""
commits = subprocess.run(["git", "log", "--format=%H", "--", "mobile/upstream.json"], cwd=REPO,
capture_output=True, text=True, check=True).stdout.split()
codes = set()
for commit in commits:
text = subprocess.run(["git", "show", f"{commit}:mobile/upstream.json"], cwd=REPO,
capture_output=True, text=True, check=True).stdout
code = json.loads(text)["android"].get("app_version", {}).get("code")
if isinstance(code, int):
codes.add(code)
if not codes:
raise RuntimeError("Aucun code Android dans l'historique : lecture git muette")
return codes
def version_selftest():
"""Contrôle de la règle, avec canaris fabriqués qui doivent être refusés."""
for name in ("2026.10.0", "2026.10.1", "2026.11.0", "2027.1.12"):
check_version(name, 5, {3, 4})
for name in ("2026.09.0", "2026.10.00", "2026.13.0", "2026.0.1", "26.10.0", "2026.10", "2026.10.0-rc"):
try:
check_version(name, 5, {3, 4})
except ValueError:
continue
raise RuntimeError(f"Canari accepté : version {name!r}")
for code, used in ((4, {3, 4, 5}), (3, {3, 4}), (2, {3}), (0, set()), ("3", set())):
try:
check_version("2026.10.0", code, used)
except ValueError:
continue
raise RuntimeError(f"Canari accepté : code {code!r} après {sorted(used)}")
check_version("2026.10.0", 4, {3, 4}) # même code qu'au dernier commit : rebuild admis
# En-têtes envoyés au serveur : Vaultwarden active des fonctions selon Bitwarden-Client-Version,
# il doit voir la version amont réelle du code (2026.9.0), pas la version Loksi affichée.
# Même choix que l'extension (06/10/2026). Le User-Agent suit, pour rester cohérent.
HEADER_UTILS = "app/src/main/kotlin/com/x8bit/bitwarden/data/platform/datasource/network/util/HeaderUtils.kt"
CLIENT_VERSION_TEST = "app/src/test/kotlin/com/x8bit/bitwarden/data/platform/datasource/network/util/LoksiClientVersionTest.kt"
# Plus de Bitwarden sauf obligation (Romain, 09/10/2026). Inventaire vérifié le 09/10 sur le
# tag et sur Vaultwarden 1.37.3. Gardés car obligatoires : le schéma bitwarden:// (retour SSO
# imposé par src/sso.rs:198, Duo et WebAuthn par les connecteurs de Loksi web), les en-têtes
# Bitwarden-Client-Version et Device-Type que Vaultwarden lit (src/auth.rs), la mention GPL,
# et l'espace de noms Kotlin com.x8bit.bitwarden, jamais affiché, qui donne aussi les noms de
# composants (services, tuiles, MainActivity). Laissé : premium-checkout-result, retour du
# paiement Premium de Bitwarden, inaccessible avec Vaultwarden. Retiré ou passé à Loksi :
SHORTCUT_PACKAGES = {"main": DEBUG_ID, "release": APPLICATION_ID, "beta": APPLICATION_ID + ".beta"}
LOKSI_ACTIONS = ("ACTION_CREATE_PASSKEY", "ACTION_GET_PASSKEY", "ACTION_CREATE_PASSWORD",
"ACTION_GET_PASSWORD", "ACTION_UNLOCK_ACCOUNT")
def remove_bitwarden_remnants():
# Raccourcis de l'icône : ils visaient le package de Bitwarden, donc cassés dans Loksi.
for variant, package in SHORTCUT_PACKAGES.items():
shortcuts = SRC / f"app/src/{variant}/res/xml/shortcuts.xml"
old = "com.x8bit.bitwarden.dev" if variant == "main" else (
"com.x8bit.bitwarden.beta" if variant == "beta" else "com.x8bit.bitwarden")
replace_once(shortcuts, f'android:targetPackage="{old}" />', f'android:targetPackage="{package}" />', count=2)
# Le remplissage ne doit jamais remplir Loksi elle-même ; l'amont s'excluait lui-même.
replace_once(SRC / APP / "data/autofill/accessibility/util/AccessibilityNodeInfoExtensions.kt",
'private const val PACKAGE_NAME_BITWARDEN_PREFIX: String = "com.x8bit.bitwarden"',
f'private const val PACKAGE_NAME_BITWARDEN_PREFIX: String = "{APPLICATION_ID}"')
replace_once(SRC / APP / "data/autofill/parser/AutofillParserImpl.kt", """ "androidapp://com.x8bit.bitwarden",
"androidapp://com.x8bit.bitwarden.beta",
"androidapp://com.x8bit.bitwarden.dev",""", f""" "androidapp://{APPLICATION_ID}",
"androidapp://{APPLICATION_ID}.beta",
"androidapp://{DEBUG_ID}",""")
# Fichier d'export du coffre, visible dans les fichiers de l'utilisateur.
replace_once(SRC / APP / "ui/platform/feature/settings/exportvault/ExportVaultViewModel.kt",
'val fileName = "bitwarden_export_$date.$extension"', 'val fileName = "loksi_export_$date.$extension"')
# User-Agent : Vaultwarden 1.37.3 ne le lit pas (seulement le sien en sortie, src/http_client.rs).
replace_once(SRC / HEADER_UTILS, '"Bitwarden_Mobile/$LOKSI_UPSTREAM_VERSION (', '"Loksi_Mobile/$LOKSI_UPSTREAM_VERSION (')
# Actions internes du fournisseur d'identifiants, manifeste et code ensemble.
pending = SRC / APP / "data/credentials/manager/CredentialManagerPendingIntentManagerImpl.kt"
manifest = SRC / "app/src/main/AndroidManifest.xml"
for action in LOKSI_ACTIONS:
replace_once(pending, f'"com.x8bit.bitwarden.credentials.{action}"', f'"{APPLICATION_ID}.credentials.{action}"')
replace_once(manifest, f'android:name="com.x8bit.bitwarden.credentials.{action}"',
f'android:name="{APPLICATION_ID}.credentials.{action}"')
# Pont vers Bitwarden Authenticator : service exporté aux applis signées par Bitwarden
# (known_authenticator_app_certs). Loksi n'a pas d'Authenticator : retiré du manifeste.
text = manifest.read_text()
blocks = [r"\n <!-- Protect access to AuthenticatorBridgeService.*?tools:targetApi=\"s\" />",
r"\n\s*<service\s+android:name=\"com\.x8bit\.bitwarden\.data\.platform\.service\.AuthenticatorBridgeService\".*?/>",
# Retour du « cookie vendor » : connexion par cookie que Vaultwarden ne fournit pas.
r"\n\s*<intent-filter>(?:(?!</intent-filter>).)*?android:host=\"sso-cookie-vendor\"(?:(?!</intent-filter>).)*?</intent-filter>"]
for block in blocks:
text, count = re.subn(block, "", text, flags=re.S)
if count != 1:
raise RuntimeError(f"Bloc amont du manifeste modifié : {block[:60]}")
manifest.write_text(text)
def adapt_client_version():
headers = SRC / HEADER_UTILS
replace_once(headers, '"Bitwarden_Mobile/${BuildConfig.VERSION_NAME} (',
'"Bitwarden_Mobile/$LOKSI_UPSTREAM_VERSION (')
replace_once(headers, "const val HEADER_VALUE_CLIENT_VERSION: String = BuildConfig.VERSION_NAME\n",
"const val HEADER_VALUE_CLIENT_VERSION: String = LOKSI_UPSTREAM_VERSION\n")
replace_once(headers, "import com.x8bit.bitwarden.BuildConfig\n",
"import com.x8bit.bitwarden.BuildConfig\n\n"
"/**\n * Loksi: version of the Bitwarden code, sent to the server instead of the Loksi version.\n */\n"
f'const val LOKSI_UPSTREAM_VERSION: String = "{UPSTREAM_VERSION}"\n')
test = SRC / CLIENT_VERSION_TEST
if test.exists():
raise RuntimeError("Test Loksi déjà présent dans l'amont : " + CLIENT_VERSION_TEST)
displayed = CONFIG["app_version"]["marketing"]
if displayed == UPSTREAM_VERSION:
raise RuntimeError("Version Loksi égale à la version amont : le canari ne distinguerait rien")
test.parent.mkdir(parents=True, exist_ok=True)
test.write_text(f"""// GPL-3.0-only. Loksi: the server sees the Bitwarden version of the code, not the Loksi one.
// Written by mobile/android/loksi.py.
package com.x8bit.bitwarden.data.platform.datasource.network.util
import com.x8bit.bitwarden.BuildConfig
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class LoksiClientVersionTest {{
@Test
fun `client version header and user agent carry the upstream version`() {{
assertEquals("{UPSTREAM_VERSION}", HEADER_VALUE_CLIENT_VERSION)
assertTrue(HEADER_VALUE_USER_AGENT.startsWith("Loksi_Mobile/{UPSTREAM_VERSION} ("))
}}
@Test
fun `canary, the displayed Loksi version is never the client version`() {{
assertEquals("{displayed}", BuildConfig.VERSION_NAME)
assertNotEquals(BuildConfig.VERSION_NAME, HEADER_VALUE_CLIENT_VERSION)
assertTrue(!HEADER_VALUE_USER_AGENT.contains(BuildConfig.VERSION_NAME))
}}
}}
""")
def adapt_version():
"""Version de l'appli : upstream.json fait foi (android.app_version), processus commun
apps/docs/applis-mobiles.md, règle de numérotation ci-dessus."""
version = CONFIG["app_version"]
version_selftest()
check_version(version["marketing"], version["code"], used_codes() | {version["code"]})
toml = SRC / "gradle/libs.versions.toml"
replace_once(toml, 'appVersionCode = "1"\n', f'appVersionCode = "{version["code"]}"\n')
replace_once(toml, 'appVersionName = "2026.9.0"\n', f'appVersionName = "{version["marketing"]}"\n')
def render_graphics():
"""Icône adaptative du lanceur, rendue par Chromium depuis brand/ (render.mjs)."""
node = CACHE / "node"
node.mkdir(exist_ok=True)
for name in ("package.json", "package-lock.json"):
shutil.copy2(REPO / "brand" / name, node / name)
if not (node / "node_modules/playwright").exists():
run(["npm", "ci", "--no-audit", "--no-fund"], cwd=node)
out = CACHE / "android-graphics"
if out.exists():
shutil.rmtree(out)
run(["node", HERE / "render.mjs", out], cwd=node)
res = SRC / "app/src/main/res"
copied = []
for png in sorted(out.glob("drawable-*/loksi_launcher_*.png")):
target = res / png.parent.name / png.name
target.parent.mkdir(exist_ok=True)
shutil.copy2(png, target)
copied.append(target)
if len(copied) != 10:
raise RuntimeError(f"Icône adaptative : 10 PNG attendus, {len(copied)}")
for name in ("ic_launcher", "ic_launcher_round"):
replace_once(res / f"mipmap-anydpi/{name}.xml", '<background android:drawable="@color/ic_launcher_background" />',
'<background android:drawable="@drawable/loksi_launcher_background" />')
return len(copied)
def prepare():
fetch()
if SRC.exists():
shutil.rmtree(SRC)
with tarfile.open(CACHE / "android.tar.gz") as archive:
archive.extractall(CACHE / "android-extract", filter="data")
(CACHE / "android-extract" / ("android-" + CONFIG["tag"].lstrip("v"))).rename(SRC)
shutil.rmtree(CACHE / "android-extract")
# Les clés debug de Bitwarden sont retirées : toute référence restante casse la compilation.
for key in (SRC / "keystores").glob("*.keystore"):
key.unlink()
gradle = SRC / "app/build.gradle.kts"
replace_once(gradle, 'applicationId = "com.x8bit.bitwarden"', f'applicationId = "{APPLICATION_ID}"')
replace_once(gradle, 'archivesName.set("com.x8bit.bitwarden")', f'archivesName.set("{APPLICATION_ID}")')
replace_once(gradle, ''' keyAlias = "androiddebugkey"
keyPassword = "android"
storeFile = file("../keystores/debug.keystore")
storePassword = "android"''', ''' // Loksi : clé debug propre, hors du dépôt (mobile/android/loksi.py keys).
val loksiKeys = File(System.getenv("LOKSI_ANDROID_KEYS") ?: error("LOKSI_ANDROID_KEYS absent"))
val loksiPassword = File(loksiKeys, "debug.pass").readText().trim()
keyAlias = "loksi-debug"
keyPassword = loksiPassword
storeFile = File(loksiKeys, "debug.p12")
storePassword = loksiPassword''')
unset_server()
adapt_version()
adapt_client_version()
remove_bitwarden_remnants()
# Liens d'application https vers les domaines Bitwarden : jamais vérifiables pour Loksi.
# Le schéma bitwarden:// reste : Vaultwarden 1.37.3 l'impose pour le retour SSO mobile.
manifest = SRC / "app/src/main/AndroidManifest.xml"
text = manifest.read_text()
text, count = re.subn(r'\n\s*<intent-filter android:autoVerify="true">(?:(?!</intent-filter>).)*?'
r'android:host="\*?\.?bitwarden\.com"(?:(?!</intent-filter>).)*?</intent-filter>',
"", text, flags=re.S)
if count != 2:
raise RuntimeError(f"Liens d'application Bitwarden : 2 attendus, {count} trouvés")
manifest.write_text(text)
renamed = adapt_strings()
server_strings = server_entry()
hide_registration()
server_strings += vault_name_entry()
carousel = adapt_carousel()
adapt_about()
remove_bitwarden_offers()
adapt_links()
import_tutorial_address()
add_contact_row()
french_fixes()
sys.path.insert(0, str(HERE))
import graphics
drawn = graphics.write_all(SRC, REPO / "brand")
illustrations, _ = graphics.write_illustrations(SRC, REPO / "brand")
tabs, holes = graphics.write_tab_icons(SRC, REPO / "brand")
rendered = render_graphics()
colors = adapt_colors()
fonts = adapt_fonts()
(SRC / "user.properties").write_text("localSdk=true\n")
(SRC / "local.properties").write_text(f"sdk.dir={ANDROID_HOME}\n")
(SRC / "LOKSI-NOTICE.txt").write_text(
"Loksi pour Android, adaptation par Aleop.\n"
f"Basé sur bitwarden/android {CONFIG['tag']} ({CONFIG['commit']}),\n"
f"SDK recompilé depuis bitwarden/sdk-internal {CONFIG['sdk']['source_commit']}.\n"
"GPL v3. Modifications : identifiant, nom, icônes, illustrations, couleurs, police,\n"
"choix du serveur sans adresse par défaut, accueil sans création de compte, textes,\n"
"liens d'application et clé de signature. Ni affilié ni approuvé par Bitwarden.\n"
"Les fichiers ui/src/main/res/font/dm_sans_*.ttf contiennent la police Loksi,\n"
"instances de Raleway (SIL Open Font License 1.1, copyright et licence dans la\n"
"table name de chaque fichier), et non DM Sans.\n"
f"Modifié par Aleop depuis le {UPSTREAM['releve']} ; fichiers modifiés listés par loksi.py changes.\n")
print(f"Sources Loksi préparées : {renamed} chaînes renommées, {carousel} textes de carrousel, "
f"{server_strings} textes du serveur, {len(drawn)} ressources dessinées, {len(illustrations)} illustrations, "
f"{len(tabs)} pictogrammes d'onglets ({holes} évidements), {rendered} PNG d'icône, {colors} couleurs, "
f"{fonts} polices, version {CONFIG['app_version']['marketing']} ({CONFIG['app_version']['code']})")
changes()
def changes():
"""Échoue si un fichier hors des zones d'adaptation diffère de l'archive."""
allowed = re.compile(
r"app/build\.gradle\.kts|app/src/main/AndroidManifest\.xml|"
r"data/src/main/kotlin/com/bitwarden/data/repository/util/EnvironmentUrlDataJsonExtensions\.kt|"
r"data/src/test/kotlin/com/bitwarden/data/repository/util/EnvironmentUrlsDataJsonExtensionsTest\.kt|"
r"ui/src/main/res/values[^/]*/strings(_non_localized)?\.xml|"
r"app/src/(main|beta|release)/res/values/strings_non_localized\.xml|"
r"app/src/(main|beta|release)/res/drawable/ic_launcher_(foreground|monochrome)\.xml|"
r"app/src/main/res/values/ic_launcher_background\.xml|"
r"ui/src/main/res/drawable/logo_(bitwarden|bitwarden_icon|shield_icon)\.xml|"
r"app/src/main/res/mipmap-anydpi/ic_launcher(_round)?\.xml|"
r"ui/src/main/kotlin/com/bitwarden/ui/platform/theme/color/ColorScheme\.kt|"
r"ui/src/main/res/font/dm_sans_(regular|medium|semi_bold|bold)\.ttf|"
r"ui/src/main/res/drawable/(ill_[a-z0-9_]+|ic_(vault|generator|send|settings)(_filled)?)\.xml|"
r"gradle/libs\.versions\.toml|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/platform/components/dropdown/EnvironmentSelector\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/auth/feature/(landing/Landing(Screen|ViewModel)|"
r"environment/EnvironmentViewModel|welcome/WelcomeScreen)\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/platform/feature/settings/about/AboutViewModel\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/tools/feature/send/SendScreen\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/tools/feature/generator/GeneratorScreen\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/platform/feature/settings/about/AboutScreen\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/platform/feature/settings/flightrecorder/FlightRecorderScreen\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/auth/feature/environment/EnvironmentScreen\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/data/platform/datasource/network/util/HeaderUtils\.kt|"
r"app/src/(main|release|beta)/res/xml/shortcuts\.xml|"
r"app/src/main/kotlin/com/x8bit/bitwarden/data/autofill/(accessibility/util/AccessibilityNodeInfoExtensions|"
r"parser/AutofillParserImpl)\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/platform/feature/settings/exportvault/ExportVaultViewModel\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/data/credentials/manager/CredentialManagerPendingIntentManagerImpl\.kt|"
r"app/src/main/kotlin/com/x8bit/bitwarden/ui/platform/feature/settings/accountsecurity/AccountSecurityViewModel\.kt")
# Fichiers qui n'existent pas dans l'archive : chacun doit être prévu ici.
added_allowed = re.compile(
r"user\.properties|local\.properties|LOKSI-NOTICE\.txt|"
r"data/src/(main|test)/kotlin/com/bitwarden/data/repository/util/LoksiVault(Test)?\.kt|"
r"app/src/test/kotlin/com/x8bit/bitwarden/data/platform/datasource/network/util/LoksiClientVersionTest\.kt|"
r"ui/src/main/res/drawable-night/(logo_bitwarden|ill_[a-z0-9_]+|ic_(vault|generator|send|settings)_filled)\.xml|"
r"app/src/main/res/drawable-(mdpi|hdpi|xhdpi|xxhdpi|xxxhdpi)/loksi_launcher_(foreground|background)\.png")
# Produits de Gradle, jamais comparés.
generated = re.compile(r"(.*/)?(build|\.gradle|\.kotlin|\.idea)/.*")
changed, removed, added, upstream = [], [], [], set()
with tarfile.open(CACHE / "android.tar.gz") as archive:
for member in archive:
if not member.isfile():
continue
relative = member.name.split("/", 1)[1]
upstream.add(relative)
target = SRC / relative
if not target.exists():
if not re.fullmatch(r"keystores/[^/]+\.keystore", relative):
raise RuntimeError("Fichier amont supprimé hors périmètre : " + relative)
removed.append(relative)
continue
if archive.extractfile(member).read() != target.read_bytes():
if not allowed.fullmatch(relative):
raise RuntimeError("Modification hors périmètre : " + relative)
changed.append(relative)
for path in sorted(SRC.rglob("*")):
relative = path.relative_to(SRC).as_posix()
if not path.is_file() or relative in upstream or generated.fullmatch(relative):
continue
if not added_allowed.fullmatch(relative):
raise RuntimeError("Fichier ajouté hors périmètre : " + relative)
added.append(relative)
REPORTS.mkdir(exist_ok=True)
(REPORTS / "android-upstream-changes.json").write_text(
json.dumps({"modified": changed, "removed": removed, "added": added}, indent=2) + "\n")
print(f"{len(changed)} fichiers amont adaptés, {len(removed)} retirés, {len(added)} ajoutés, aucun hors périmètre")
def build():
env = tool_env()
for name in ("debug.pass", "debug.p12"):
if not (KEYS / name).is_file():
sys.exit(f"Clé debug absente ({KEYS / name}) : lancer d'abord loksi.py keys")
# Tests unitaires des modules touchés par l'adaptation, puis l'APK.
run(["./gradlew", ":data:testDebugUnitTest", ":app:assembleFdroidDebug"], cwd=SRC, env=env)
# Les tests Loksi du module data doivent avoir tourné, tous : un fichier absent ou un
# compte différent veut dire qu'ils ont été sautés, pas qu'ils passent.
report = SRC / "data/build/test-results/testDebugUnitTest/TEST-com.bitwarden.data.repository.util.LoksiVaultTest.xml"
if not report.is_file():
raise RuntimeError("Tests LoksiVaultTest absents des résultats")
suite = re.search(r'<testsuite[^>]* tests="(\d+)"[^>]* failures="(\d+)" errors="(\d+)"', report.read_text())
if not suite or suite.groups() != ("8", "0", "0"):
raise RuntimeError(f"LoksiVaultTest : {suite.groups() if suite else 'illisible'}, 8 tests sans échec attendus")
apk = SRC / f"app/build/outputs/apk/fdroid/debug/{DEBUG_ID}-fdroid.apk"
DIST.mkdir(parents=True, exist_ok=True)
target = DIST / apk.name
shutil.copy2(apk, target)
with open(REPORTS / "android-dependencies.txt", "w") as out:
run(["./gradlew", "-q", ":app:dependencies", "--configuration", "fdroidDebugRuntimeClasspath"],
cwd=SRC, env=env, stdout=out)
verify()
# Tests amont qui échouent par construction, chacun avec sa raison. Tout échec en plus ou
# en moins fait tomber la commande tests. Les classes lancées couvrent chaque fichier
# Kotlin que Loksi modifie. Relevé le 09/10/2026 sur 1244 tests, 36 échecs.
APP_TESTS = ["*Environment*", "*RestrictionManager*", "*Landing*", "*Autofill*", "*Welcome*", "*About*",
"*StartRegistration*", "*SendScreen*", "*SendViewModel*", "*AccountSecurity*",
"*FlightRecorder*", "*ImportLogins*", "*LoksiClientVersion*", "*HeaderUtils*", "*HeadersInterceptor*",
"*ExportVault*", "*AccessibilityNodeInfo*", "*CredentialManagerPendingIntent*", "*AutofillParser*", "*GeneratorScreen*"]
EXPECTED_APP_FAILURES = {
# Ils cherchent les libellés « A\u2014Z » et « a\u2014z » du générateur : Loksi les écrit
# « A-Z » et « a-z », sans tiret cadratin (french_fixes). Relevé le 09/10/2026.
("GeneratorScreenTest", "in Password state, disabled elements should not send events"),
("GeneratorScreenTest", "in Password state, the ViewModel state should update the UI correctly"),
("GeneratorScreenTest", "in Password state, toggling the capital letters toggle should send ToggleCapitalLettersChange action"),
("GeneratorScreenTest", "in Password state, toggling the use lowercase toggle should send ToggleLowercaseLettersChange action"),
# Ils attendent le serveur US quand rien n'est enregistré : Loksi rend le marqueur
# « adresse à saisir » (29/09/2026, avant : loksi.aleop.eu). Relevé le 28/09/2026.
("BaseUrlsProviderTest", "getBaseApiUrl should return default value when preAuthEnvironmentUrlData is null()"),
("BaseUrlsProviderTest", "getBaseIdentityUrl should return default value when preAuthEnvironmentUrlData is null()"),
("BaseUrlsProviderTest", "getBaseEventsUrl should return default value when preAuthEnvironmentUrlData is null()"),
("EnvironmentRepositoryTest", "after initialize changes to the active user should update the environment if necessary()"),
("EnvironmentRepositoryTest", "environmentStateFow should react to changes in environment()"),
("EnvironmentRepositoryTest", "environment should pull from and update EnvironmentDiskSource()"),
# Il cherche le texte « Bitwarden Autofill Service », devenu « Loksi Autofill Service ».
("VaultAddEditScreenTest", "InitialAutofillPrompt is shown according to state"),
# Pas de création de compte dans l'app (Romain, 29/09/2026) : bouton du carrousel et lien
# de l'écran de connexion retirés, « Create account » introuvable.
("LandingScreenTest", "allowCreateAccount state should show and hide CreateAccount UI"),
("LandingScreenTest", "create account click should send CreateAccountClick action"),
("WelcomeScreenTest", "create account button click should send CreateAccountClick action"),
("WelcomeScreenTest", "create account button should update according to state"),
# Plus de menu des régions (Romain, 29/09/2026) : « Connexion sur » ouvre la saisie du
# coffre, le dialogue bitwarden.com, bitwarden.eu n'apparaît plus.
("LandingScreenTest", "selecting environment should send EnvironmentOptionSelect action"),
("StartRegistrationScreenTest", "when environment selected in dialog should send EnvironmentTypeSelect action"),
# Textes Loksi : ils cherchent le texte anglais amont en dur. Carrousel réécrit
# (« Security, prioritized »), « Bitwarden » devenu « Loksi » (« Bitwarden web vault »,
# texte des applications de confiance pour les passkeys).
("WelcomeScreenTest", "pages should display and update according to state"),
("WelcomeScreenTest", "pages should display and update according to state in landscape mode"),
("AboutScreenTest", "on bitwarden web vault click should display confirmation dialog and confirm click should emit WebVaultClick"),
("AboutPrivilegedAppsScreenTest", "content is displayed correctly"),
("AccountSecurityScreenTest", "on unlock with pin toggle when disabled should show the PIN input dialog and send "
"UnlockWithPinToggle PendingEnabled"),
# Offres et apps Bitwarden retirées (brand/README.md, 29/09/2026) : plus d'entrée « About
# Send » vers la page produit, plus de synchronisation avec Bitwarden Authenticator.
("SendScreenTest", "on overflow item click should display menu"),
("SendScreenTest", "on about send click should send AboutSendClick"),
("AccountSecurityViewModelTest", "when version is at least 31 should show authenticator sync UI()"),
# Aide et confidentialité sur les pages Loksi du site (29/09/2026) : ils attendent
# bitwarden.com/help et bitwarden.com/privacy, ou le libellé « Bitwarden help center ».
("AboutScreenTest", "on NavigateToHelpCenter should call launchUri on IntentManager"),
("AboutScreenTest", "on NavigateToPrivacyPolicy should call launchUri on IntentManager"),
("AboutScreenTest", "on bitwarden help center click should display confirmation dialog and confirm click should emit "
"HelpCenterClick"),
# L'enregistreur de vols renvoie au centre d'aide Loksi, plus à bitwarden.com/help/flight-recorder ;
# son texte dit « Loksi help center ». Ligne des organisations retirée d'À propos (bitwarden.com).
("AboutScreenTest", "on NavigateToFlightRecorderHelp should call launchUri on IntentManager"),
("AboutScreenTest", "on learn about organizations click should display confirmation dialog and confirm click "
"should emit LearnAboutOrganizationsClick"),
("FlightRecorderScreenTest", "on NavigateToHelpCenter event should launch intent for help center"),
("FlightRecorderScreenTest", "on help center click should emit HelpCenterClick action"),
# Nom ou adresse du coffre (04/10/2026) : le champ s'appelle « Nom ou adresse de votre
# coffre » ; l'enregistrement exige qu'un Vaultwarden réponde sur /api/config, ce que ne
# font pas les adresses d'essai, et un champ vide donne le message Loksi.
("EnvironmentScreenTest", "server URL change should send ServerUrlChange"),
("EnvironmentScreenTest", "server URL should change according to the state"),
("EnvironmentViewModelTest", "SaveClick should emit NavigateBack, send a snackbar to the ENVIRONMENT SAVED relay, "
"and update the environment when all URLs are valid()"),
("EnvironmentViewModelTest", "SaveClick should emit NavigateBack, send a snackbar to the ENVIRONMENT SAVED relay, "
"and update the environment when some URLs are valid and others are null()"),
("EnvironmentViewModelTest", "SaveClick should show the error dialog when any URLs are invalid()"),
# Plus de Bitwarden sauf obligation (09/10/2026) : Loksi s'exclut elle-même du remplissage
# (eu.aleop.loksi au lieu de com.x8bit.bitwarden) et exporte en loksi_export_.
("AccessibilityNodeInfoExtensionsTest", "shouldSkipPackage when packageName is prefixed with bitwarden package "
"should return true()"),
("AutofillParserTests", "parse should skip block listed URIs Login when a Login view is focused()"),
("ExportVaultViewModelTest", "ReceiveExportVaultDataToStringResult should emit NavigateToSelectExportDataLocation "
"on result success()"),
}
def tests():
import html
env = tool_env()
results = SRC / "app/build/test-results/testFdroidDebugUnitTest"
if results.exists():
shutil.rmtree(results)
command = ["./gradlew", "--continue", ":app:testFdroidDebugUnitTest"]
for pattern in APP_TESTS:
command += ["--tests", pattern]
subprocess.run(command, cwd=SRC, env=env) # échecs attendus : le verdict se fait ci-dessous
total, failures = 0, set()
for path in results.glob("*.xml"):
text = path.read_text()
total += sum(int(n) for n in re.findall(r'<testsuite[^>]* tests="(\d+)"', text))
for name, classname in re.findall(r'<testcase name="([^"]+)" classname="([^"]+)"[^>]*>\s*<(?:failure|error)', text):
failures.add((classname.rsplit(".", 1)[-1], html.unescape(name)))
if total < 500:
raise RuntimeError(f"Seulement {total} tests exécutés")
# Le test Loksi de l'en-tête de version doit avoir tourné, ses 2 cas sans échec.
loksi = results / "TEST-com.x8bit.bitwarden.data.platform.datasource.network.util.LoksiClientVersionTest.xml"
suite = re.search(r'<testsuite[^>]* tests="(\d+)"[^>]* failures="(\d+)" errors="(\d+)"',
loksi.read_text() if loksi.is_file() else "")
if not suite or suite.groups() != ("2", "0", "0"):
raise RuntimeError(f"LoksiClientVersionTest : {suite.groups() if suite else 'absent'}, 2 tests sans échec attendus")
if failures != EXPECTED_APP_FAILURES:
raise RuntimeError(f"Échecs inattendus : {sorted(failures - EXPECTED_APP_FAILURES)}, "
f"attendus absents : {sorted(EXPECTED_APP_FAILURES - failures)}")
print(f"{total} tests app, {len(failures)} échecs, tous attendus")
def install():
"""Nouvelle installation sur l'AVD Loksi : l'ancienne app et ses données sont retirées,
comme sur un téléphone neuf, puis l'APK est installé et lancé."""
adb = ANDROID_HOME / "platform-tools/adb"
devices = subprocess.run([adb, "devices"], capture_output=True, text=True, check=True).stdout
if not re.search(r"^emulator-\d+\s+device$", devices, re.M):
subprocess.Popen([ANDROID_HOME / "emulator/emulator", "-avd", AVD, "-no-snapshot-load"],
stdout=open(CACHE / "emulator.log", "w"), stderr=subprocess.STDOUT)
run([adb, "wait-for-device"])
while subprocess.run([adb, "shell", "getprop", "sys.boot_completed"], capture_output=True,
text=True).stdout.strip() != "1":
subprocess.run(["sleep", "2"])
name = subprocess.run([adb, "emu", "avd", "name"], capture_output=True, text=True).stdout.split()
if not name or name[0] != AVD:
sys.exit(f"Émulateur inattendu : {name[:1]}, {AVD} attendu")
subprocess.run([adb, "uninstall", DEBUG_ID], capture_output=True) # absente la première fois
run([adb, "install", DIST / f"{DEBUG_ID}-fdroid.apk"])
# monkey rend 251 sur l'image Android 16 (« SYS_KEYS has no physical keys »), vu le
# 29/09/2026 : on lance l'activité d'accueil résolue par le système. Android 16 bloque un
# intent explicite qui ne correspond pas au filtre (« Access blocked ») : action et
# catégorie sont données avec le composant.
activity = subprocess.run([adb, "shell", "cmd", "package", "resolve-activity", "--brief", "-c",
"android.intent.category.LAUNCHER", DEBUG_ID], capture_output=True, text=True,
check=True).stdout.split()[-1]
if not activity.startswith(DEBUG_ID + "/"):
sys.exit(f"Activité d'accueil introuvable : {activity}")
run([adb, "shell", "am", "start", "-W", "-a", "android.intent.action.MAIN", "-c",
"android.intent.category.LAUNCHER", "-n", activity], stdout=subprocess.DEVNULL)
print(f"Loksi installé à neuf et lancé sur {AVD}")
def build_tool(name):
tools = sorted((ANDROID_HOME / "build-tools").iterdir())
return tools[-1] / name
def dex_strings(apk):
blob = b""
with zipfile.ZipFile(apk) as archive:
for name in archive.namelist():
if re.fullmatch(r"(base/dex/)?classes\d*\.dex", name):
blob += archive.read(name)
return blob
def app_texts_with_bitwarden(apk):
"""Chaînes de l'APK qui disent encore « Bitwarden », formes déclinées comprises (pas de
limite de mot : « Bitwardenin », « Bitwardenを »). Seules les chaînes gardées exprès
(éditeur, aide, formats, Authenticator) sont admises."""
dump = subprocess.run([build_tool("aapt2"), "dump", "resources", apk], capture_output=True, text=True,
check=True).stdout
found, name, dotcom = set(), None, set()
for line in dump.splitlines():
declared = re.match(r"\s+resource 0x[0-9a-f]+ (?:string|plurals)/(\S+)", line)
if declared:
name = declared.group(1)
elif re.match(r"\s+resource ", line):
name = None
elif name and "Bitwarden" in line:
found.add(name)
if name and "bitwarden.com" in line.lower():
dotcom.add(name)
# Canari : le même relevé doit voir les chaînes gardées exprès.
assert {"bitwarden_authenticator", "download_bitwarden_card_title"} <= found, \
f"canari du relevé des textes : {found}"
# Ressource des tests amont (ui/src/test/res), que l'APK debug embarque sans l'afficher.
test_only = {"test_for_single_link_annotation"}
if not (SRC / "ui/src/test/res/values/strings_for_tests_only.xml").read_text().count(
'name="test_for_single_link_annotation"'):
raise RuntimeError("Chaîne de test amont déplacée : test_for_single_link_annotation")
# La mention d'origine d'À propos cite Bitwarden exprès : elle doit y être, texte exact.
assert "loksi_origin_notice" in found, "mention d'origine absente de l'APK"
for sentence in (f"Based on Bitwarden {UPSTREAM_VERSION}.", f"Basé sur Bitwarden {UPSTREAM_VERSION}.",
"Loksi, by Aleop. Bitwarden® app modified by Aleop, under the GPL v3. "
"Aleop is not affiliated with Bitwarden Inc.",
"Loksi, par Aleop. Application Bitwarden® modifiée par Aleop, sous licence GPL v3. "
"Aleop n'est pas affilié à Bitwarden Inc."):
assert sentence in dump, f"mention d'origine inexacte : {sentence}"
unexpected = sorted(found - KEEP_STRINGS - test_only - {"loksi_origin_notice"})
assert not unexpected, f"« Bitwarden » encore dans des textes de l'app : {unexpected}"
# « bitwarden.com » en minuscules échappe au relevé ci-dessus. Canari : les textes jamais
# affichés qui le citent doivent être vus.
assert UNUSED_BITWARDEN_COM <= dotcom, f"canari du relevé bitwarden.com : {sorted(dotcom)}"
unexpected = sorted(dotcom - UNUSED_BITWARDEN_COM - KEEP_STRINGS - test_only)
assert not unexpected, f"« bitwarden.com » encore dans des textes de l'app : {unexpected}"
return len(found)
def bitwarden_remnants(apk, package, dex):
"""Restes Bitwarden retirables encore présents dans l'APK. Vide si tout est retiré ; lève
si la lecture elle-même ne voit pas les éléments obligatoires (canari de lecture)."""
aapt2 = build_tool("aapt2")
manifest = subprocess.run([aapt2, "dump", "xmltree", "--file", "AndroidManifest.xml", apk],
capture_output=True, text=True, check=True).stdout
for kept in ("sso-callback", "duo-callback", "webauthn-callback"):
assert kept in manifest, f"canari : retour obligatoire bitwarden://{kept} absent du manifeste lu"
found = [needle for needle in ("com.x8bit.bitwarden.credentials", "AUTHENTICATOR_BRIDGE", "sso-cookie-vendor",
"Bitwarden Bridge") if needle in manifest]
resources = subprocess.run([aapt2, "dump", "resources", apk], capture_output=True, text=True, check=True).stdout
paths = re.findall(r"resource 0x[0-9a-f]+ xml/shortcuts\b.*?\n\s+\([^)]*\) \(file\) (\S+)", resources, re.S)
assert paths, "canari : fichier des raccourcis introuvable dans l'APK"
shortcuts = subprocess.run([aapt2, "dump", "xmltree", "--file", paths[0], apk],
capture_output=True, text=True, check=True).stdout
targets = set(re.findall(r'targetPackage[^=]*="([^"]+)"', shortcuts))
if targets != {package}:
found.append(f"raccourcis vers {sorted(targets)}")
# Le User-Agent est découpé par le compilateur : on cherche la sous-chaîne, pas la chaîne exacte
# (la chaîne exacte ne voyait pas « Bitwarden_Mobile » dans l'APK du 08/10).
if b"Bitwarden_Mobile" in dex:
found.append("chaîne Bitwarden_Mobile")
if b"Loksi_Mobile" not in dex:
found.append("chaîne Loksi absente : Loksi_Mobile")
# La chaîne nue com.x8bit.bitwarden reste : c'est l'espace de noms du code (namespace Gradle)
# et le module authenticatorbridge, jamais appelé dans Loksi. On contrôle le préfixe ciblé.
for literal in ("bitwarden_export_", "androidapp://com.x8bit.bitwarden"):
if dex_literal(literal) in dex:
found.append(f"chaîne {literal}")
for literal in ("loksi_export_", f"androidapp://{APPLICATION_ID}", APPLICATION_ID):
if dex_literal(literal) not in dex:
found.append(f"chaîne Loksi absente : {literal}")
return found
def verify(apk=None, package=DEBUG_ID, kind="debug", report_name="android-apk.json"):
apk = apk or DIST / f"{DEBUG_ID}-fdroid.apk"
badging = subprocess.run([build_tool("aapt2"), "dump", "badging", apk], capture_output=True, text=True,
check=True).stdout
assert f"package: name='{package}'" in badging, "identifiant d'application"
assert "application-label:'Loksi'" in badging, "nom affiché"
expected = f"versionCode='{CONFIG['app_version']['code']}' versionName='{CONFIG['app_version']['marketing']}'"
assert expected in badging, f"version de l'APK : {expected} attendu"
signers = subprocess.run([build_tool("apksigner"), "verify", "--print-certs", apk], capture_output=True,
text=True, check=True).stdout
digests = re.findall(r"certificate SHA-256 digest: ([0-9a-f]+)", signers)
assert digests == [certificate_digest(kind)], f"signé par la clé {kind} Loksi"
dex = dex_strings(apk)
forbidden = [b"Lcom/google/firebase/", b"Lcom/android/billingclient/", b"Lcom/google/mlkit/",
b"Lcom/google/android/play/core/review/", b"Lcom/google/android/play/review/"]
found = [f.decode() for f in forbidden if f in dex]
assert not found, f"bibliothèques exclues présentes : {found}"
# Le coffre d'Aleop n'est plus un défaut : son adresse ne doit être ni dans le code ni
# dans les ressources. Canari : le même balayage doit trouver le SDK et le marqueur
# « adresse à saisir ».
with zipfile.ZipFile(apk) as archive:
resources = archive.read("resources.arsc")
host = SERVER.split("://", 1)[1].encode()
assert host not in dex and host not in resources, "adresse du coffre d'Aleop encore dans l'APK"
assert b"Lcom/bitwarden/sdk/" in dex, "canari : balayage des dex muet"
assert UNSET_SERVER.split("://", 1)[1].encode() in dex, "canari : marqueur « adresse à saisir » absent du code"
bitwarden = app_texts_with_bitwarden(apk)
# Aide et confidentialité d'À propos : les pages Loksi, plus celles de Bitwarden. Canari :
# l'APK du 29/09 au soir porte les deux adresses Bitwarden exactes.
for old in ("https://bitwarden.com/help", "https://bitwarden.com/privacy"):
assert dex_literal(old) not in dex, f"lien Bitwarden encore dans À propos : {old}"
for key in ("help", "privacy"):
assert dex_literal(CONFIG["links"][key]) in dex, f"lien Loksi absent : {CONFIG['links'][key]}"
# Nom de coffre : le domaine loksi.fr et la page produit sont dans le code.
assert dex_literal(LOKSI_PRODUCT) in dex, "lien Découvrir Loksi absent"
assert b"loksi.fr" in dex, "domaine loksi.fr absent du code"
# Plus de Bitwarden sauf obligation (09/10/2026). Canari : l'APK du 08/10 en a 12.
remnants = bitwarden_remnants(apk, package, dex)
assert not remnants, f"restes Bitwarden retirables : {remnants}"
# « Nous contacter » : courriel au support. Canari : l'APK précédent ne l'a pas.
assert dex_literal("mailto:" + CONFIG["links"]["support"]) in dex, "ligne Nous contacter absente"
assert dex_literal(CONFIG["links"]["source"]) in dex, "ligne Code source absente"
assert dex_literal(CONFIG["links"]["source"] + "-canari") not in dex, "contrôle Code source aveugle"
# Plus l'entrée du support client, qui rejette les inconnus. Canari : l'APK du 03/10 au matin la porte.
assert dex_literal("mailto:support@aleop.eu") not in dex, "Nous contacter écrit encore à l'entrée du support client"
with zipfile.ZipFile(apk) as archive:
library = archive.read("lib/arm64-v8a/libbitwarden_uniffi.so")
report = json.loads((REPORTS / "android-sdk.json").read_text())
# AGP retire les symboles des .so à l'empaquetage : on refait le même retrait sur
# la bibliothèque compilée avant de comparer. Vérifié le 28/09/2026, octet pour octet.
compiled = SDK_SRC / "crates/bitwarden-uniffi/kotlin/sdk/src/main/jniLibs/arm64-v8a/libbitwarden_uniffi.so"
assert sha256(compiled) == report["libbitwarden_uniffi_arm64_sha256"], "bibliothèque SDK modifiée depuis sdk"
strip = ANDROID_HOME / "ndk" / CONFIG["toolchain"]["ndk"] / "toolchains/llvm/prebuilt/darwin-x86_64/bin/llvm-strip"
stripped = CACHE / "libbitwarden_uniffi.stripped.so"
subprocess.run([strip, "--strip-unneeded", "-o", stripped, compiled], check=True)
assert hashlib.sha256(library).hexdigest() == sha256(stripped), "SDK recompilé embarqué"
result = {"apk": apk.name, "apk_sha256": sha256(apk), "certificate_sha256": digests[0],
"version": re.search(r"versionCode='(\d+)' versionName='([^']+)'", badging).groups(),
"bitwarden_texts_kept": bitwarden,
"sdk_library_sha256": report["libbitwarden_uniffi_arm64_sha256"],
"sdk_library_stripped_sha256": sha256(stripped)}
(REPORTS / report_name).write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
print("Vérifications de l'APK réussies")
return dex, stripped
def release():
"""AAB fdroid release pour Google Play et APK release d'essai, signés par la clé d'envoi.
L'amont ne signe pas sa release dans Gradle : Loksi la signe après coup, sans toucher au
build. L'APK sert aux essais (R8 et réduction des ressources) ; il n'est pas destiné à
être diffusé, sa signature n'étant pas celle que Google posera sur l'app publiée."""
env = tool_env()
for name in ("upload.pass", "upload.p12"):
if not (KEYS / name).is_file():
sys.exit(f"Clé d'envoi absente ({KEYS / name}) : lancer d'abord loksi.py upload-key")
changes()
run(["./gradlew", ":app:bundleFdroidRelease", ":app:assembleFdroidRelease"], cwd=SRC, env=env)
bundles = list((SRC / "app/build/outputs/bundle/fdroidRelease").glob("*.aab"))
# archivesName de l'amont : l'APK non signé s'appelle eu.aleop.loksi-fdroid.apk, sans
# suffixe « -unsigned » (vu le 02/10/2026). On contrôle qu'il n'a aucune signature.
apks = list((SRC / "app/build/outputs/apk/fdroid/release").glob("*.apk"))
if len(bundles) != 1 or len(apks) != 1:
raise RuntimeError(f"Sorties release inattendues : {bundles}, {apks}")
unsigned = subprocess.run([build_tool("apksigner"), "verify", apks[0]], capture_output=True, text=True)
if unsigned.returncode == 0:
raise RuntimeError("L'APK release sort déjà signé de Gradle : signature inattendue")
DIST.mkdir(parents=True, exist_ok=True)
aab = DIST / f"{APPLICATION_ID}-fdroid-release.aab"
apk = DIST / f"{APPLICATION_ID}-fdroid-release.apk"
for target in (aab, apk):
if target.exists():
target.unlink()
store, password, alias = KEYS / "upload.p12", KEYS / "upload.pass", SIGNING["upload"]["alias"]
jdk = Path(java_home()) / "bin"
try:
signed = subprocess.run([jdk / "jarsigner", "-keystore", store, "-storetype", "PKCS12",
"-storepass:file", password, "-keypass:file", password,
"-sigalg", "SHA256withRSA", "-digestalg", "SHA-256",
"-signedjar", aab, bundles[0], alias], capture_output=True)
if signed.returncode:
raise RuntimeError("jarsigner a échoué")
signed = subprocess.run([build_tool("apksigner"), "sign", "--ks", store, "--ks-pass", f"file:{password}",
"--ks-key-alias", alias, "--out", apk, apks[0]], capture_output=True)
if signed.returncode:
raise RuntimeError("apksigner a échoué")
except Exception as error: # le message brut pourrait citer un argument
sys.exit(f"Signature release interrompue : {type(error).__name__}")
verify_release(aab, apk)
def verify_release(aab=None, apk=None):
aab = aab or DIST / f"{APPLICATION_ID}-fdroid-release.aab"
apk = apk or DIST / f"{APPLICATION_ID}-fdroid-release.apk"
upload, debug = certificate_digest("upload"), certificate_digest("debug")
assert upload != debug, "clé d'envoi identique à la clé debug"
# APK release : tous les contrôles de l'APK debug, avec l'identifiant définitif.
dex, stripped = verify(apk, APPLICATION_ID, "upload", "android-release-apk.json")
jdk = Path(java_home()) / "bin"
# Pas de -strict : il refuse toute clé auto-signée, or une clé d'envoi Play l'est par nature
# (vu le 02/10/2026). Le certificat est contrôlé par son empreinte juste après.
checked = subprocess.run([jdk / "jarsigner", "-verify", aab], capture_output=True, text=True)
assert checked.returncode == 0 and "jar verified." in checked.stdout, "signature de l'AAB"
# Canari : l'AAB non signé sorti de Gradle doit être refusé par le même contrôle.
unsigned = next((SRC / "app/build/outputs/bundle/fdroidRelease").glob("*.aab"))
canary = subprocess.run([jdk / "jarsigner", "-verify", unsigned], capture_output=True, text=True)
assert "jar verified." not in canary.stdout, "canari : l'AAB non signé passe le contrôle de signature"
printed = subprocess.run([jdk / "keytool", "-J-Duser.language=en", "-printcert", "-jarfile", aab],
capture_output=True, text=True, check=True).stdout
digests = [d.replace(":", "").lower() for d in re.findall(r"SHA256:\s*([0-9A-F:]{95})", printed)]
assert digests == [upload], f"AAB signé par la clé d'envoi : {digests}"
with zipfile.ZipFile(aab) as archive:
manifest = archive.read("base/manifest/AndroidManifest.xml")
library = archive.read("base/lib/arm64-v8a/libbitwarden_uniffi.so")
# Manifeste protobuf : l'identifiant y figure en clair. Pas de suffixe .dev ni .beta.
assert APPLICATION_ID.encode() in manifest, "identifiant absent du manifeste de l'AAB"
assert DEBUG_ID.encode() not in manifest and (APPLICATION_ID + ".beta").encode() not in manifest, \
"AAB d'une autre variante"
assert hashlib.sha256(library).hexdigest() == sha256(stripped), "SDK recompilé embarqué dans l'AAB"
# Le code de l'AAB est celui de l'APK release : mêmes dex, compilés dans la même passe.
assert dex_strings(aab) == dex, "dex de l'AAB différents de ceux de l'APK release"
result = {"aab": aab.name, "aab_sha256": sha256(aab), "apk": apk.name, "apk_sha256": sha256(apk),
"upload_certificate_sha256": upload}
(REPORTS / "android-release.json").write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
print("Vérifications de la release réussies")
if __name__ == "__main__":
commands = {"fetch": fetch, "sdk": sdk, "keys": keys, "prepare": prepare, "changes": changes,
"build": build, "verify": verify, "tests": tests, "install": install,
"upload-key": upload_key, "release": release, "verify-release": verify_release}
if len(sys.argv) != 2 or sys.argv[1] not in commands:
sys.exit(__doc__)
commands[sys.argv[1]]()