#!/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() 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']*>)(.*?)()', 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'(]*>)(.*?)()', 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'()[^<]*()', 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("&", "&").replace("<", "<").replace(">", ">") 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'(]*>)(.*?)()', 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' {android_text(messages[language(path)])}\n' if text.count("") != 1: raise RuntimeError(f"Fin de ressources amont modifiée : {folder}") path.write_text(text.replace("", lines + "")) 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://.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://.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'()(.*?)()', 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']}.", }, } 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"), ) """) 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