#!/usr/bin/env python3
"""Application iOS Loksi, adaptée de bitwarden/ios. 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é, identifiants
d'application, groupes, serveur par défaut, ressources et retrait de Firebase.
Usage, depuis n'importe où :
loksi.py fetch archive amont et xcframework du SDK, empreintes vérifiées
loksi.py prepare sources iOS réextraites puis adaptées, projets Xcode générés
loksi.py changes refuse toute modification hors des zones prévues
loksi.py build application pour le simulateur, copiée dans ../dist/ios
loksi.py verify contrôles de l'application produite, avec canaris
loksi.py tests tests unitaires amont (plan Bitwarden-Unit), échecs attendus listés
loksi.py install installation et lancement sur le simulateur Loksi
loksi.py device installation sur l'iPhone branché, équipe Aleop (upstream.json, ios.apple_team)
loksi.py archive archive Release et .ipa App Store signés par l'équipe Aleop, sans envoi
"""
import hashlib
import json
import os
import plistlib
import re
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" / "ios"
REPORTS = MOBILE / "reports"
UPSTREAM = json.loads((MOBILE / "upstream.json").read_text())
CONFIG = UPSTREAM["ios"]
SERVER = UPSTREAM["server"]
# Pas de serveur par défaut : loksi.aleop.eu est le coffre d'Aleop, pas celui des clients
# (Romain, 29/09/2026). Tant que rien n'est saisi, l'app vise ce marqueur : le domaine
# .invalid est réservé et ne se résout jamais (RFC 6761), aucun serveur n'est contacté.
UNSET_SERVER = "https://coffre-a-renseigner.invalid"
SRC = CACHE / "ios-src"
DERIVED = CACHE / "ios-derived"
BUNDLE_ID = CONFIG["bundle_id"]
# Identifiant iOS eu.aleop.loksi.ios et non eu.aleop.loksi : la Personal Team gratuite de
# Romain a pris eu.aleop.loksi, eu.aleop.loksi.share-extension et group.eu.aleop.loksi le
# 29/09/2026, et Apple les refuse à l'équipe Aleop le 01/10/2026 (« cannot be registered to
# your development team because it is not available »). Un compte gratuit n'a pas de portail
# pour les rendre. Décision de Romain du 01/10/2026, même schéma que Klepsi (app.klepsi.ios).
# Le groupe reste celui de l'amont, « group. » plus l'identifiant.
APP_GROUP = f"group.{BUNDLE_ID}"
SIMULATOR = CONFIG["toolchain"]["local_simulator"]
XCFRAMEWORK = CACHE / Path(CONFIG["sdk"]["xcframework_url"]).name
APP = DERIVED / "Build/Products/Debug-iphonesimulator/Bitwarden.app"
# Équipe Apple de Bitwarden : verify la refuse dans les binaires Loksi.
BITWARDEN_TEAM = "LTZ2PFU5D6"
# Chaînes où « Bitwarden » désigne l'éditeur, son site, son aide, ses offres ou son
# application Authenticator. Elles restent telles quelles, dans toutes les langues.
# Toutes les autres désignent l'application ou le coffre et passent en Loksi.
KEEP_STRINGS = {
"LearnAboutOrganizationsDescriptionLong",
"GetAdviceAnnouncementsAndResearchOpportunitiesFromBitwardenInYourInboxUnsubscribeAtAnyTime.",
"ManageYourSubscriptionPlanInTheBitwardenWebApp",
"GoToBitwardenToIntegrateBitwardenIntoYourFavoriteBrowserForASeamlessExperience",
"AccountsSyncedFromBitwardenApp", "BitwardenAuthenticator", "BitwardenAuthenticatorDataIsBackedUpAndCanBeRestored",
"CopyToBitwardenVault", "DownloadTheBitwardenApp", "SaveThisAuthenticatorKeyHereOrAddItToALoginInYourBitwardenApp",
"SaveToBitwarden", "SecureYourAssetsWithBitwardenAuthenticator", "SetSaveToBitwardenAsYourDefaultSaveOption",
"SyncWithBitwardenApp", "SyncWithTheBitwardenApp", "UnableToSyncCodesFromTheBitwardenApp",
}
# Identifiants et groupes Loksi. Common-bwpm.xcconfig prévoit ce fichier local pour
# qu'une équipe tierce compile sans toucher au projet : c'est la voie amont.
LOCAL_XCCONFIG = f"""// Loksi : identité et signature locale, générées par mobile/ios/loksi.py.
DEVELOPMENT_TEAM =
ORGANIZATION_IDENTIFIER = eu.aleop
BASE_BUNDLE_ID = {BUNDLE_ID}
SHARED_APP_GROUP_IDENTIFIER = group.{BUNDLE_ID}.authenticator
BMPW_BUNDLE_DISPLAY_NAME = Loksi
// Version de l'appli : upstream.json fait foi, comme project.yml pour Klepsi.
MARKETING_VERSION = {CONFIG["app_version"]["marketing"]}
CURRENT_PROJECT_VERSION = {CONFIG["app_version"]["build"]}
// Simulateur : signature ad hoc « Sign to Run Locally », sans équipe ni profil Apple.
CODE_SIGN_STYLE = Manual
CODE_SIGN_IDENTITY = -
// Écart de poste, Xcode 27 au lieu de 26.6 : watchOS 9.0 minimum, l'amont vise 8.0.
WATCHOS_DEPLOYMENT_TARGET = 9.0
"""
# Numérotation des sorties, décision de Romain du 06/10/2026, la même pour tous les clients
# Loksi et Klepsi : version affichée AAAA.M.n sans zéro devant (n à 0 pour la première
# sortie du mois), build entier qui monte à chaque archive et ne sert qu'une fois.
VERSION_PATTERN = re.compile(r"^20[0-9]{2}\.(?:[1-9]|1[0-2])\.(?:0|[1-9][0-9]*)$")
BITWARDEN_VERSION = CONFIG["tag"].removeprefix("v").removesuffix("-bwpm")
def version_problems(marketing, build, last_archived):
"""Ce qui ne va pas dans une version, liste vide si elle est bonne."""
problems = []
if not VERSION_PATTERN.match(str(marketing)):
problems.append(f"version {marketing!r} : AAAA.M.n attendu, sans zéro devant")
if not isinstance(build, int) or isinstance(build, bool) or build <= last_archived:
problems.append(f"build {build!r} : entier supérieur au dernier archivé ({last_archived}) attendu")
return problems
def check_version():
"""Refuse la version de upstream.json si elle ne suit pas la règle. Canaris : un zéro
devant, un mois 13 et un build qui ne monte pas doivent être refusés."""
for marketing, build in (("2026.09.0", 16), ("2026.13.0", 16), ("2026.10.00", 16), ("2026.10.0", 15)):
if not version_problems(marketing, build, 15):
raise RuntimeError(f"Canari muet : {marketing} ({build}) accepté")
if version_problems("2026.10.0", 16, 15) or version_problems("2026.11.12", 40, 39):
raise RuntimeError("Contrôle de version : une version correcte est refusée")
version = CONFIG["app_version"]
problems = version_problems(version["marketing"], version["build"], version["last_archived_build"])
if problems:
raise RuntimeError("Version de upstream.json refusée : " + " ; ".join(problems))
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 git(*args, **kwargs):
return subprocess.run(["git", "-c", "user.name=Loksi", "-c", "user.email=loksi@aleop.eu", *args],
cwd=SRC, check=True, capture_output=True, text=True, **kwargs).stdout
def fetch():
CACHE.mkdir(exist_ok=True)
archive = CACHE / "ios.tar.gz"
if not archive.exists():
run(["curl", "-fsSL", "-o", archive, CONFIG["archive_url"]])
if sha256(archive) != CONFIG["archive_sha256"]:
raise RuntimeError("Archive iOS amont incorrecte : SHA-256 différent")
if not XCFRAMEWORK.exists():
run(["curl", "-fsSL", "-o", XCFRAMEWORK, CONFIG["sdk"]["xcframework_url"]])
if sha256(XCFRAMEWORK) != CONFIG["sdk"]["xcframework_sha256"]:
raise RuntimeError("xcframework du SDK incorrect : 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")
licence = CACHE / "Raleway-OFL.txt"
if not licence.exists():
run(["curl", "-fsSL", "-o", licence, UPSTREAM["font"]["url"].rsplit("/", 1)[0] + "/OFL.txt"])
if 'Reserved Font Name "Raleway"' not in licence.read_text():
raise RuntimeError("Licence OFL de Raleway inattendue")
# SwiftPM prend le zip vérifié dans son cache au lieu de le retélécharger, et
# revérifie la somme déclarée par Package.swift. Le 29/09/2026, son propre
# téléchargement de ce zip de 161 Mo a calé plus de dix minutes sans trafic.
swiftpm = Path.home() / "Library/Caches/org.swift.swiftpm/artifacts"
swiftpm.mkdir(parents=True, exist_ok=True)
seeded = swiftpm / re.sub(r"[^A-Za-z0-9_]", "_", CONFIG["sdk"]["xcframework_url"])
if not seeded.exists() or sha256(seeded) != CONFIG["sdk"]["xcframework_sha256"]:
shutil.copy2(XCFRAMEWORK, seeded)
print(f"Sources vérifiées : ios {CONFIG['tag']}, xcframework {XCFRAMEWORK.name}")
def adapt_strings():
"""« Bitwarden » devient « Loksi » dans les valeurs, jamais dans les clés."""
english = SRC / "BitwardenResources/Localizations/en.lproj/Localizable.strings"
line = re.compile(r'^("((?:[^"\\]|\\.)*)"\s*=\s*")((?:[^"\\]|\\.)*)(";)', re.M)
keys = {m.group(2) for m in line.finditer(english.read_text())}
missing = sorted(KEEP_STRINGS - keys)
if missing:
raise RuntimeError("Chaînes amont renommées : " + ", ".join(missing))
# Pas de \b final : plusieurs langues collent une terminaison au nom (« Bitwardenin »,
# « Bitwardenを »), 122 valeurs manquées le 29/09/2026. Seule exception, les
# variables de format des pluriels, précédées de @ (%#@BitwardenCouldNot...@).
word = re.compile(r"(? changent.
for path in sorted((SRC / "BitwardenResources/Localizations").glob("*.lproj/Localizable.stringsdict")):
text = path.read_text()
new = re.sub(r"([^<]*)", lambda m: "" + word.sub("Loksi", m.group(1)) + "", text)
changed += new != text
path.write_text(new)
if changed < 500:
raise RuntimeError(f"Seulement {changed} chaînes renommées, l'amont a changé")
return changed
def adapt_plists():
"""Noms affichés des applications et extensions."""
names = {
"Bitwarden/Application/Support/Info.plist": {"CFBundleName": "Loksi"},
"BitwardenAutoFillExtension/Application/Support/Info.plist": {"CFBundleDisplayName": "Loksi", "CFBundleName": "Loksi Autofill"},
"BitwardenShareExtension/Application/Support/Info.plist": {"CFBundleDisplayName": "Loksi Share", "CFBundleName": "Loksi Share Extension"},
"BitwardenActionExtension/Application/Support/Info.plist": {"CFBundleDisplayName": "Autofill with Loksi", "CFBundleName": "Loksi Extension"},
"BitwardenNotificationExtension/Application/Support/Info.plist": {"CFBundleDisplayName": "Loksi", "CFBundleName": "Loksi Notification"},
"BitwardenWatchApp/Info.plist": {"CFBundleDisplayName": "Loksi", "CFBundleName": "Loksi Watch App"},
"BitwardenWatchWidgetExtension/Application/Support/Info.plist": {"CFBundleDisplayName": "Loksi Watch Widget", "CFBundleName": "Loksi Watch Widget Extension"},
}
for relative, values in names.items():
path = SRC / relative
for key, value in values.items():
text = path.read_text()
new, count = re.subn(rf"({key}\s*)[^<]*Bitwarden[^<]*()", rf"\g<1>{value}\g<2>", text)
if count != 1:
raise RuntimeError(f"{key} amont modifié : {relative}")
path.write_text(new)
# Couleurs : la correspondance du coffre web (habillage user.vaultwarden.scss.hbs de Loksi web),
# navy en clair, cyan en sombre. Neutres, états, badges et rose des codes restent amont.
# Clé : (apparence, valeur amont). Chaque valeur doit être trouvée au moins une fois.
COLORS = {
("light", "#175DDC"): "#003087", ("dark", "#65ABFF"): "#009CDE", ("dark", "#175DDC"): "#009CDE",
("light", "#DBE5F6"): "#E5EEF9", ("dark", "#AAC3EF"): "#33C3FF", ("light", "#020F66"): "#002260",
}
# Couples texte sur fond à tenir au-dessus de 4,5:1 (WCAG AA), après correspondance.
CONTRAST = [("buttonFilledForeground", "buttonFilledBackground"), ("textInteraction", "backgroundPrimary"),
("textInteraction", "backgroundSecondary"), ("buttonOutlinedForeground", "backgroundSecondary")]
def colorset_value(color):
components = color["color"]["components"]
def channel(value):
value = str(value)
return int(value, 16) if value.startswith("0x") else round(float(value) * 255)
return "#%02X%02X%02X" % tuple(channel(components[k]) for k in ("red", "green", "blue"))
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 (1, 3, 5))
return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)
def adapt_colors():
found, changed, palette = set(), 0, {}
catalogs = [SRC / "BitwardenResources/Colors.xcassets", SRC / "Bitwarden/Application/Support/Assets.xcassets"]
for path in sorted(p for catalog in catalogs for p in catalog.rglob("*.colorset/Contents.json")):
contents = json.loads(path.read_text())
touched = False
for color in contents["colors"]:
dark = any(a.get("value") == "dark" for a in color.get("appearances", []))
key = ("dark" if dark else "light", colorset_value(color))
if key in COLORS:
new = COLORS[key]
components = color["color"]["components"]
for channel, index in (("red", 1), ("green", 3), ("blue", 5)):
components[channel] = "0x" + new[index:index + 2]
found.add(key)
touched = True
changed += 1
palette[(path.parent.stem, key[0])] = colorset_value(color)
if touched:
path.write_text(json.dumps(contents, indent=2) + "\n")
missing = sorted(set(COLORS) - found)
if missing:
raise RuntimeError(f"Couleurs amont introuvables : {missing}")
for text, background in CONTRAST:
for mode in ("light", "dark"):
a, b = sorted((luminance(palette[(text, mode)]), luminance(palette[(background, mode)])))
ratio = (b + 0.05) / (a + 0.05)
if ratio < 4.5:
raise RuntimeError(f"Contraste {text} sur {background} ({mode}) : {ratio:.2f}")
return changed
def adapt_fonts():
"""DM Sans remplacée par la police Loksi, instances de Raleway (ios/fonts.py)."""
out = CACHE / "ios-fonts"
if out.exists():
shutil.rmtree(out)
python = CACHE / "venv/bin/python"
if not python.exists():
run(["python3", "-m", "venv", CACHE / "venv"])
run([python, "-m", "pip", "install", "-q", f"fonttools=={UPSTREAM['font']['fonttools']}"])
run([python, HERE / "fonts.py", CACHE / "Raleway-wght.ttf", CACHE / "Raleway-Italic-wght.ttf", out])
fonts = SRC / "BitwardenResources/Fonts"
old = sorted(fonts.glob("DMSans-*.ttf"))
if len(old) != 6:
raise RuntimeError(f"Polices amont : 6 DM Sans attendues, {len(old)}")
for path in old:
path.unlink()
for path in sorted(out.glob("*.ttf")):
shutil.copy2(path, fonts / path.name)
shutil.copy2(CACHE / "Raleway-OFL.txt", fonts / "OFL-Raleway.txt")
uses = {"BitwardenKit/UI/Platform/Application/Appearance/StyleGuideFont.swift": 5,
"BitwardenKit/UI/Platform/Application/Appearance/UI.swift": 7,
"BitwardenKit/UI/Platform/Application/Views/BitwardenUITextView.swift": 1,
"BitwardenKit/UI/Platform/Application/Views/BitwardenStepper.swift": 1}
for relative, count in uses.items():
replace_once(SRC / relative, "FontFamily.DMSans.", "FontFamily.Loksi.", count=count)
info = SRC / "BitwardenShared/UI/Platform/Application/Support/Info.plist"
for style in ("Bold", "BoldItalic", "Italic", "Regular", "SemiBold", "SemiBoldItalic"):
replace_once(info, f"DMSans-{style}.ttf", f"Loksi-{style}.ttf")
return len(old)
# Pas de création de compte dans l'app : un compte Loksi est créé par l'administrateur
# de l'entreprise (invitation ou SSO), le site reste le seul canal d'acquisition.
# Décision de Romain le 29/09/2026. Indépendant de disableUserRegistration du serveur.
ADMIN_MESSAGE = {
"en": "Your account is created by your company's administrator.",
"fr": "Votre compte est créé par l'administrateur de votre entreprise.",
}
VAULT_ADDRESS_TO_ENTER = {"en": "address to enter", "fr": "adresse à saisir"}
# « Nous contacter » d'À propos, aligné sur Android (demande de Romain du 30/09/2026), et
# l'avis de dérivation validé par Romain le 30/09/2026, le même partout (brand/README.md,
# « Le nom Bitwarden »). Le « © Bitwarden Inc. » amont le suit dans AppInfoService.
ORIGIN_NOTICE = {
"fr": "Loksi, par Aleop. Application Bitwarden® modifiée par Aleop, sous licence GPL v3. "
"Aleop n'est pas affilié à Bitwarden Inc.",
"en": "Loksi, by Aleop. Bitwarden® app modified by Aleop, under the GPL v3. "
"Aleop is not affiliated with Bitwarden Inc.",
}
SUPPORT_ADDRESS = CONFIG["links"]["support"].removeprefix("mailto:")
CONTACT_STRINGS = {
"LoksiOriginNotice": ORIGIN_NOTICE,
"LoksiContactUs": {"en": "Contact us", "fr": "Nous contacter"},
# Source GPL publiée (ordre de Romain du 12/10/2026), même ligne qu'Android.
"LoksiSourceCode": {"en": "Source code", "fr": "Code source"},
# Version de Bitwarden dans À propos, à côté de la mention d'origine (06/10/2026).
"LoksiBasedOnBitwarden": {"en": f"Based on Bitwarden {BITWARDEN_VERSION}.",
"fr": f"Basé sur Bitwarden {BITWARDEN_VERSION}."},
"LoksiVaultNameOrAddress": {"en": "Name or address of your vault", "fr": "Nom ou adresse de votre coffre"},
"LoksiVaultAddressInvalid": {
"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://.",
"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://.",
},
"LoksiNotAVault": {
"en": "No Loksi vault answers at this address. Check the name with your administrator.",
"fr": "Aucun coffre Loksi ne répond à cette adresse. Vérifiez le nom auprès de votre administrateur.",
},
"LoksiDiscoverLoksi": {"en": "Not a customer yet? Discover Loksi", "fr": "Pas encore client ? Découvrir Loksi"},
"LoksiEmailSupportTitle": {"en": "Email support?", "fr": "Écrire au support ?"},
# loksi@aleop.eu et non support@aleop.eu, entrée du support client qui rejette les
# expéditeurs inconnus. Décision de Romain du 03/10/2026, comme Android.
"LoksiEmailSupportMessage": {
"en": f"Your email app opens with a message to {SUPPORT_ADDRESS}. For data protection, write to dpo@aleop.eu.",
"fr": f"Votre messagerie s'ouvre avec un courriel pour {SUPPORT_ADDRESS}. "
"Pour la protection des données, écrivez à dpo@aleop.eu.",
},
}
def hide_registration():
carousel = SRC / "BitwardenShared/UI/Auth/IntroCarousel/IntroCarouselView.swift"
replace_once(carousel, """ AsyncButton(Localizations.createAccount) {
await store.perform(.createAccount)
}
.buttonStyle(.primary())
Button(Localizations.logIn) {
store.send(.logIn)
}
.buttonStyle(.secondary())""", """ Button(Localizations.logIn) {
store.send(.logIn)
}
.buttonStyle(.primary())""")
landing = SRC / "BitwardenShared/UI/Auth/Landing/LandingView.swift"
replace_once(landing, """ if !store.state.isCreateAccountButtonHidden {
HStack(spacing: 4) {
Spacer()
Text(Localizations.newAroundHere)
.foregroundColor(SharedAsset.Colors.textSecondary.swiftUIColor)
Button(Localizations.createAccount) {
store.send(.createAccountPressed)
}
.accessibilityIdentifier("CreateAccountButton")
.foregroundColor(SharedAsset.Colors.textInteraction.swiftUIColor)
Spacer()
}
.styleGuide(.footnote)
}""", """ Text(Localizations.loksiAccountCreatedByAdministrator)
.foregroundColor(SharedAsset.Colors.textSecondary.swiftUIColor)
.frame(maxWidth: .infinity, alignment: .center)
.multilineTextAlignment(.center)
.styleGuide(.footnote)
if store.state.serverHost == nil {
// Loksi: no vault entered yet, a link for whoever is not a customer yet.
Link(Localizations.loksiDiscoverLoksi, destination: ExternalLinksConstants.loksiProduct)
.foregroundColor(SharedAsset.Colors.textInteraction.swiftUIColor)
.frame(maxWidth: .infinity, alignment: .center)
.styleGuide(.footnote)
}""")
for language, message in ADMIN_MESSAGE.items():
strings = SRC / f"BitwardenResources/Localizations/{language}.lproj/Localizable.strings"
text = strings.read_text()
if "LoksiAccountCreatedByAdministrator" in text:
raise RuntimeError("Chaîne Loksi déjà présente dans l'amont")
extra = "".join(f'"{key}" = "{values[language]}";\n' for key, values in CONTACT_STRINGS.items())
strings.write_text(text.rstrip("\n") + f'\n"LoksiAccountCreatedByAdministrator" = "{message}";\n'
f'"LoksiVaultAddressToEnter" = "{VAULT_ADDRESS_TO_ENTER[language]}";\n' + extra)
# Carrousel d'accueil : textes Loksi validés par Romain le 29/09/2026. Français pour fr,
# anglais pour toutes les autres langues : aucune ne garde le discours de Bitwarden.
CAROUSEL = {
"fr": {
"IntroCarouselPage1Title": "Les accès de l'équipe, dans un coffre à vous",
"IntroCarouselPage1Message": "Identifiants, cartes et notes sont chiffrés sur votre téléphone. "
"Le serveur ne voit jamais vos secrets en clair.",
"IntroCarouselPage2Title": "Connexion en un geste",
"IntroCarouselPage2Message": "Face ID et le remplissage automatique ouvrent vos comptes sans rien taper.",
"IntroCarouselPage3Title": "Un mot de passe solide pour chaque compte",
"IntroCarouselPage3Message": "Le générateur les crée, Loksi les retient à votre place.",
"IntroCarouselPage4Title": "Vos secrets, dans votre coffre, en France",
"IntroCarouselPage4Message": "Le même coffre sur votre téléphone, dans votre navigateur "
"et sur le coffre web de votre entreprise.",
},
"en": {
"IntroCarouselPage1Title": "Your team's access, in a vault of your own",
"IntroCarouselPage1Message": "Logins, cards and notes are encrypted on your phone. "
"The server never sees your secrets in clear text.",
"IntroCarouselPage2Title": "Log in with one gesture",
"IntroCarouselPage2Message": "Face ID and autofill open your accounts without typing anything.",
"IntroCarouselPage3Title": "A strong password for every account",
"IntroCarouselPage3Message": "The generator creates them and Loksi remembers them for you.",
"IntroCarouselPage4Title": "Your secrets, in your vault, in France",
"IntroCarouselPage4Message": "The same vault on your phone, in your browser "
"and on your company's web vault.",
},
}
def adapt_carousel():
line = re.compile(r'^("(IntroCarouselPage[1-4](?:Title|Message))"\s*=\s*")((?:[^"\\]|\\.)*)(";)', re.M)
files = sorted((SRC / "BitwardenResources/Localizations").glob("*.lproj/Localizable.strings"))
for path in files:
texts = CAROUSEL["fr" if path.parent.name == "fr.lproj" else "en"]
seen = []
def replace(match):
seen.append(match.group(2))
return match.group(1) + texts[match.group(2)].replace('"', '\\"') + match.group(4)
path.write_text(line.sub(replace, path.read_text()))
if path.parent.name == "Base.lproj" and not seen:
continue # Base.lproj ne porte pas le carrousel (relevé le 29/09/2026)
if sorted(seen) != sorted(texts):
raise RuntimeError(f"Carrousel amont modifié dans {path.parent.name} : {sorted(seen)}")
return len(files)
# Illustrations Loksi dessinées par la charte (brand/illustrations-mobiles/, style validé
# par Romain le 29/09/2026). Chaque PDF Bitwarden est remplacé sous le même nom par le
# maître Loksi converti en PDF vectoriel à la taille amont : les Contents.json, donc
# les apparences clair et sombre, restent ceux de l'amont. Premium et vault hors jeu.
ILLUSTRATIONS_DIR = "BitwardenShared/UI/Platform/Application/Support/Images.xcassets/Images"
ILLUSTRATIONS = {
f"{ILLUSTRATIONS_DIR}/Illustrations/items.imageset": "coffre",
f"{ILLUSTRATIONS_DIR}/Illustrations/biometrics-phone.imageset": "biometrie",
f"{ILLUSTRATIONS_DIR}/Illustrations/generate.imageset": "generateur",
f"{ILLUSTRATIONS_DIR}/Illustrations/secure-devices.imageset": "appareils",
"BitwardenResources/Illustrations.xcassets/secure-devices.imageset": "appareils",
f"{ILLUSTRATIONS_DIR}/Illustrations/devices.imageset": "appareils",
f"{ILLUSTRATIONS_DIR}/Autofill/autofill.imageset": "autofill",
f"{ILLUSTRATIONS_DIR}/Illustrations/lock.imageset": "verrou",
f"{ILLUSTRATIONS_DIR}/Illustrations/no-items.imageset": "dossier-vide",
f"{ILLUSTRATIONS_DIR}/Illustrations/send.imageset": "send",
f"{ILLUSTRATIONS_DIR}/Illustrations/import.imageset": "import",
f"{ILLUSTRATIONS_DIR}/Illustrations/keyhole.imageset": "synchro-navigateur",
f"{ILLUSTRATIONS_DIR}/Illustrations/email.imageset": "email",
f"{ILLUSTRATIONS_DIR}/Illustrations/email-otp.imageset": "email-code",
f"{ILLUSTRATIONS_DIR}/Illustrations/authenticator-app.imageset": "authentificateur",
f"{ILLUSTRATIONS_DIR}/Illustrations/yubikey.imageset": "cle-securite",
f"{ILLUSTRATIONS_DIR}/Illustrations/item-transfer.imageset": "organisation",
f"{ILLUSTRATIONS_DIR}/Illustrations/item-transfer-warning.imageset": "organisation",
}
def pdf_size(path):
info = subprocess.run(["pdfinfo", path], capture_output=True, text=True, check=True).stdout
match = re.search(r"Page size:\s+([\d.]+) x ([\d.]+) pts", info)
return float(match.group(1)), float(match.group(2))
def raster_count(path):
listing = subprocess.run(["pdfimages", "-list", path], capture_output=True, text=True, check=True).stdout
return len(listing.strip().splitlines()) - 2
def adapt_illustrations():
sources = REPO / "brand/illustrations-mobiles/sources"
replaced = 0
for relative, name in ILLUSTRATIONS.items():
imageset = SRC / relative
contents = json.loads((imageset / "Contents.json").read_text())
entries = [i for i in contents["images"] if i.get("filename", "").endswith(".pdf")]
if not entries or len(entries) != len(list(imageset.glob("*.pdf"))):
raise RuntimeError(f"Illustration amont modifiée : {relative}")
for entry in entries:
dark = any(a.get("value") == "dark" for a in entry.get("appearances", []))
svg = sources / f"{name}-{'sombre' if dark else 'clair'}.svg"
target = imageset / entry["filename"]
width, height = pdf_size(target)
# 72 ppp : un pixel de rsvg-convert vaut un point PDF, la taille amont est gardée.
subprocess.run(["rsvg-convert", "-f", "pdf", "--dpi-x", "72", "--dpi-y", "72",
"-w", str(round(width)), "-h", str(round(height)), "-o", target, svg], check=True)
if raster_count(target):
raise RuntimeError(f"{target.name} : image matricielle dans le PDF, il doit rester vectoriel")
replaced += 1
# Canari : le même contrôle doit voir une image matricielle quand il y en a une.
canary = CACHE / "canari-raster.pdf"
subprocess.run(["sips", "-s", "format", "pdf", CACHE / "ios-graphics/icon-1024.png", "--out", canary],
capture_output=True, check=True)
if not raster_count(canary):
raise RuntimeError("Canari muet : le contrôle des images matricielles ne voit rien")
return replaced
# Choix du serveur : pas de bitwarden.com ni bitwarden.eu, le client saisit l'adresse de
# son coffre. La ligne « Connexion sur » affiche cette adresse et ouvre directement la
# saisie. Demande de Romain le 29/09/2026 ; les régions restent dans le code amont.
SERVER_STRINGS = {
"SelfHostedEnvironment": {"fr": "Votre coffre Loksi", "en": "Your Loksi vault"},
# Après un import : « Connectez-vous sur bitwarden.com... » ne vaut pas pour Loksi.
"LogInAtBitwardenToEasilyManageYourAccountAndUpdateSettings": {
"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.",
},
# Nom ou adresse du coffre (04/10/2026) : la même aide qu'Android et l'extension.
"SelfHostedEnvironmentFooter": {
"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 server_entry():
helper = SRC / "BitwardenShared/UI/Auth/Utilities/RegionHelper.swift"
text = helper.read_text()
start = text.index(" let actions = RegionType.userSelectableCases\n")
end = text.index(" await coordinator.showAlert(alert)\n }\n") + len(" await coordinator.showAlert(alert)\n")
body = text[start:end]
if text.count(body) != 1 or "preferredStyle: .actionSheet" not in body:
raise RuntimeError("Sélecteur de région amont modifié")
helper.write_text(text.replace(body, """ // Loksi: no region list, the vault address is entered directly.
await coordinator.navigate(to: .selfHosted(currentRegion: currentRegion ?? .selfHosted), context: delegate)
"""))
replace_once(SRC / "BitwardenShared/UI/Auth/Landing/LandingState.swift",
" /// The region selected by the user.\n var region: RegionType\n",
" /// The region selected by the user.\n var region: RegionType\n\n"
" /// Loksi: the host of the server in use, shown instead of the region name.\n"
" var serverHost: String?\n")
landing = SRC / "BitwardenShared/UI/Auth/Landing/LandingProcessor.swift"
replace_once(landing,
" await services.environmentService.setPreAuthURLs(urls: urls)\n state.region = region\n",
" await services.environmentService.setPreAuthURLs(urls: urls)\n state.region = region\n"
" state.serverHost = urls.isLoksiUnset ? nil : urls.base?.host\n")
replace_once(landing, """ case .continuePressed:
updateRememberedEmail()
await validateEmailAndContinue()
""", """ case .continuePressed:
updateRememberedEmail()
guard state.serverHost != nil else {
// Loksi: no vault address yet, ask for it first.
await regionHelper.presentRegionSelectorAlert(
title: Localizations.loggingInOn,
currentRegion: .selfHosted,
)
return
}
await validateEmailAndContinue()
""")
replace_once(SRC / "BitwardenShared/UI/Auth/Landing/LandingView.swift",
"regionName: store.state.region.baseURLDescription,",
"regionName: store.state.serverHost ?? Localizations.loksiVaultAddressToEnter,")
coordinator = SRC / "BitwardenShared/UI/Auth/AuthCoordinator.swift"
replace_once(coordinator,
" let preAuthEnvironmentURLs = services.appSettingsStore.preAuthEnvironmentURLs ?? EnvironmentURLData()\n"
" var state = SelfHostedState()\n",
" let preAuthEnvironmentURLs = services.appSettingsStore.preAuthEnvironmentURLs ?? EnvironmentURLData()\n"
" // Loksi: the \"not entered yet\" marker is shown as an empty field.\n"
" let serverUrl = preAuthEnvironmentURLs.isLoksiUnset ? \"\" : preAuthEnvironmentURLs.base?.sanitized.description\n"
" var state = SelfHostedState()\n")
replace_once(coordinator,
" serverUrl: preAuthEnvironmentURLs.base?.sanitized.description ?? \"\",\n",
" serverUrl: serverUrl ?? \"\",\n")
for key, messages in SERVER_STRINGS.items():
line = re.compile(r'^("' + key + r'"\s*=\s*")((?:[^"\\]|\\.)*)(";)', re.M)
for path in sorted((SRC / "BitwardenResources/Localizations").glob("*.lproj/Localizable.strings")):
if path.parent.name == "Base.lproj":
continue
message = messages["fr" if path.parent.name == "fr.lproj" else "en"]
text, count = line.subn(lambda m: m.group(1) + message.replace('"', '\\"') + m.group(3), path.read_text())
if count != 1:
raise RuntimeError(f"{key} absent de {path.parent.name}")
path.write_text(text)
# Nom ou adresse du coffre (décision de Romain du 04/10/2026, même règle qu'Android et
# l'extension) : 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 ». La
# logique vit dans ios/swift/LoksiVault.swift, testée seule (LoksiVaultTests.swift, canaris
# compris) ; tests() exige qu'elle ait tourné.
LOKSI_PRODUCT = "https://www.aleop.eu/loksi/"
LOKSI_SWIFT_DIR = "BitwardenShared/UI/Auth/Landing/SelfHosted"
LOKSI_SWIFT = ("LoksiVault.swift", "LoksiVaultTests.swift")
LOKSI_VAULT_TESTS = 6
# Version vue par le serveur (relevé de la discussion de l'extension, 06/10/2026) : Vaultwarden
# lit Bitwarden-Client-Version et peut activer des fonctions selon elle. Il doit voir la
# version amont réelle du code, pas la nôtre, qui ne vaut que pour l'affichage. Trois appels
# lisaient Bundle.main.appVersion : l'en-tête, le SDK et le User-Agent.
LOKSI_UPSTREAM_SWIFT = "BitwardenShared/Core/Platform/Utilities/LoksiUpstream.swift"
SERVER_VERSION_USES = {
"BitwardenShared/Core/Platform/Services/API/APIService.swift": " appVersion: Bundle.main.appVersion,\n",
"BitwardenShared/Core/Platform/Services/ClientBuilder.swift": " bitwardenClientVersion: Bundle.main.appVersion,\n",
# User-Agent seulement : l'autre appVersion de ce fichier sert à la demande d'avis, locale.
"BitwardenShared/Core/Platform/Services/ServiceContainer.swift":
' appName: "Bitwarden_Mobile",\n appVersion: Bundle.main.appVersion,\n',
}
# « Plus de Bitwarden, à moins que ce soit totalement obligatoire » (Romain, 09/10/2026).
# Restent par obligation : le schéma bitwarden:// (retours SSO, Duo, WebAuthn, imposé par
# Vaultwarden 1.37.3, src/sso.rs), Bitwarden-Client-Version et Device-Type que le serveur lit,
# la mention GPL, et les noms des cibles et modules du projet amont, jamais affichés.
FRAMEWORK_IDS = {
"Configs/BitwardenKit-Debug.xcconfig": ".bitwarden-kit", "Configs/BitwardenKit-Release.xcconfig": ".bitwarden-kit",
"Configs/BitwardenResources-Debug.xcconfig": ".bitwarden-resources",
"Configs/BitwardenResources-Release.xcconfig": ".bitwarden-resources",
"Configs/BitwardenShared-Debug.xcconfig": ".bitwarden-shared", "Configs/BitwardenShared-Release.xcconfig": ".bitwarden-shared",
}
# Ligne d'À propos qui ouvre le coffre web : libellé choisi par Romain le 09/10/2026.
WEB_VAULT_LABEL = {"fr": "Loksi : Coffre-fort Web", "en": "Loksi: Web vault"}
def without_bitwarden():
for relative, suffix in FRAMEWORK_IDS.items():
replace_once(SRC / relative, f"{suffix}\n", suffix.replace("bitwarden", "loksi") + "\n")
for language, label in WEB_VAULT_LABEL.items():
strings = SRC / f"BitwardenResources/Localizations/{language}.lproj/Localizable.strings"
text, count = re.subn(r'^"WebVault" = "[^"]*";$', f'"WebVault" = "{label}";', strings.read_text(), flags=re.M)
if count != 1:
raise RuntimeError(f"WebVault absent de {language}.lproj")
strings.write_text(text)
# Nom de l'appli qui exporte, montré par iOS lors d'un transfert d'identifiants.
replace_once(SRC / "BitwardenShared/Core/Tools/Utilities/CredentialManagerFactory.swift",
'exporterDisplayName: "Bitwarden",', 'exporterDisplayName: "Loksi",')
def upstream_version_for_server():
target = SRC / LOKSI_UPSTREAM_SWIFT
if target.exists():
raise RuntimeError("LoksiUpstream.swift déjà présent dans l'amont")
target.write_text(
"// GPL-3.0-only. Generated by mobile/ios/loksi.py from mobile/upstream.json (ios.tag).\n\n"
"/// Loksi: the Bitwarden version this code is built from, sent to the server.\n"
"///\n"
"/// The displayed version is Loksi's own (AAAA.M.n). The server reads Bitwarden-Client-Version,\n"
"/// the SDK client version and the User-Agent to enable features, so it gets the real upstream one.\n"
"///\n"
"enum LoksiUpstream {\n"
f" /// The upstream Bitwarden version, {json.dumps(CONFIG['tag'])} without its prefix and suffix.\n"
f" static let bitwardenVersion = {json.dumps(BITWARDEN_VERSION)}\n"
"}\n")
for relative, line in SERVER_VERSION_USES.items():
# Le User-Agent porte aussi le nom Loksi : Vaultwarden 1.37.3 ne lit pas le User-Agent
# entrant (src/ ne le cite que pour ses propres requêtes, relevé le 09/10/2026).
replace_once(SRC / relative, line, line.replace("Bundle.main.appVersion", "LoksiUpstream.bitwardenVersion")
.replace('appName: "Bitwarden_Mobile"', 'appName: "Loksi"'))
def vault_name_entry():
for name in LOKSI_SWIFT:
target = SRC / LOKSI_SWIFT_DIR / name
if target.exists():
raise RuntimeError(f"Fichier Loksi déjà présent dans l'amont : {name}")
shutil.copy2(HERE / "swift" / name, target)
processor = SRC / LOKSI_SWIFT_DIR / "SelfHostedProcessor.swift"
replace_once(processor, """ private func saveEnvironment() async {
guard areURLsValid() else {""", """ private func saveEnvironment() async {
// 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.
guard let loksiBase = LoksiVault.address(for: state.serverUrl) else {
coordinator.showAlert(Alert.defaultAlert(
title: Localizations.anErrorHasOccurred,
message: Localizations.loksiVaultAddressInvalid,
))
return
}
guard await LoksiVault.isVault(loksiBase) else {
coordinator.showAlert(Alert.defaultAlert(
title: Localizations.anErrorHasOccurred,
message: Localizations.loksiNotAVault,
))
return
}
state.serverUrl = loksiBase.absoluteString
guard areURLsValid() else {""")
replace_once(SRC / LOKSI_SWIFT_DIR / "SelfHostedView.swift", " title: Localizations.serverUrl,\n",
" title: Localizations.loksiVaultNameOrAddress,\n")
# Barre d'onglets : pictogrammes Loksi de la charte (brand/illustrations-mobiles/onglets/),
# un SVG clair et un sombre par état, posés sous les noms de PDF amont (dont la faute
# « vault-actve-light.pdf », gardée pour ne pas toucher au Contents.json).
def alpha_at(pdf, fx, fy):
"""Opacité du pixel en (fx, fy), fractions de la largeur et de la hauteur, du PDF rendu en
PNG transparent (décodeur PNG minimal)."""
import struct
import zlib
png = CACHE / "controle-onglet"
subprocess.run(["pdftocairo", "-png", "-transp", "-singlefile", "-r", "288", pdf, png], check=True)
data = (CACHE / "controle-onglet.png").read_bytes()
width, height, depth, color = struct.unpack(">IIBB", data[16:26])
if (depth, color) != (8, 6):
raise RuntimeError("PNG de contrôle inattendu : RGBA 8 bits attendu")
raw, pos = b"", 8
while pos < len(data):
length, kind = struct.unpack(">I4s", data[pos:pos + 8])
if kind == b"IDAT":
raw += data[pos + 8:pos + 8 + length]
pos += 12 + length
raw = zlib.decompress(raw)
stride, rows, prev = width * 4, [], bytearray(width * 4)
for y in range(height):
kind, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
for x in range(stride):
a = line[x - 4] if x >= 4 else 0
b, c = prev[x], prev[x - 4] if x >= 4 else 0
if kind == 1:
line[x] = (line[x] + a) & 255
elif kind == 2:
line[x] = (line[x] + b) & 255
elif kind == 3:
line[x] = (line[x] + (a + b) // 2) & 255
elif kind == 4:
pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c)
line[x] = (line[x] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
rows.append(line)
prev = line
return rows[int(height * fy)][int(width * fx) * 4 + 3]
def adapt_tab_icons():
sources = REPO / "brand/illustrations-mobiles/onglets"
tabbar = SRC / "BitwardenResources/Icons.xcassets/TabBar"
replaced = 0
for imageset in sorted(tabbar.glob("*.imageset")):
name = imageset.stem
contents = json.loads((imageset / "Contents.json").read_text())
entries = [i for i in contents["images"] if i.get("filename", "").endswith(".pdf")]
if len(entries) != 2 or len(list(imageset.glob("*.pdf"))) != 2:
raise RuntimeError(f"Onglet amont modifié : {name}")
for entry in entries:
dark = any(a.get("value") == "dark" for a in entry.get("appearances", []))
target = imageset / entry["filename"]
width, height = pdf_size(target)
subprocess.run(["rsvg-convert", "-f", "pdf", "--dpi-x", "72", "--dpi-y", "72", "-w", str(round(width)),
"-h", str(round(height)), "-o", target,
sources / f"{name}-{'dark' if dark else 'light'}.svg"], check=True)
if raster_count(target):
raise RuntimeError(f"{target.name} : image matricielle dans le PDF")
replaced += 1
if replaced != 16:
raise RuntimeError(f"16 pictogrammes attendus, {replaced}")
# Le moyeu de la roue crantée est un évidement (fill-rule evenodd) : il doit rester
# transparent. Canari : le même contrôle sur le bloc plein de gauche du coffre actif
# (son centre est creux par dessin, vérifié à l'image le 29/09/2026).
if alpha_at(tabbar / "settings-idle.imageset/settings-idle-light.pdf", 0.5, 0.5) != 0:
raise RuntimeError("Évidement perdu : le moyeu de la roue n'est pas transparent")
vault = next((tabbar / "vault-active.imageset").glob("*light.pdf"))
if alpha_at(vault, 0.3, 0.7) == 0:
raise RuntimeError("Canari muet : le contrôle de transparence ne voit rien")
return replaced
def render_graphics():
"""Icône et logos Loksi, rendus 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 / "ios-graphics"
if out.exists():
shutil.rmtree(out)
run(["node", HERE / "render.mjs", out], cwd=node)
return out
def write_logo(imageset, graphics):
"""Logo complet Loksi, clair et sombre, rendu d'origine au lieu du gabarit teinté."""
for old in imageset.glob("*.png"):
old.unlink()
images = []
for variant, appearance in (("clair", None), ("sombre", "dark")):
for scale in (1, 2, 3):
name = f"loksi-logo-{variant}@{scale}x.png"
shutil.copy2(graphics / f"logo-{variant}@{scale}x.png", imageset / name)
image = {"filename": name, "idiom": "universal", "scale": f"{scale}x"}
if appearance:
image["appearances"] = [{"appearance": "luminosity", "value": appearance}]
images.append(image)
contents = {"images": images, "info": {"author": "xcode", "version": 1},
"properties": {"template-rendering-intent": "original"}}
(imageset / "Contents.json").write_text(json.dumps(contents, indent=2) + "\n")
def adapt_graphics(graphics):
support = SRC / "Bitwarden/Application/Support"
# Les icônes Icon Composer (.icon) de Bitwarden sont retirées : Xcode se rabat sur
# le catalogue d'actifs, où l'icône Loksi remplace celles de production et de dev.
for icon in ("AppIcon.icon", "AppIcon-Dev.icon", "AppIcon-Beta.icon"):
shutil.rmtree(support / icon)
for name in ("AppIcon", "AppIcon-Dev", "AppIcon-Beta"):
iconset = support / f"Assets.xcassets/{name}.appiconset"
contents = json.loads((iconset / "Contents.json").read_text())
pngs = sorted({image["filename"] for image in contents["images"] if "filename" in image})
if len(pngs) != 1:
raise RuntimeError(f"{name} : une seule image 1024 attendue, {pngs}")
shutil.copy2(graphics / "icon-1024.png", iconset / pngs[0])
write_logo(support / "Assets.xcassets/logoBitwarden.imageset", graphics)
write_logo(SRC / "BitwardenShared/UI/Platform/Application/Support/Images.xcassets/logo.imageset", graphics)
return 5
def prepare():
check_version()
fetch()
if SRC.exists():
shutil.rmtree(SRC)
extract = CACHE / "ios-extract"
if extract.exists():
shutil.rmtree(extract)
with tarfile.open(CACHE / "ios.tar.gz") as archive:
archive.extractall(extract, filter="data")
(extract / ("ios-" + CONFIG["tag"].lstrip("v"))).rename(SRC)
shutil.rmtree(extract)
# État amont figé dans un dépôt local : changes compare à ce commit, et le script
# amont lint-changes.sh, lancé après compilation, passe SwiftLint et SwiftFormat
# sur les fichiers Swift que Loksi modifie.
git("init", "-q")
git("add", "-A", "-f")
git("commit", "-q", "-m", f"bitwarden/ios {CONFIG['tag']} ({CONFIG['commit']})")
(SRC / "Configs/Local-bwpm.xcconfig").write_text(LOCAL_XCCONFIG)
# Firebase Crashlytics retiré : paquet, liens, configurations et rapporteur. Le
# rapporteur OSLog de BitwardenKit, déjà utilisé en debug, sert partout.
replace_once(SRC / "project-common.yml", """ Firebase:
url: https://github.com/firebase/firebase-ios-sdk
exactVersion: 12.14.0
""", "")
pm = SRC / "project-pm.yml"
replace_once(pm, """ - package: Firebase
product: FirebaseCrashlytics
""", "", count=2)
replace_once(pm, """ - path: Bitwarden/Application/Support/GoogleService-Info.plist
buildPhase: resources
""", "")
replace_once(pm, """ - path: BitwardenWatchApp/GoogleService-Info.plist
buildPhase: resources
""", "")
for relative in ("Bitwarden/Application/Support/GoogleService-Info.plist", "BitwardenWatchApp/GoogleService-Info.plist",
"Bitwarden/Application/Services/ErrorReporter/CrashlyticsErrorReporter.swift"):
(SRC / relative).unlink()
replace_once(SRC / "Bitwarden/Application/Services/ErrorReporter/ErrorReporterFactory.swift", """ #if DEBUG
OSLogErrorReporter()
#else
CrashlyticsErrorReporter.shared
#endif
""", """ OSLogErrorReporter()
""")
replace_once(SRC / "BitwardenWatchApp/ExtensionDelegate.swift", """import FirebaseCore
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
#if !DEBUG
FirebaseApp.configure()
#endif
}
}""", """import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {}
}""")
# Aucun serveur quand rien n'est enregistré : le marqueur UNSET_SERVER, que l'interface
# présente comme « adresse à saisir ». La configuration gérée baseEnvironmentUrl (MDM),
# le compte actif et le choix de l'utilisateur passent avant.
replace_once(SRC / "BitwardenKit/Core/Platform/Models/Domain/EnvironmentURLData.swift", """public extension EnvironmentURLData {
/// The default URLs for the US region.""", f"""public extension EnvironmentURLData {{
/// Loksi: whether no vault address has been entered yet.
var isLoksiUnset: Bool {{
base == Self.loksiUnset.base
}}
}}
public extension EnvironmentURLData {{
/// Loksi: no default server. This never-resolving address stands for "not entered yet".
static let loksiUnset = EnvironmentURLData(base: URL(string: {json.dumps(UNSET_SERVER)})!)
/// The default URLs for the US region.""")
service = SRC / "BitwardenShared/Core/Platform/Services/EnvironmentService.swift"
replace_once(service, "_environmentURLs = EnvironmentURLs(environmentURLData: .defaultUS)",
"_environmentURLs = EnvironmentURLs(environmentURLData: .loksiUnset)")
replace_once(service, """ } else {
urls = .defaultUS
}""", """ } else {
urls = .loksiUnset
}""")
replace_once(SRC / "BitwardenShared/UI/Auth/Utilities/RegionHelper.swift",
"await delegate?.setRegion(.unitedStates, .defaultUS)", "await delegate?.setRegion(.selfHosted, .loksiUnset)")
# Mention d'À propos : Loksi en tête, l'avis de copyright de Bitwarden gardé comme la GPL
# l'impose. Demande de Romain le 29/09/2026. Trait d'union au lieu du demi-cadratin.
replace_once(SRC / "BitwardenKit/Core/Platform/Services/AppInfoService.swift",
' "© Bitwarden Inc. 2015\\(String.enDash)\\(Calendar.current.component(.year, from: timeProvider.presentTime))"\n',
' let year = Calendar.current.component(.year, from: timeProvider.presentTime)\n'
' return "\\(Localizations.loksiOriginNotice) \\(Localizations.loksiBasedOnBitwarden) "\n'
' + "© Bitwarden Inc. 2015-\\(year)"\n')
# À propos : l'interrupteur « Envoyer les journaux de plantage » pilotait Crashlytics,
# retiré ; il ne fait plus rien. Masqué à la demande de Romain le 29/09/2026.
replace_once(SRC / "BitwardenShared/UI/Platform/Settings/Settings/About/AboutView.swift",
" VStack(alignment: .leading, spacing: 8) {\n submitCrashLogs\n\n",
" VStack(alignment: .leading, spacing: 8) {\n")
# Aide et confidentialité : les pages Loksi du site (vitrine, 29/09/2026) au lieu de
# celles de Bitwarden. Le libellé « Centre d'aide Bitwarden » devient Loksi avec les
# autres chaînes, la clé n'est plus gardée.
links = SRC / "BitwardenKit/Core/Platform/Utilities/ExternalLinksConstants.swift"
replace_once(links, 'helpAndFeedback = URL(string: "https://bitwarden.com/help/")!',
f'helpAndFeedback = URL(string: "{CONFIG["links"]["help"]}")!')
replace_once(links, 'privacyPolicy = URL(string: "https://bitwarden.com/privacy/")!',
f'privacyPolicy = URL(string: "{CONFIG["links"]["privacy"]}")!')
replace_once(links, 'flightRecorderHelp = URL(string: "https://bitwarden.com/help/flight-recorder")!',
f'flightRecorderHelp = URL(string: "{CONFIG["links"]["help"]}")!')
# Liens « En savoir plus » vers l'aide, les offres ou les conditions de Bitwarden : tous
# vers l'aide Loksi, règle de brand/README.md (« plus aucun lien vers l'aide de
# Bitwarden »). Relevé le 02/10/2026 dans le .ipa Release : 15 adresses bitwarden.com dans ce fichier.
shared_links = SRC / "BitwardenShared/Core/Platform/Utilities/ExternalLinksConstants.swift"
text, count = re.subn(r'"https://bitwarden\.com/[^"]*"', json.dumps(CONFIG["links"]["help"]), shared_links.read_text())
if count != 15:
raise RuntimeError(f"Liens Bitwarden amont : 15 attendus, {count}")
shared_links.write_text(text)
# « Nous contacter » : ligne sous la confidentialité, confirmation puis messagerie.
replace_once(links, f'privacyPolicy = URL(string: "{CONFIG["links"]["privacy"]}")!\n',
f'privacyPolicy = URL(string: "{CONFIG["links"]["privacy"]}")!\n\n'
f' /// Loksi: the support address, opened in the email app.\n'
f' public static let loksiContactSupport = URL(string: "{CONFIG["links"]["support"]}")!\n\n'
f' /// Loksi: the product page, for whoever is not a customer yet.\n'
f' public static let loksiProduct = URL(string: "{LOKSI_PRODUCT}")!\n\n'
f' /// Loksi: the GPL source of the app, required before any distribution.\n'
f' public static let loksiSourceCode = URL(string: "{CONFIG["links"]["source"]}")!\n')
about = SRC / "BitwardenShared/UI/Platform/Settings/Settings/About"
replace_once(about / "AboutAction.swift", " /// The privacy policy button was tapped.\n case privacyPolicyTapped\n",
" /// The privacy policy button was tapped.\n case privacyPolicyTapped\n\n"
" /// Loksi: the contact us button was tapped.\n case contactUsTapped\n\n"
" /// Loksi: the source code button was tapped.\n case sourceCodeTapped\n")
replace_once(about / "AboutProcessor.swift", " case .privacyPolicyTapped:\n", """ case .contactUsTapped:
coordinator.showAlert(Alert(
title: Localizations.loksiEmailSupportTitle,
message: Localizations.loksiEmailSupportMessage,
alertActions: [
AlertAction(title: Localizations.cancel, style: .cancel),
AlertAction(title: Localizations.continue, style: .default) { _ in
self.state.url = ExternalLinksConstants.loksiContactSupport
},
],
))
case .sourceCodeTapped:
state.url = ExternalLinksConstants.loksiSourceCode
case .privacyPolicyTapped:
""")
replace_once(about / "AboutView.swift",
" externalLinkRow(Localizations.privacyPolicy, action: .privacyPolicyTapped)\n\n",
" externalLinkRow(Localizations.privacyPolicy, action: .privacyPolicyTapped)\n\n"
" externalLinkRow(Localizations.loksiContactUs, action: .contactUsTapped)\n\n"
" externalLinkRow(Localizations.loksiSourceCode, action: .sourceCodeTapped)\n\n")
# « En savoir plus sur les organisations » ouvre bitwarden.com : offre Bitwarden sans
# objet pour Loksi, retirée (règle de brand/README.md, « Le nom Bitwarden »).
replace_once(SRC / "BitwardenShared/UI/Platform/Settings/Settings/About/AboutView.swift",
" externalLinkRow(Localizations.learnOrg, action: .learnAboutOrganizationsTapped)\n\n", "")
# Pas de demande de notifications : l'explication amont promet une synchronisation par
# push, et Loksi n'a ni aps-environment ni relais push (pas décidé). Vu sur l'iPhone de
# Romain le 02/10/2026, première ouverture du coffre. À remettre avec le push.
replace_once(SRC / "BitwardenShared/UI/Vault/Vault/VaultList/VaultListProcessor.swift",
" case .notDetermined:\n await requestNotificationPermissions()\n",
" case .notDetermined:\n // Loksi: no push relay yet, so no push permission request.\n break\n")
# Pas d'app Apple Watch : elle n'affichait que les codes TOTP, jamais essayée, et elle
# obligeait à fournir des captures de montre à l'App Store. Retirée sur décision de
# Romain du 03/10/2026, avec l'interrupteur « Se connecter à la montre » de l'iPhone.
replace_once(SRC / "project-pm.yml", " - target: BitwardenShareExtension\n - target: BitwardenWatchApp\n",
" - target: BitwardenShareExtension\n")
replace_once(SRC / "BitwardenShared/UI/Platform/Settings/Settings/Other/OtherSettingsProcessor.swift",
" state.shouldShowConnectToWatchToggle = services.watchService.isSupported()\n",
" // Loksi: no watch app in the bundle.\n state.shouldShowConnectToWatchToggle = false\n")
# Région affichée avant le chargement : sinon « bitwarden.com » s'affiche un instant.
replace_once(SRC / "BitwardenShared/UI/Auth/Landing/LandingState.swift",
"region: RegionType = .unitedStates,", "region: RegionType = .selfHosted,")
# Domaines associés de Bitwarden retirés : jamais vérifiables pour Loksi. Le schéma
# bitwarden:// reste, Vaultwarden 1.37.3 l'impose pour le retour SSO mobile.
entitlements = SRC / "Bitwarden/Application/Support/Bitwarden.entitlements"
text, count = re.subn(r"\s*com\.apple\.developer\.associated-domains\s*.*?", "",
entitlements.read_text(), flags=re.S)
if count != 1 or "bitwarden" in text.lower():
raise RuntimeError("Domaines associés Bitwarden : bloc amont modifié")
entitlements.write_text(text)
info = SRC / "Bitwarden/Application/Support/Info.plist"
replace_once(info, "com.8bit.bitwarden.url", f"{BUNDLE_ID}.url")
replace_once(info, "com.8bit.bitwarden", f"{BUNDLE_ID}")
# Code de conformité export déposé par Bitwarden chez Apple : Loksi aura le sien.
replace_once(info, """ ITSEncryptionExportComplianceCode
ecf076d3-4824-4d7b-b716-2a9a47d7d296
""", "")
# Type d'échange avec l'extension d'action et service de trousseau de la montre.
replace_once(SRC / "BitwardenShared/Core/Platform/Utilities/Constants.swift",
'"com.8bit.bitwarden.extension-setup"', f'"{BUNDLE_ID}.extension-setup"')
replace_once(SRC / "BitwardenActionExtension/Application/Support/Info.plist",
""com.8bit.bitwarden.extension-setup"", f""{BUNDLE_ID}.extension-setup"")
replace_once(SRC / "BitwardenWatchApp/Helpers/KeychainHelper.swift",
'"com.8bit.bitwarden.watch.kc"', f'"{BUNDLE_ID}.watch.kc"')
adapt_plists()
renamed = adapt_strings()
drawn = adapt_graphics(render_graphics())
illustrations = adapt_illustrations()
illustrations += adapt_tab_icons()
colors = adapt_colors()
hide_registration()
adapt_carousel()
server_entry()
vault_name_entry()
upstream_version_for_server()
without_bitwarden()
fonts = adapt_fonts()
(SRC / "LOKSI-NOTICE.txt").write_text(
"Loksi pour iOS, adaptation par Aleop.\n"
f"Basé sur bitwarden/ios {CONFIG['tag']} ({CONFIG['commit']}),\n"
f"SDK {CONFIG['sdk']['xcframework_url'].rsplit('/', 1)[-1]}, source bitwarden/sdk-internal "
f"{CONFIG['sdk']['source_commit']}.\n"
"GPL v3. Modifications : identifiants d'application et groupes, nom, icônes, logos,\n"
"serveur par défaut, domaines associés, retrait de Firebase Crashlytics.\n"
"Ni affilié ni approuvé par Bitwarden.\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, {drawn} jeux d'images remplacés, "
f"{colors} couleurs, {fonts} polices, {illustrations} illustrations")
changes()
generate()
def generate():
for spec in ("project-bwk.yml", "project-pm.yml"):
run(["mint", "run", "xcodegen", "--spec", spec], cwd=SRC)
# Tout ce que Loksi peut toucher. Le reste doit être octet pour octet l'archive amont.
ALLOWED = re.compile(
r"Configs/Local-bwpm\.xcconfig|LOKSI-NOTICE\.txt|project-(common|pm)\.yml|"
r"Bitwarden/Application/Support/(Info\.plist|Bitwarden\.entitlements|GoogleService-Info\.plist)|"
r"Bitwarden/Application/Support/AppIcon(-Dev|-Beta)?\.icon/.*|"
r"Bitwarden/Application/Support/Assets\.xcassets/(AppIcon(-Dev|-Beta)?\.appiconset|logoBitwarden\.imageset)/.*|"
r"BitwardenShared/UI/Platform/Application/Support/Images\.xcassets/logo\.imageset/.*|"
r"BitwardenShared/UI/Platform/Application/Support/Images\.xcassets/Images/(Illustrations|Autofill)/[a-z-]+\.imageset/[^/]+\.pdf|"
r"BitwardenResources/Illustrations\.xcassets/secure-devices\.imageset/[^/]+\.pdf|"
r"BitwardenResources/Icons\.xcassets/TabBar/[a-z-]+\.imageset/[^/]+\.pdf|"
r"Bitwarden/Application/Services/ErrorReporter/(ErrorReporterFactory|CrashlyticsErrorReporter)\.swift|"
r"BitwardenWatchApp/(ExtensionDelegate\.swift|GoogleService-Info\.plist|Helpers/KeychainHelper\.swift|Info\.plist)|"
r"BitwardenKit/Core/Platform/Models/Domain/EnvironmentURLData\.swift|"
r"BitwardenKit/Core/Platform/Services/AppInfoService\.swift|"
r"Bitwarden(Kit|Shared)/Core/Platform/Utilities/ExternalLinksConstants\.swift|"
r"BitwardenShared/UI/Platform/Settings/Settings/About/About(View|Action|Processor)\.swift|"
r"BitwardenShared/UI/Vault/Vault/VaultList/VaultListProcessor\.swift|"
r"BitwardenShared/UI/Auth/Landing/SelfHosted/(SelfHostedProcessor|SelfHostedView|LoksiVault|LoksiVaultTests)\.swift|"
r"BitwardenShared/Core/Platform/Utilities/LoksiUpstream\.swift|"
r"Configs/Bitwarden(Kit|Resources|Shared)-(Debug|Release)\.xcconfig|"
r"BitwardenShared/Core/Tools/Utilities/CredentialManagerFactory\.swift|"
r"BitwardenShared/Core/Platform/Services/(API/APIService|ClientBuilder|ServiceContainer)\.swift|"
r"BitwardenShared/UI/Platform/Settings/Settings/Other/OtherSettingsProcessor\.swift|"
r"BitwardenShared/Core/Platform/Services/EnvironmentService\.swift|"
r"BitwardenShared/UI/Auth/Utilities/RegionHelper\.swift|"
r"BitwardenShared/Core/Platform/Utilities/Constants\.swift|"
r"Bitwarden(AutoFill|Share|Action|Notification)Extension/Application/Support/Info\.plist|"
r"BitwardenWatchWidgetExtension/Application/Support/Info\.plist|"
r"BitwardenResources/Localizations/[^/]+\.lproj/Localizable\.strings(dict)?|"
r"BitwardenResources/Colors\.xcassets/.*\.colorset/Contents\.json|"
r"Bitwarden/Application/Support/Assets\.xcassets/(BackgroundColors|TintColors)/.*\.colorset/Contents\.json|"
r"BitwardenResources/Fonts/(DMSans-[A-Za-z]+\.ttf|Loksi-[A-Za-z]+\.ttf|OFL-Raleway\.txt)|"
r"BitwardenKit/UI/Platform/Application/(Appearance/StyleGuideFont|Appearance/UI|Views/BitwardenUITextView|"
r"Views/BitwardenStepper)\.swift|BitwardenShared/UI/Platform/Application/Support/Info\.plist|"
r"BitwardenShared/UI/Auth/(IntroCarousel/IntroCarouselView|Landing/LandingView|Landing/LandingState|Landing/LandingProcessor|AuthCoordinator)\.swift")
# Produits de xcodegen, de SwiftGen, de Sourcery, de LicensePlist et d'Xcode.
GENERATED = re.compile(
r"[^/]+\.xcodeproj/.*|Bitwarden\.xcworkspace/xcshareddata/swiftpm/Package\.resolved|"
r".*/Generated/.*|Bitwarden/Application/Support/Settings\.bundle/Acknowledgements.*|"
r"BitwardenKit/Core/Platform/Utilities/SDKVersionInfo\.swift|"
r".*\.xcworkspace/xcuserdata/.*")
def changes():
"""Échoue si un fichier hors des zones d'adaptation diffère de l'archive amont."""
status = git("status", "--porcelain", "--untracked-files=all", "--ignored=matching", "-z")
modified, added, removed = [], [], []
for entry in filter(None, status.split("\0")):
code, relative = entry[:2], entry[3:]
if GENERATED.fullmatch(relative):
continue
if not ALLOWED.fullmatch(relative):
raise RuntimeError(f"Modification hors périmètre ({code.strip()}) : {relative}")
(removed if "D" in code else added if code in ("??", "!!") else modified).append(relative)
REPORTS.mkdir(exist_ok=True)
(REPORTS / "ios-upstream-changes.json").write_text(
json.dumps({"modified": modified, "added": added, "removed": removed}, indent=2) + "\n")
print(f"{len(modified)} fichiers amont adaptés, {len(added)} ajoutés, {len(removed)} retirés, "
"aucun hors périmètre")
def simulator_udid():
"""Simulateur propre à Loksi, créé au besoin, pour ne gêner aucune autre session."""
devices = json.loads(subprocess.run(["xcrun", "simctl", "list", "devices", "-j"], capture_output=True,
text=True, check=True).stdout)["devices"]
for runtime, entries in devices.items():
for device in entries:
if device["name"] == SIMULATOR["name"] and device.get("isAvailable"):
return device["udid"]
return subprocess.run(["xcrun", "simctl", "create", SIMULATOR["name"], SIMULATOR["device_type"], SIMULATOR["runtime"]],
capture_output=True, text=True, check=True).stdout.strip()
def xcodebuild(log, *arguments):
"""xcodebuild sur le simulateur Loksi, journal complet dans .cache."""
command = ["xcodebuild", "-workspace", "Bitwarden.xcworkspace", "-scheme", "Bitwarden", "-configuration", "Debug",
"-destination", f"platform=iOS Simulator,id={simulator_udid()}", "-derivedDataPath", str(DERIVED),
"-skipPackagePluginValidation", *[str(a) for a in arguments]]
print("+", " ".join(command), flush=True)
env = dict(os.environ)
env.pop("CI", None) # lint-changes.sh ne se lance pas si CI est posé
with open(log, "w") as out:
return subprocess.run(command, cwd=SRC, env=env, stdout=out, stderr=subprocess.STDOUT).returncode
def fresh_product(app):
"""La compilation incrémentale garde ce qui n'est plus embarqué : le 03/10/2026, le
dossier Watch est resté dans l'app après le retrait de la montre. On repart d'une app vide."""
if app.exists():
shutil.rmtree(app)
def build():
log = CACHE / "ios-build.log"
fresh_product(APP)
if xcodebuild(log, "build"):
print(subprocess.run(["grep", "-E", "error:|BUILD FAILED", str(log)], capture_output=True, text=True).stdout[-6000:])
sys.exit(f"Compilation échouée, journal complet : {log}")
# Le script amont lint-changes.sh a passé SwiftLint et SwiftFormat sur les fichiers
# Swift modifiés par Loksi : son verdict doit être dans le journal.
if "All modified Swift files passed formatting and linting checks" not in log.read_text():
sys.exit(f"Lint amont des fichiers Loksi absent ou en échec, journal : {log}")
DIST.mkdir(parents=True, exist_ok=True)
target = DIST / "Loksi-simulator.app"
if target.exists():
shutil.rmtree(target)
# Les passes de tests injectent leurs bundles .xctest dans l'app de DerivedData,
# qui leur sert d'hôte : ils ne font pas partie de l'application livrée.
shutil.copytree(APP, target, symlinks=True, ignore=shutil.ignore_patterns("*.xctest"))
changes()
verify()
def binaries(bundle):
"""Exécutables Mach-O du paquet, frameworks et extensions compris."""
found = []
for path in bundle.rglob("*"):
if path.is_file() and not path.is_symlink():
with open(path, "rb") as handle:
if handle.read(4) in (b"\xcf\xfa\xed\xfe", b"\xca\xfe\xba\xbe"):
found.append(path)
return found
def entitlements(bundle):
"""Entitlements lus par le simulateur : section __TEXT,__entitlements de l'exécutable.
Une signature ad hoc n'en porte aucun (codesign -d rend un dictionnaire vide) : Xcode
les inscrit dans cette section pour les compilations simulateur.
"""
executable = bundle / plistlib.loads((bundle / "Info.plist").read_bytes())["CFBundleExecutable"]
archs = subprocess.run(["lipo", "-archs", executable], capture_output=True, text=True, check=True).stdout.split()
if len(archs) > 1: # binaire universel (montre) : les offsets sont relatifs à la tranche
thin = CACHE / "entitlements-slice"
subprocess.run(["lipo", "-thin", "arm64", "-output", thin, executable], check=True)
executable = thin
load = subprocess.run(["otool", "-l", executable], capture_output=True, text=True, check=True).stdout
match = re.search(r"sectname __entitlements\n\s+segname __TEXT\n.*?size (0x[0-9a-f]+)\n\s+offset (\d+)", load, re.S)
if not match:
return {}
size, offset = int(match.group(1), 16), int(match.group(2))
with open(executable, "rb") as handle:
handle.seek(offset)
return plistlib.loads(handle.read(size).rstrip(b"\0"))
def scan(paths, needles):
hits = set()
for path in paths:
data = path.read_bytes()
hits |= {needle for needle in needles if needle in data}
return hits
def verify():
app = DIST / "Loksi-simulator.app"
info = plistlib.loads((app / "Info.plist").read_bytes())
assert info["CFBundleIdentifier"] == BUNDLE_ID, "identifiant de l'application"
version = CONFIG["app_version"]
assert (info["CFBundleShortVersionString"], info["CFBundleVersion"]) == (version["marketing"], str(version["build"])), \
f"version de l'app : {info['CFBundleShortVersionString']} ({info['CFBundleVersion']})"
assert not version_problems(info["CFBundleShortVersionString"], int(info["CFBundleVersion"]), version["last_archived_build"]), \
"version de l'app hors règle"
assert info["CFBundleDisplayName"] == "Loksi" and info["CFBundleName"] == "Loksi", "nom affiché"
assert "bitwarden" in info["CFBundleURLTypes"][0]["CFBundleURLSchemes"], "schéma de retour SSO gardé"
assert not list(app.rglob("*.xctest")), "bundles de tests dans l'application"
assert not (app / "Watch").exists(), "app montre embarquée"
assert "target: BitwardenWatchApp" in git("show", "HEAD:project-pm.yml"), "canari : montre absente de l'amont"
bundles = {"app": app, **{p.name: p for p in app.rglob("*.appex")}, **{p.name: p for p in (app / "Watch").glob("*.app")}}
identifiers = {}
for name, bundle in bundles.items():
identifier = plistlib.loads((bundle / "Info.plist").read_bytes())["CFBundleIdentifier"]
assert identifier == BUNDLE_ID or identifier.startswith(BUNDLE_ID + "."), f"{name} : {identifier}"
identifiers[name] = identifier
groups, keychains = {}, {}
for name, bundle in bundles.items():
values = entitlements(bundle)
text = json.dumps(values)
assert "bitwarden" not in text.lower() and "8bit" not in text, f"entitlements Bitwarden dans {name}"
groups[name] = values.get("com.apple.security.application-groups", [])
keychains[name] = values.get("keychain-access-groups", [])
assert all(APP_GROUP in groups[name] for name in groups if name != "BitwardenWatchApp.app" and "Widget" not in name), \
f"groupe {APP_GROUP} absent d'un paquet : {groups}"
# Canari : la même lecture sur l'amont doit trouver les domaines Bitwarden.
upstream = git("show", "HEAD:Bitwarden/Application/Support/Bitwarden.entitlements")
assert "bitwarden.com" in upstream, "canari : entitlements amont illisibles"
executables = binaries(app)
forbidden = [b"FIRCrashlytics", b"FirebaseCore", b"GoogleAppMeasurement", BITWARDEN_TEAM.encode(), b"com.8bit.bitwarden"]
sdk = [path for path in executables if path.name.startswith("BitwardenSdk_")]
assert len(sdk) == 1, f"bibliothèque SDK embarquée : {sdk}"
found = scan([path for path in executables if path not in sdk], forbidden)
# Le SDK Rust, inchangé, journalise sous le sous-système os_log « com.8bit.bitwarden »
# (sdk-internal, crates/bitwarden-uniffi/src/lib.rs). Seule exception admise.
found |= scan(sdk, forbidden[:-1])
assert scan(sdk, forbidden[-1:]), "canari : sous-système os_log du SDK introuvable"
assert not found, f"éléments exclus présents : {sorted(f.decode() for f in found)}"
# Avis de dérivation : texte exact validé par Romain, en français et en anglais, dans
# les ressources de l'app. Canari : la même lecture ne le trouve pas dans l'amont figé.
resources = app / "Frameworks/BitwardenResources.framework"
for language, notice in ORIGIN_NOTICE.items():
table = plistlib.loads((resources / f"{language}.lproj/Localizable.strings").read_bytes())
assert table.get("LoksiOriginNotice") == notice, f"avis de dérivation {language}"
assert table.get("LoksiBasedOnBitwarden") == CONTACT_STRINGS["LoksiBasedOnBitwarden"][language], \
f"version de Bitwarden dans À propos ({language})"
assert table.get("WebVault") == WEB_VAULT_LABEL[language], f"libellé du coffre web ({language})"
assert ORIGIN_NOTICE["fr"] not in git("show", "HEAD:BitwardenResources/Localizations/fr.lproj/Localizable.strings"), \
"canari : l'avis de dérivation figure déjà dans l'amont"
# Nom de coffre (04/10/2026) : domaine des coffres et page produit dans le code. Canari :
# ni l'un ni l'autre dans l'amont figé.
assert scan(executables, [b"loksi.fr", LOKSI_PRODUCT.encode()]) == {b"loksi.fr", LOKSI_PRODUCT.encode()}, \
"domaine loksi.fr ou lien Découvrir Loksi absent"
assert "loksi.fr" not in git("show", "HEAD:BitwardenShared/UI/Auth/Landing/SelfHosted/SelfHostedProcessor.swift"), \
"canari : loksi.fr déjà dans l'amont"
# Source GPL (12/10/2026) : son adresse exacte dans le code, absente de l'amont figé.
source = CONFIG["links"]["source"].encode()
assert scan(executables, [source]), "adresse de la source GPL absente de l'application"
assert source.decode() not in git("show", "HEAD:BitwardenKit/Core/Platform/Utilities/ExternalLinksConstants.swift"), \
"canari : adresse de la source déjà dans l'amont"
# Plus de Bitwarden sauf obligation (09/10/2026) : aucun identifiant de paquet hors SDK,
# pas de User-Agent Bitwarden_Mobile. Canaris : l'amont figé a les deux.
ids = {plistlib.loads(path.read_bytes()).get("CFBundleIdentifier", "") for path in app.rglob("Info.plist")
if "BitwardenSdk_" not in str(path)}
assert not [i for i in ids if "bitwarden" in i.lower() or "8bit" in i], f"identifiant Bitwarden : {sorted(ids)}"
assert ".bitwarden-kit" in git("show", "HEAD:Configs/BitwardenKit-Debug.xcconfig"), "canari : identifiant amont"
assert not scan([path for path in executables if path not in sdk], [b"Bitwarden_Mobile"]), "User-Agent Bitwarden_Mobile"
assert "Bitwarden_Mobile" in git("show", "HEAD:BitwardenShared/Core/Platform/Services/ServiceContainer.swift"), \
"canari : User-Agent amont"
# Plus aucun lien vers bitwarden.com hors du SDK, qui n'est pas modifié. Canari : le
# fichier amont figé en contient.
assert not scan([path for path in executables if path not in sdk], [b"https://bitwarden.com/"]), \
"lien vers bitwarden.com dans l'application"
assert "https://bitwarden.com/help/" in git("show", "HEAD:BitwardenShared/Core/Platform/Utilities/ExternalLinksConstants.swift"), \
"canari : liens Bitwarden absents de l'amont"
# Le coffre d'Aleop n'est plus un défaut : son adresse ne doit plus être dans le code.
assert not scan(executables, [SERVER.encode()]), "adresse du coffre d'Aleop encore dans le code"
# « Nous contacter » : l'adresse exacte du support doit être dans le code, et pas dans
# le code amont figé (canari : le même balayage sur la source d'origine ne la trouve pas).
support = CONFIG["links"]["support"].encode()
assert scan(executables, [support]), "adresse du support absente de l'application"
# L'ancienne adresse, entrée du support client, ne doit plus être nulle part : ni dans le code
# ni dans les textes. Canari : le même balayage trouve la nouvelle dans les textes.
strings = [path for path in app.rglob("Localizable.strings")]
assert not scan(executables + strings, [b"support@aleop.eu"]), "support@aleop.eu encore dans l'application"
assert any(SUPPORT_ADDRESS in plistlib.loads(path.read_bytes()).get("LoksiEmailSupportMessage", "")
for path in strings), "canari : adresse du support absente des textes"
assert support.decode() not in git("show", "HEAD:BitwardenKit/Core/Platform/Utilities/ExternalLinksConstants.swift"), \
"canari : l'adresse du support figure déjà dans l'amont"
# Canaris : le même balayage doit trouver le SDK, le marqueur « adresse à saisir », et
# l'équipe Bitwarden dans le fichier amont qui la déclare.
present = scan(executables, [b"BitwardenSdk", UNSET_SERVER.encode()])
assert present == {b"BitwardenSdk", UNSET_SERVER.encode()}, f"canari du balayage : {present}"
assert scan([SRC / "Configs/Common-bwpm.xcconfig"], [BITWARDEN_TEAM.encode()]), "canari : équipe Bitwarden introuvable"
# SDK : la bibliothèque liée vient du xcframework dont le SHA-256 est épinglé.
artifacts = list((DERIVED / "SourcePackages/artifacts").rglob("BitwardenFFI.xcframework"))
assert len(artifacts) == 1, f"xcframework SPM : {artifacts}"
resolved = artifacts[0] / "ios-arm64_x86_64-simulator"
library = next(resolved.rglob("libbitwarden_uniffi.a"), None) or next(resolved.rglob("BitwardenFFI"), None)
assert library, "bibliothèque simulateur du SDK introuvable"
relative = library.relative_to(artifacts[0].parent)
with zipfile.ZipFile(XCFRAMEWORK) as archive:
pinned = hashlib.sha256(archive.read(str(relative))).hexdigest()
assert pinned == sha256(library), "SDK résolu par SPM différent du xcframework épinglé"
assert all(k.endswith("." + BUNDLE_ID) for k in keychains["app"]) and keychains["app"], "trousseau Loksi"
result = {"app": app.name, "bundle_identifiers": identifiers, "app_groups": groups, "keychain_groups": keychains,
"sdk_library": str(relative), "sdk_library_sha256": pinned,
"executable_sha256": sha256(app / info["CFBundleExecutable"])}
REPORTS.mkdir(exist_ok=True)
(REPORTS / "ios-app.json").write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
print("Vérifications de l'application réussies")
# Tests amont qui échouent, relevés le 29/09/2026 sur 6286 tests du plan Bitwarden-Unit.
# Tout échec en plus ou en moins fait tomber la commande tests.
EXPECTED_FAILURES = {
# Ils attendent le serveur US quand rien n'est enregistré : Loksi rend loksi.aleop.eu.
("EnvironmentServiceTests", "defaultUrls()"),
("EnvironmentServiceTests", "loadURLsForActiveAccount_noAccount()"),
("LandingProcessorTests", "test_perform_appeared_loadsRegion_noPreAuthUrls()"),
("RegionHelperTests", "test_loadRegion_nil()"),
("StartRegistrationProcessorTests", "test_perform_appeared_loadsRegion_noPreAuthUrls()"),
# Ils attendent le menu des régions (bitwarden.com, bitwarden.eu, auto-hébergé), retiré
# à la demande de Romain le 29/09/2026 : « expected non-nil value of type Alert ».
("LandingProcessorTests", "test_perform_regionPressed()"),
("LandingProcessorTests", "test_perform_regionPressed_fedrampGovRegionEnabled()"),
("LandingProcessorTests", "test_perform_regionPressed_fedrampGovRegionEnabled_staleConfig()"),
("RegionHelperTests", "test_presentRegionSelectorAlert_eu()"),
("RegionHelperTests", "test_presentRegionSelectorAlert_excludesInternal()"),
("RegionHelperTests", "test_presentRegionSelectorAlert_excludingRegions()"),
("RegionHelperTests", "test_presentRegionSelectorAlert_gov()"),
("RegionHelperTests", "test_presentRegionSelectorAlert_nil()"),
("RegionHelperTests", "test_presentRegionSelectorAlert_selfHosted()"),
("RegionHelperTests", "test_presentRegionSelectorAlert_us()"),
("StartRegistrationProcessorTests", "test_perform_regionTapped()"),
# Pas de serveur par défaut (29/09/2026) : sans adresse de coffre, Continuer ouvre sa
# saisie au lieu de poursuivre. Ces tests ne posent aucun serveur.
("LandingProcessorTests", "test_perform_continuePressed_withInvalidEmail()"),
("LandingProcessorTests", "test_perform_continuePressed_withValidEmailAndSpace()"),
("LandingProcessorTests", "test_perform_continuePressed_withValidEmailUppercased()"),
("LandingProcessorTests", "test_perform_continuePressed_withValidEmail_isRememberMeOn_false()"),
("LandingProcessorTests", "test_perform_continuePressed_withValidEmail_isRememberMeOn_true()"),
# Environnement : ils ajoutent une vraie notification locale. Sur un simulateur
# neuf l'autorisation est « NotDetermined », SpringBoard refuse (UNErrorDomain 2003)
# et le test s'arrête avant ses vérifications. Vu dans le journal du simulateur ;
# simctl privacy ne sait pas accorder les notifications.
("NotificationServiceTests", "test_messageReceived_loginRequest_differentAccount()"),
("NotificationServiceTests", "test_messageReceived_loginRequest_sameAccount()"),
("NotificationServiceTests", "test_messageReceived_loginRequest_sameAccount_notFound()"),
# Pas de demande de notifications sans push (02/10/2026) : ils attendent l'alerte
# d'explication puis la demande d'autorisation, retirées.
("VaultListProcessorTests", "test_perform_appeared_requestNotifications_denied()"),
("VaultListProcessorTests", "test_perform_appeared_requestNotifications_error()"),
("VaultListProcessorTests", "test_perform_appeared_requestNotifications_success()"),
# Pas de montre (03/10/2026) : il attend l'interrupteur « Se connecter à la montre ».
("OtherSettingsProcessorTests", "test_perform_loadInitialValues_success()"),
# Nom ou adresse du coffre (04/10/2026) : l'enregistrement exige qu'un Vaultwarden réponde
# sur /api/config, ce que ne font pas les adresses d'essai de ces tests.
("SelfHostedProcessorTests", "test_perform_saveEnvironment()"),
("SelfHostedProcessorTests", "test_perform_saveEnvironment_invalidURLs()"),
("SelfHostedProcessorTests", "test_perform_saveEnvironment_multipleURLs()"),
("SelfHostedProcessorTests", "test_perform_saveEnvironment_withCertificate()"),
}
# Tests amont qui tuent l'app hôte au lieu d'échouer, retirés du passage par -skip-testing.
# Mesuré le 30/09/2026 : 6 rapports ~/Library/Logs/DiagnosticReports/Bitwarden-*.ips du
# 29 et du 30/09, tous sur ce seul test. EXC_BREAKPOINT dans Array._checkSubscript, donc
# un indice hors limites : sans serveur l'alerte de compte existant ne vient pas et le test
# lit coordinator.alertShown[0] sur un tableau vide. Un XCTAssert échoue, ceci tue l'app,
# et macOS affichait « Bitwarden a quitté de manière imprévue » à chaque passage.
SKIPPED_TESTS = [
"BitwardenSharedTests/LandingProcessorTests/test_perform_continuePressed_matchingExistingAccount",
]
def tests():
results = CACHE / "ios-tests.xcresult"
if results.exists():
shutil.rmtree(results)
# Échecs attendus : le verdict se fait sur le résultat, pas sur le code de retour.
xcodebuild(CACHE / "ios-tests.log", "-testPlan", "Bitwarden-Unit", "-resultBundlePath", results,
*[f"-skip-testing:{test}" for test in SKIPPED_TESTS], "test")
summary = json.loads(subprocess.run(["xcrun", "xcresulttool", "get", "test-results", "tests", "--path", results],
capture_output=True, text=True, check=True).stdout)
total, failures = 0, set()
loksi_passed = 0
def walk(node, path):
nonlocal total, loksi_passed
if node.get("nodeType") == "Test Case":
total += 1
if node.get("result") == "Failed":
failures.add((path[-1] if path else "", node["name"]))
elif path and path[-1] == "LoksiVaultTests" and node.get("result") == "Passed":
loksi_passed += 1
return
for child in node.get("children", []):
walk(child, path + [node.get("name", "")])
for node in summary.get("testNodes", []):
walk(node, [])
REPORTS.mkdir(exist_ok=True)
(REPORTS / "ios-tests.json").write_text(json.dumps({"total": total, "failures": sorted(failures)}, indent=2) + "\n")
if total < 1000:
raise RuntimeError(f"Seulement {total} tests exécutés, journal : {CACHE / 'ios-tests.log'}")
# Un compte différent veut dire que les tests Loksi ont été sautés, pas qu'ils passent.
if loksi_passed != LOKSI_VAULT_TESTS:
raise RuntimeError(f"LoksiVaultTests : {loksi_passed} réussis, {LOKSI_VAULT_TESTS} attendus")
if failures != EXPECTED_FAILURES:
raise RuntimeError(f"Échecs inattendus : {sorted(failures - EXPECTED_FAILURES)}, "
f"attendus absents : {sorted(EXPECTED_FAILURES - failures)}")
print(f"{total} tests, {len(failures)} échecs, tous attendus")
# iPhone, signé par l'équipe Aleop (compte Apple Developer organisation payé le 01/10/2026).
# Identifiant d'équipe dans upstream.json (ios.apple_team.id), nulle part ailleurs. App
# complète, avec AutoFill, action, notifications et montre, groupes, trousseau et NFC.
# Restent retirés : aps-environment, le push n'a pas de relais propre à Loksi et n'est pas
# décidé ; le conteneur iCloud, qu'aucun code Swift de l'amont n'utilise (relevé le 01/10/2026).
#
# Du 29/09 au 01/10/2026, l'app passait par la Personal Team gratuite de Romain, réduite à
# l'app et au partage : Apple y refuse l'AutoFill (« The selected team does not have a
# program membership that is eligible for this feature »). Ce mode est retiré : relancé, il
# réserverait les identifiants sur le compte gratuit, comme pour eu.aleop.loksi (voir APP_GROUP).
DEVICE_SRC = CACHE / "ios-device"
DEVICE_APP = CACHE / "ios-device-derived/Build/Products/Debug-iphoneos/Bitwarden.app"
DEVICE_REMOVED = (r"\s*aps-environment\s*[^<]*",
r"\s*com\.apple\.developer\.ubiquity-container-identifiers\s*.*?")
def apple_team():
team = CONFIG["apple_team"]["id"]
if not team:
sys.exit("Identifiant d'équipe Aleop absent de upstream.json (ios.apple_team.id)")
return team
def signed_sources(target, team, release):
"""Copie des sources préparées, signée par l'équipe Aleop, push et iCloud retirés."""
if target.exists():
shutil.rmtree(target)
shutil.copytree(SRC, target, symlinks=True, ignore=shutil.ignore_patterns(".git", "*.xcodeproj"))
xcconfig = (LOCAL_XCCONFIG
.replace("DEVELOPMENT_TEAM =\n", f"DEVELOPMENT_TEAM = {team}\n")
.replace("CODE_SIGN_STYLE = Manual\nCODE_SIGN_IDENTITY = -\n", "CODE_SIGN_STYLE = Automatic\n"))
if not release:
# Sans Crashlytics, OSLogErrorReporter sert partout et, en Debug, s'arrête sur une
# assertion à chaque erreur signalée. Sur iPhone, sans aps-environment,
# l'inscription au push échoue à coup sûr et l'app plantait (rapport du
# 29/09/2026, 16h20). Drapeau prévu par l'amont pour couper cette assertion. En
# Release, BITWARDEN_FLAGS reste celui de l'amont (vide) : assertionFailure ne fait
# rien dans une compilation optimisée, et le menu de débogage n'a rien à y faire.
xcconfig += "BITWARDEN_FLAGS = DEBUG_MENU DISABLE_ASSERTION_FAILURE_ON_LOG_ERROR\n"
(target / "Configs/Local-bwpm.xcconfig").write_text(xcconfig)
entitlements = target / "Bitwarden/Application/Support/Bitwarden.entitlements"
text = entitlements.read_text()
for block in DEVICE_REMOVED:
text, count = re.subn(block, "", text, flags=re.S)
if count != 1:
raise RuntimeError(f"Entitlement amont modifié : {block}")
entitlements.write_text(text)
for spec in ("project-bwk.yml", "project-pm.yml"):
run(["mint", "run", "xcodegen", "--spec", spec], cwd=target)
def xcodebuild_signed(log, cwd, *arguments):
command = ["xcodebuild", *[str(a) for a in arguments]]
print("+", " ".join(command), flush=True)
env = dict(os.environ)
env.pop("CI", None)
with open(log, "w") as out:
result = subprocess.run(command, cwd=cwd, env=env, stdout=out, stderr=subprocess.STDOUT)
if result.returncode:
print(subprocess.run(["grep", "-E", "error:|FAILED", str(log)], capture_output=True, text=True).stdout[-6000:])
sys.exit(f"xcodebuild en échec, journal complet : {log}")
def device():
team = apple_team()
listing = CACHE / "devices.json"
subprocess.run(["xcrun", "devicectl", "list", "devices", "--json-output", listing], capture_output=True, check=True)
phones = [d for d in json.loads(listing.read_text())["result"]["devices"]
if d["hardwareProperties"].get("reality") == "physical"
and d["connectionProperties"].get("tunnelState") != "unavailable"]
if len(phones) != 1:
sys.exit(f"Un iPhone branché attendu, {len(phones)} trouvés")
phone = phones[0]
udid = phone["hardwareProperties"]["udid"]
signed_sources(DEVICE_SRC, team, release=False)
fresh_product(DEVICE_APP)
xcodebuild_signed(CACHE / "ios-device.log", DEVICE_SRC, "-workspace", "Bitwarden.xcworkspace", "-scheme", "Bitwarden",
"-configuration", "Debug", "-destination", f"id={udid}",
"-derivedDataPath", CACHE / "ios-device-derived", "-skipPackagePluginValidation",
"-allowProvisioningUpdates",
# Sans lui, xcodebuild n'inscrit pas l'iPhone dans une équipe payante : « Device
# isn't registered in your developer account », vu le 01/10/2026 sur l'équipe Aleop.
"-allowProvisioningDeviceRegistration", "build")
verify_signed(DEVICE_APP, team, "ios-device.json", distribution=False)
run(["xcrun", "devicectl", "device", "install", "app", "--device", udid, DEVICE_APP])
print(f"Loksi {CONFIG['app_version']['marketing']} ({CONFIG['app_version']['build']}) installé sur "
f"{phone['deviceProperties']['name']}, équipe {team}")
def signed_entitlements(bundle):
"""Entitlements de la signature réelle (codesign), ceux qu'iOS applique sur l'iPhone."""
out = subprocess.run(["codesign", "-d", "--entitlements", "-", "--xml", bundle],
capture_output=True, check=True).stdout
return plistlib.loads(out) if out.strip() else {}
def verify_signed(bundle_app, team, report_name, distribution):
"""Ce que le profil Apple a réellement accordé, paquet par paquet, avant installation ou envoi."""
bundles = {"app": bundle_app, **{p.name: p for p in bundle_app.rglob("*.appex")},
**{p.name: p for p in (bundle_app / "Watch").glob("*.app")}}
# App et 4 extensions : la montre est retirée (03/10/2026).
assert len(bundles) == 5 and not (bundle_app / "Watch").exists(), f"5 paquets attendus : {sorted(bundles)}"
report = {}
for name, bundle in bundles.items():
info = plistlib.loads((bundle / "Info.plist").read_bytes())
identifier = info["CFBundleIdentifier"]
assert identifier == BUNDLE_ID or identifier.startswith(BUNDLE_ID + "."), f"{name} : {identifier}"
values = signed_entitlements(bundle)
assert values.get("com.apple.developer.team-identifier") == team, f"{name} : équipe {values.get('com.apple.developer.team-identifier')}"
text = json.dumps(values)
assert "bitwarden" not in text.lower() and "8bit" not in text, f"entitlements Bitwarden dans {name}"
assert "aps-environment" not in values, f"{name} : push signé alors qu'il n'est pas décidé"
# Profil de développement : débogueur autorisé. Profil App Store : interdit, sinon
# App Store Connect refuse l'envoi.
assert values.get("get-task-allow", False) is (not distribution), f"{name} : get-task-allow"
report[name] = {"identifier": identifier, "entitlements": values}
app = report["app"]["entitlements"]
assert APP_GROUP in app.get("com.apple.security.application-groups", []), "groupe Loksi de l'app"
assert f"{team}.{BUNDLE_ID}" in app.get("keychain-access-groups", []), "trousseau Loksi de l'app"
autofill = "com.apple.developer.authentication-services.autofill-credential-provider"
extension = report["BitwardenAutoFillExtension.appex"]["entitlements"]
assert app.get(autofill) is True and extension.get(autofill) is True, "AutoFill non accordé par le profil"
assert f"{team}.{BUNDLE_ID}" in extension.get("keychain-access-groups", []), "trousseau de l'extension AutoFill"
assert APP_GROUP in extension.get("com.apple.security.application-groups", []), "groupe de l'extension AutoFill"
# Canari : la même lecture sur l'app du simulateur, signée ad hoc, ne rend aucune équipe.
simulator = DIST / "Loksi-simulator.app"
if simulator.exists():
assert "com.apple.developer.team-identifier" not in signed_entitlements(simulator), \
"canari : la lecture de signature voit une équipe dans l'app ad hoc"
REPORTS.mkdir(exist_ok=True)
(REPORTS / report_name).write_text(json.dumps({"team": team, "distribution": distribution, "bundles": report},
indent=2, default=str) + "\n")
print(f"Signature vérifiée : {len(bundles)} paquets, équipe {team}, AutoFill accordé")
ARCHIVE_SRC = CACHE / "ios-archive"
ARCHIVE = CACHE / "Loksi.xcarchive"
def archive():
"""Archive Release et .ipa App Store signés par l'équipe Aleop, dans ../dist/ios. Rien n'est
envoyé : destination « export », l'envoi à TestFlight se fait à part, sur accord de Romain."""
check_version()
team = apple_team()
signed_sources(ARCHIVE_SRC, team, release=True)
if ARCHIVE.exists():
shutil.rmtree(ARCHIVE)
xcodebuild_signed(CACHE / "ios-archive.log", ARCHIVE_SRC, "-workspace", "Bitwarden.xcworkspace", "-scheme", "Bitwarden",
"-configuration", "Release", "-destination", "generic/platform=iOS",
"-derivedDataPath", CACHE / "ios-archive-derived", "-skipPackagePluginValidation",
"-allowProvisioningUpdates", "-archivePath", ARCHIVE, "archive")
options = CACHE / "ExportOptions.plist"
options.write_bytes(plistlib.dumps({"method": "app-store-connect", "destination": "export", "teamID": team,
"signingStyle": "automatic", "uploadSymbols": True,
"manageAppVersionAndBuildNumber": False}))
export = DIST / "Loksi-appstore"
if export.exists():
shutil.rmtree(export)
xcodebuild_signed(CACHE / "ios-export.log", CACHE, "-exportArchive", "-archivePath", ARCHIVE, "-exportPath", export,
"-exportOptionsPlist", options, "-allowProvisioningUpdates")
ipas = list(export.glob("*.ipa"))
assert len(ipas) == 1, f"un .ipa attendu : {ipas}"
unpacked = CACHE / "ios-ipa"
if unpacked.exists():
shutil.rmtree(unpacked)
with zipfile.ZipFile(ipas[0]) as ipa:
ipa.extractall(unpacked)
# zipfile ne garde pas les droits d'exécution : codesign lit quand même la signature.
app = next((unpacked / "Payload").glob("*.app"))
info = plistlib.loads((app / "Info.plist").read_bytes())
version = CONFIG["app_version"]
assert (info["CFBundleShortVersionString"], info["CFBundleVersion"]) == (version["marketing"], str(version["build"])), \
f"version de l'archive : {info['CFBundleShortVersionString']} ({info['CFBundleVersion']})"
verify_signed(app, team, "ios-appstore.json", distribution=True)
# Canari : la même lecture sur l'app de développement voit get-task-allow.
if DEVICE_APP.exists():
assert signed_entitlements(DEVICE_APP).get("get-task-allow") is True, "canari : get-task-allow illisible"
# Le build archivé ne resservira pas : il devient le plancher du prochain.
upstream = MOBILE / "upstream.json"
text = upstream.read_text()
old = f'"last_archived_build": {version["last_archived_build"]},'
if text.count(old) != 1:
raise RuntimeError("last_archived_build introuvable dans upstream.json")
upstream.write_text(text.replace(old, f'"last_archived_build": {version["build"]},'))
print(f"Loksi {version['marketing']} ({version['build']}) prêt pour App Store Connect : {ipas[0]}, rien d'envoyé. "
f"Build {version['build']} inscrit comme dernier archivé : monter build avant la prochaine archive")
def install():
udid = simulator_udid()
subprocess.run(["xcrun", "simctl", "boot", udid], capture_output=True)
run(["xcrun", "simctl", "install", udid, DIST / "Loksi-simulator.app"])
run(["xcrun", "simctl", "launch", udid, BUNDLE_ID])
print(f"Loksi lancé sur {SIMULATOR['name']} ({udid})")
if __name__ == "__main__":
commands = {"fetch": fetch, "prepare": prepare, "generate": generate, "changes": changes, "build": build,
"verify": verify, "tests": tests, "install": install,
"device": device, "archive": archive}
if len(sys.argv) != 2 or sys.argv[1] not in commands:
sys.exit(__doc__)
commands[sys.argv[1]]()